[英]How to save video capture in mp4 format with opencv python
伙計們,我正在使用以下代碼使用 opencv 和 python 捕獲桌面視頻:
import numpy as np
import cv2
from mss import mss
from PIL import Image
bounding_box = {'top': 100, 'left': 0, 'width': 400, 'height': 300}
sct = mss()
while True:
sct_img = sct.grab(bounding_box)
cv2.imshow('screen', np.array(sct_img))
if(cv2.waitKey(1) & 0xFF) == ord('q'):
cv2.destroyAllWindows()
break
我希望能夠以 mp4 格式保存此捕獲,我該怎么做?
它應該像這樣工作。
import numpy as np
import cv2
from mss import mss
from PIL import Image
bounding_box = {'top': 100, 'left': 0, 'width': 400, 'height': 300}
sct = mss()
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))
while True:
sct_img = sct.grab(bounding_box)
out.write(np.array(sct_img))
cv2.imshow('screen', np.array(sct_img))
if(cv2.waitKey(1) & 0xFF) == ord('q'):
cv2.destroyAllWindows()
break
官方文檔在Getting Started with Videos中展示了示例
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
frame = cv.flip(frame, 0)
# write the flipped frame
out.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()
首先,您必須使用 4 個字符的代碼設置編解碼器。 有帶有代碼的頁面fourcc.org 。
不同的系統可能使用不同的編解碼器——主要是DIVX
、 XVID
、 MJPG
、 X264
、 WMV1
、 WMV2
。
fourcc = cv.VideoWriter_fourcc(*'XVID')
接下來,您必須設置文件名和擴展名、 FPS
、寬度、高度
out = cv.VideoWriter('output.avi', fourcc, 20.0, (400, 300))
某些編解碼器不適用於某些擴展 - 您可能需要檢查不同的組合( .avi
、 .mp4
、 .mkv
、 .mov
等)
如果圖像有400x300
而你想要視頻800x600
然后設置VideoWriter(..., (800, 600))
但你還必須在寫入之前調整每一幀的大小因為VideoWriter
不會自動調整它的大小 - 它跳過幀(沒有錯誤)並且最后它創建空文件(~4kb)。
frame = cv2.resize(frame, (800, 600))
out.write(frame)
VideoWriter(.., 20.0, ...)
設置20 FPS
(每秒幀數),但它不是寫入速度,而是視頻播放器必須以多快的速度顯示它的信息。
如果您每秒創建 20 幀,那么播放器將以正確的速度顯示它。 如果您每秒創建 10 幀,那么播放器的顯示速度將提高 2 倍。 如果你每秒創建 40 幀,那么播放器將以一半的速度顯示它。
它使用程序FFMPEG ,您可以看到在系統控制台/終端中運行的編解碼器列表
ffmpeg -codecs
或在源代碼中(帶有 4 個字符的代碼)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.