10/17/2018

修訂 (OpenCV) cv.VideoCapture 的參考範例

opencv 上的參考範例
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('vtest.avi')  
while(cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # 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) & 0xFF == ord('q'):
        break  
cap.release()
cv.destroyAllWindows()

github 上的 vtest.avi 無法使用,所以以下將改用此處的 drop.avi
當程式讀到檔案的最後,執行 gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) 會出現錯誤
error: ..\..\..\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor
看了 stackoverflow 上的說明,還是不行。只好找出 cv.VideoCapture 中,read() 的說明和使用
修訂後的參考範例,播放的影片會跳出一個視窗 (Anaconda 3-5.2.0, OpenCV 3.1.0)
import cv2 as cv
cap = cv.VideoCapture('drop.avi')

while(cap.isOpened()):
    # Capture frame-by-frame
    # cap.read() returns a bool (True/False). 
    # If frame is read correctly, it will be True. 
    # ret: true or false
    # time in milliseconds. (千分之一秒)
    cv.waitKey(120)
    ret, frame = cap.read()
    # Our operations on the frame come here
    if ret:
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        # Display the resulting frame
        cv.imshow('frame', gray)
    else:
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
也可以在 Jupyter Notebook 中呈現所有的圖片
import cv2 as cv
import matplotlib.pyplot as plt
from skimage import io
cap = cv.VideoCapture('drop.avi') 
while(cap.isOpened()):
    # Capture frame-by-frame
    # cap.read() returns a bool (True/False).
    # If frame is read correctly, it will be True.
    ret, frame = cap.read()
    # ret: true or false
    # Our operations on the frame come here
    if ret:
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        io.imshow(gray)
        plt.show()
    else:
        break 
# When everything done, release the capture
cap.release()

沒有留言:

張貼留言