gpt4 book ai didi

python - VideoWriter 输出损坏的视频文件

转载 作者:行者123 更新时间:2023-12-02 15:21:43 26 4
gpt4 key购买 nike

这是我保存 web_cam 流的代码。它正在工作,但输出视频文件的问题。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)

# write the flipped frame
out.write(frame)

cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

最佳答案

这是将帧保存到视频文件中的一些简单代码。我建议创建另一个线程来获取自 cv2.VideoCapture.read() 以来的帧正在阻塞。这可能很昂贵并导致延迟,因为主线程必须等待直到获得帧。通过将此操作放入一个单独的线程中,该线程只专注于在主线程中抓取帧和处理/保存帧,由于减少了 I/O 延迟,它显着提高了性能。您也可以尝试使用其他编解码器,但使用 MJPG 应该是安全的,因为它内置于 OpenCV 中。

from threading import Thread
import cv2

class WebcamVideoWriter(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.capture = cv2.VideoCapture(src)

# Default resolutions of the frame are obtained (system dependent)
self.frame_width = int(self.capture.get(3))
self.frame_height = int(self.capture.get(4))

# Set up codec and output video settings
self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))

# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()

def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()

def show_frame(self):
# Display frames in main program
if self.status:
cv2.imshow('frame', self.frame)

# Press Q on keyboard to stop recording
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
self.output_video.release()
cv2.destroyAllWindows()
exit(1)

def save_frame(self):
# Save obtained frame into video output file
self.output_video.write(self.frame)

if __name__ == '__main__':
webcam_videowriter = WebcamVideoWriter()
while True:
try:
webcam_videowriter.show_frame()
webcam_videowriter.save_frame()
except AttributeError:
pass

关于python - VideoWriter 输出损坏的视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60052453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com