使用opencv加载视频

时间:2018-04-10 06:10:53

标签: python opencv

我是Python和OpenCV的初学者,目前我遇到了一个问题。我试图加载视频,但后来收到错误。

import numpy as np
import cv2

car_cascade = cv2.CascadeClassifier('project11.xml')
cap = cv2.VideoCapture('Crop_DownResolution.mp4')

def car_detection():
    while (cap.isOpened()):
        _ , img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        cars = car_cascade.detectMultiScale(gray, 1.2, 5)
        cv2.line(img,(120,260),(380,260),(0,0,255),5)

        for (x,y,w,h) in cars:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]

            if (y+h)>260:
                collision_warming = 1
                print('warning')
            else:
                collision_warning = 0

        cv2.imshow('img',img)
        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break

    cap.release()
    cv2.destroyAllWindows()

但是当我运行代码时,我在视频播放完成时出现了这个错误。

Traceback (most recent call last):
File "C:\Users\littl\Desktop\Presentation\Project Video.py", line 33, in 
<module>
car_detection()
File "C:\Users\littl\Desktop\Presentation\Project Video.py", line 10, in 
car_detection
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: C:\projects\opencv- 
python\opencv\modules\imgproc\src\color.cpp:11111: error: (-215) scn == 3 || 
scn == 4 in function cv::cvtColor

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

此错误可能是因为视频文件不在工作目录中。我建议你提供视频的完整路径。

cap = cv2.VideoCapture('path/to/where/video/is/Crop_DownResolution.mp4')