简体   繁体   中英

Python : Testing Video in OpenCV using python

I just installed opencv3 on my macOS sierra 10.12.3. I tried some examples and it worked out but when I try the following example it throws me some exceptions. My python version is 2.7.
I cannot figure out the problem. Can anybody help me with the issue? My python code is:

import cv2
import numpy as np
cap = cv2.VideoCapture("vtest.avi")

ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255

while(1):
    ret, frame2 = cap.read()
    next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

    flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

    mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
    hsv[...,0] = ang*180/np.pi/2
    hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
    rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)

    cv2.imshow('frame2',rgb)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    elif k == ord('s'):
        cv2.imwrite('opticalfb.png',frame2)
        cv2.imwrite('opticalhsv.png',rgb)
    prvs = next

cap.release()
cv2.destroyAllWindows()

The error message is:

    OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /tmp/opencv3-20170324-1646-1ehj5xu/modules/imgproc/src/color.cpp, line 9748
Traceback (most recent call last):
  File "/Users/Rouzbeh/BoxSync/Spring2017/TrafficProject/test/test.py", line 6, in <module>
    prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
cv2.error: /tmp/opencv3-20170324-1646-1ehj5xu/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor

Update :
I had some problem with ffmpeg formatting. However, it shows the video but at the end still throws this exception.

That's because at the end of video, frame1 is empty. You should do:

while(1):
    ret, frame2 = cap.read()
    if not ret:
        break
    next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
    # rest of code here
    pass    
cap = cv2.VideoCapture("vtest.avi")
print cap.isOpened()

you can check cv2.VideoCapture() function Working properly

maybe your OpenCV doesn't support ffmpeg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM