lundi 22 mai 2023

How can I create a random pattern flashing at specific frequency in Python for GIF creation?

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:

Output gif with 50% sparsity

Aucun commentaire:

Enregistrer un commentaire