您好,登錄后才能下訂單哦!
python利用opencv實現(xiàn)保存、播放視頻?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
1.首先創(chuàng)建一個VideoCapture對象,它的參數(shù)包含兩種:
3.釋放捕捉物。
import numpy as np import cv2 as cv cap = cv.VideoCapture(0) if not cap.isOpened(): print("Cannot open camera") exit() while True: # Capture frame-by-frame ret, frame = cap.read() # if frame is read correctly ret is True if not ret: print("Can't receive frame (stream end?). Exiting ...") break # Our operations on the frame come here gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # Display the resulting frame cv.imshow('frame', gray) if cv.waitKey(1) == ord('q'): break # When everything done, release the capture cap.release() cv.destroyAllWindows()
其他:
cap.read()
返回布爾值,如果frame讀取正確,為True,可以通過這個值判斷視頻是否已經(jīng)結(jié)束。cap.isOpened()
來檢查其是否被初始化,如果為True那是最好,如果不是,可以使用cap.open()
來嘗試打開它。cap.get(propId)
的方式獲取視頻的一些屬性,如幀的寬度,幀的高度,幀速等。propId是0-18的數(shù)字,每個數(shù)字代表一個屬性,對應(yīng)關(guān)系見底部附錄。cap.set(3,320), cap.set(4,240)
。從文件中播放視頻
代碼和從相機中捕獲視頻基本相同,不同之處在于傳入VideoCapture的參數(shù),此時傳入視頻文件的名稱。
在顯示每一幀的時候,可以使用cv2.waitKey()
設(shè)置適當?shù)臅r間,如果值很小,視頻將會很快。正常情況下,25ms就ok。
import numpy as np import cv2 cap = cv2.VideoCapture('vtest.avi') while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
保存視頻
1.創(chuàng)建一個VideoWriter 對象,指定如下參數(shù):
2.FourCC code傳遞有兩種方式:
3.FourCC是一個用于指定視頻編解碼器的4字節(jié)代碼。
import numpy as np import cv2 cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 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()
看完上述內(nèi)容,你們掌握python利用opencv實現(xiàn)保存、播放視頻的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。