简体   繁体   中英

in <module> gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)?

I am trying to make an car detector/classifier with cv2 i have a .xml file i downloaded from github:https://gist.github.com/199995/37e1e0af2bf8965e8058a9dfa3285bc6 and when ever i run my code i get

Traceback (most recent call last):

  File "C:\Users\user1\Downloads\Stuff\Python\cascades\Car_classification.py", line 13, in <module>
    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

and my code is:

import cv2
import numpy as np

cap = cv2.VideoCapture('car.jpg')

font = cv2.FONT_HERSHEY_TRIPLEX

harcascade = cv2.CascadeClassifier("cars.xml")

while True:
    ret,frames = cap.read()

    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
    
    cars = harcascade.detectMultiScale(gray, 1.1 , 2)
    
    for (x,y,w,h) in cars:
        cv2.rectangle(frames,(x,y),(x+w,y+h),(255,0,0),2)
        cv2.putText(frames,str("Car"),(x,y+h),font,1,255)
     
    
    cv2.imshow('img',frames)   

     
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
    
    
cap.release()
cv2.destroyAllWindows()

My input image:

在此处输入图片说明

My output image:

It is a car but i don't think a tire is a car! so what am i doing wrong?

Can't say why your classification isn't picking up on the car with any certainty, since I have no info on wherehttps://gist.github.com/199995/37e1e0af2bf8965e8058a9dfa3285bc6 came from. Without knowing that, I can't say what kind of images it's expected to be able to detect. It's possible that it was trained to recognize cars from images more like this停车场 , or even more zoomed out. In which case your example image is completely unlike what it has been trained to detect. Without knowing more it's impossible to say.

As for that error message you're getting, that one I can at least explain.

cap = cv2.VideoCapture('car.jpg')

You're opening an image as a video. On the first pass through the loop, it's (surprisingly) able to read image data, but after that on the next pass there's no more "frames" to read, so your frames object is None , there's no image data in it. This means when you try to convert it to grayscale, the operation is failing.

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