我正在尝试生成如下所示模式的视频,该视频使用python中的OpenCV水平移动。
我以以下方式编写。视频文件已生成,没有任何错误,但是在任何视频播放器中均未打开
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()
答案 0 :(得分:1)
当VideoWriter
需要彩色图像时,使用单通道灰度图像是一个问题。可以使用标志isColor=False
来解决此问题。
此外,由于图像的类型为uint8
,而y
最多只能显示2,因此看起来像是黑色视频,而不是您显示的图像。您可以将y
乘以y[j]*127
以达到0-255的整个范围。以下应该起作用:
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()