0

I am trying to write a code that creates a random pattern flashing (twinkling) at a specific frequency. Below is the code I am using, but the problem is that, different frequencies (frame rates) that I set for the pattern to flash will show the same frame rate within ImageJ (9 fps). Is it a code problem or display limitation? Would appreciate any help!

import numpy as np
import imageio

def create_twinkling_gif(frequency, duration, sparsity, output_path):
    frame_duration = 1 / frequency
    total_frames = int(duration * frequency)
    num_sparsity_pixels = int(sparsity * 256 * 256)

    # Create a white background
    background = np.ones((256, 256), dtype=np.uint8) * 255

    # Generate a fixed random pattern
    pixel_values = np.random.random((256, 256))
    sparsity_indices = np.random.choice(256 * 256, num_sparsity_pixels, replace=False)
    pixel_values.ravel()[sparsity_indices] = 1

    # Create the on and off frames based on the fixed pattern on white background
    on_frame = np.where(pixel_values == 1, 0, background).astype(np.uint8)
    off_frame = background

    frames = []
    for frame_num in range(total_frames):
        if frame_num % 2 == 0:
            frames.append(on_frame)
        else:
            frames.append(off_frame)

    # Save the frames as a GIF using imageio
    imageio.mimsave(output_path, frames, duration=frame_duration)

# Set the parameters for the twinkling GIFs
frequency = 60  # Hz
duration = 5  # seconds
step_size = 0.05

# Generate GIFs for different sparsity values
for i in range(21):
    sparsity = i * step_size
    output_path = f"twinkling_{sparsity:.2f}.gif"
    create_twinkling_gif(frequency, duration, sparsity, output_path)

Output gif with 50% sparsity:

enter image description here

num3ri
  • 822
  • 16
  • 20
  • a 60 fps gif? that's challenging. why don't you try this in a different program, if you suspect imagej? – Christoph Rackwitz May 22 '23 at 10:43
  • If you loop the presentation, you only need two images. The animation rate (speed of presentation) of a stack in ImageJ can be set to your liking (Image>>Stacks>>Animation>>Animation Options). – Herbie May 22 '23 at 11:15
  • @ChristophRackwitz I am not very familiar, do you have any programs to suggest? (btw thanks for the comment) – Fatemeh DND Jun 01 '23 at 01:30

0 Answers0