我想在cv2.VideoWriter不保存視頻的情況下撰寫視頻后閱讀視頻。
例如:
video = cv2.VideoWriter('using.mp4', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)
現在,在寫完這個cv2.VideoWriter物件之后,是否可以像 一樣讀取它video.read(),但是因為它read()是一個函式,cv2.VideoCapture它會拋出一個錯誤
Exception has occurred: AttributeError
'cv2.VideoWriter' object has no attribute 'read'
那么,有沒有可能的閱讀方式cv2.VideoWriter?
uj5u.com熱心網友回復:
從視頻寫入器讀取幀的另一種方法是將幀保存在串列中,而不是將每一幀保存在回圈中。完成后,您可以將它們寫在回圈之外并將保存效果為 video.read()
video = cv2.VideoWriter('using.mp4', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)
for frame in frames:
writer.write(frame)
for frame in frames:
# do other stuff here
詳細示例(注意我更改了fourcc - 你的示例對我不起作用)
import cv2
def cam_test(port: int = 0) -> None:
frames = []
cap = cv2.VideoCapture(port)
if not cap.isOpened(): # Check if the web cam is opened correctly
print("failed to open cam")
else:
print('cam opened on port {}'.format(port))
for i in range(10 ** 10):
success, cv_frame = cap.read()
if not success:
print('failed to capture frame on iter {}'.format(i))
break
frames.append(cv_frame)
cv2.imshow('Input', cv_frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
# Now you have the frames at hand
if len(frames) > 0:
# if you want to write them
size = (frames[0].shape[1], frames[0].shape[0])
video = cv2.VideoWriter(
filename='using.mp4',
fourcc=cv2.VideoWriter_fourcc(c1='m', c2='p', c3='4', c4='v'),
fps=10,
frameSize=size
)
for frame in frames:
video.write(frame)
# and to answer your question, you wanted to do video.read() which would have gave you frame by frame
for frame in frames:
pass # each iteration is like video.read() if video.read() was possible
return
if __name__ == '__main__':
cam_test()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432789.html
