我尝试用Python录制视频。运行下面的代码创建一个 .mp4 文件,但大小为 0KB,当我打开时,出现数据已损坏且无法打开的错误。我尝试使用 VLC、媒体播放器和我在 Windows 11 上获得的所有其他工具打开。也尝试了互联网上可用的所有工具,每次都是同样的问题
import cv2
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1280)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter('recording.mp4', fourcc, 30.0, (1280, 720))
recording = False
while True:
ret, frame = cap.read()
if ret:
print('working')
cv2.imshow("video", frame)
if recording:
writer.write(frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('r'):
recording = not recording
print(f'recording: {recording}')
# Release the video capture and writer objects
cap.release()
writer.release()
cv2.destroyAllWindows()
您正在手动设置尺寸,但相机可能无法在该分辨率下工作。
要解决此问题,您可以手动将分辨率设置为 1280x720,但不要对捕获结果进行硬编码,而是从相机中检索它
这样,如果相机在所需的分辨率下工作良好,如果不是,它将在默认分辨率下工作。
import cv2
cap = cv2.VideoCapture(0)
# set the camera to 1280x720
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1280)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720)
# but here get the actual resolution
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)
size = (width, height)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# then use here the actual resolution instead of the hardcoded one
writer = cv2.VideoWriter('recording.mp4', fourcc, 30.0,(width,height))
recording = False
while True:
ret, frame = cap.read()
if ret:
print('working')
cv2.imshow("video", frame)
if recording:
writer.write(frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('r'):
recording = not recording
print(f'recording: {recording}')
# Release the video capture and writer objects
cap.release()
writer.release()
cv2.destroyAllWindows()