Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Moving 2D Sinusoidal Pattern

I am trying to generate a video of a pattern as shown below which moves horizontally using OpenCV in python.

2-D sinusoidal Patter

I have written it in the following way. The video file is generated without any errors but the file doesn't open in any video players

        import cv2
        import numpy as np
        from cv2 import VideoWriter, VideoWriter_fourcc

        video = VideoWriter('_sine_pattern_gen_'+str(60)+'_fps.avi', VideoWriter_fourcc(*'MP42'), 60, (346, 260))

        x = np.arange(346)  # generate 1-D sine wave of required period 
        y = np.sin(2 * np.pi * x / 20) 

        y += max(y) # offset sine wave by the max value to go out of negative range of sine 

        frame = np.array([[y[j] for j in range(346)] for i in range(260)], dtype='uint8') # create 2-D array of sine-wave

        for _ in range(0, 346):
            video.write(frame)
            shifted_frame =  np.roll(frame, 2, axis=1) # roll the columns of the sine wave to get moving effect
            frame = shifted_frame 

        cv2.destroyAllWindows()
        video.release()
like image 676
Ashish Rao M Avatar asked Mar 09 '26 17:03

Ashish Rao M


1 Answers

This is an issue with using a single-channel grayscale image when VideoWriter is expecting a color image. This can be fixed by using the flag isColor=False.

Also, since the images are type uint8 and y only goes up to 2, this will look like a black video instead of the image you show. You can scale y to go the full 0-255 range by multiplying y[j]*127. The following should work:

import cv2
import numpy as np
from cv2 import VideoWriter, VideoWriter_fourcc

fname = '_sine_pattern_gen_'+str(60)+'_fps.avi'
video = VideoWriter(fname, VideoWriter_fourcc(*'MP42'), 60, (346, 260), isColor=False)

x = np.arange(346)  # generate 1-D sine wave of required period 
y = np.sin(2 * np.pi * x / 20)

y += max(y) # offset sine wave by the max value to go out of negative range of sine 

frame = np.array([[y[j]*127 for j in range(346)] for i in range(260)], dtype=np.uint8) # create 2-D array of sine-wave

for _ in range(0, 346):
    video.write(frame)
    shifted_frame =  np.roll(frame, 2, axis=1) # roll the columns of the sine wave to get moving effect
    frame = shifted_frame 

video.release()
like image 191
A Kruger Avatar answered Mar 11 '26 05:03

A Kruger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!