简体   繁体   English

Python:使用python在OpenCV中测试视频

[英]Python : Testing Video in OpenCV using python

I just installed opencv3 on my macOS sierra 10.12.3. 我刚刚在macOS sierra 10.12.3上安装了opencv3。 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. 我的python版本是2.7。
I cannot figure out the problem. 我无法弄清楚问题。 Can anybody help me with the issue? 有人可以帮我解决这个问题吗? My python code is: 我的python代码是:

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. 我对ffmpeg格式有一些问题。 However, it shows the video but at the end still throws this exception. 但是,它显示了视频,但最后仍然抛出此异常。

That's because at the end of video, frame1 is empty. 这是因为在视频末尾, frame1为空。 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 您可以检查cv2.VideoCapture()函数是否正常工作

maybe your OpenCV doesn't support ffmpeg 也许您的OpenCV不支持ffmpeg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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