import cv2
import numpy as np
import time
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
img = np.zeros((640,480))
center_x = 0
center_y = 256
videoFile1 = 'D:/Python/6. Const_Speed/sample1.mp4'
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('SaveVideo2.avi', fourcc, 20.0, (640, 480))
while True:
img = np.zeros((640, 480))
img = cv2.circle(img, (center_x, center_y), 20, 120, -1)
cv2.imshow('img', img)
out.write(img)
center_x += 3
time.sleep(1/30)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
out.release()
cv2.destroyAllWindows()
我想录制一个圆圈从屏幕左侧匀速移动到右侧的视频。上面的代码运行没有错误,但结果视频是空的,只有黑屏。
我试过的
您的代码存在三个问题。
问题#1:
如果你要创建.avi
,我建议你使用MJPG
.
问题#2:
您需要VideoWriter
仔细定义类
当你定义尺寸时,它应该是frame_width
和frame_height
例如,如果你想创建一个 size 的视频(640, 480)
,你需要VideoWriter
用(480, 640)
out = cv2.VideoWriter('SaveVideo2.avi', fourcc, 20.0, (480, 640))
此外,您正计划创建一个灰度视频,因此您需要初始化isColor
为False
out = cv2.VideoWriter('SaveVideo2.avi', fourcc, 20.0, (480, 640), isColor=False)
问题#3:
如果要创建黑色图像,则需要定义其类型:
while True:
img = np.zeros((640, 480), dtype=np.uint8)
如果您解决问题,结果将是:
代码:
import cv2
import numpy as np
import time
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
img = np.zeros((640, 480))
center_x = 0
center_y = 256
videoFile1 = 'video.mp4'
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('SaveVideo2.avi', fourcc, 20.0, (480, 640), isColor=False)
while True:
img = np.zeros((640, 480), dtype=np.uint8)
img = cv2.circle(img, (center_x, center_y), 20, 120, -1)
cv2.imshow('img', img)
out.write(img)
center_x += 3
time.sleep(1/30)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
out.release()
cv2.destroyAllWindows()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句