python利用opencv實現保存、播放視頻?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
1.首先創建一個VideoCapture對象,它的參數包含兩種:
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,可以通過這個值判斷視頻是否已經結束。cap.isOpened()
來檢查其是否被初始化,如果為True那是最好,如果不是,可以使用cap.open()
來嘗試打開它。cap.get(propId)
的方式獲取視頻的一些屬性,如幀的寬度,幀的高度,幀速等。propId是0-18的數字,每個數字代表一個屬性,對應關系見底部附錄。cap.set(3,320), cap.set(4,240)
。從文件中播放視頻
代碼和從相機中捕獲視頻基本相同,不同之處在于傳入VideoCapture的參數,此時傳入視頻文件的名稱。
在顯示每一幀的時候,可以使用cv2.waitKey()
設置適當的時間,如果值很小,視頻將會很快。正常情況下,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.創建一個VideoWriter 對象,指定如下參數:
2.FourCC code傳遞有兩種方式:
3.FourCC是一個用于指定視頻編解碼器的4字節代碼。
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()
看完上述內容,你們掌握python利用opencv實現保存、播放視頻的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。