Opencv(在python中)给出错误-函数'cv2 :: cvtColor'中的!_src.empty()

时间:2020-03-14 19:14:03

标签: python opencv

我目前正在尝试运行一个简单的python程序来检测面部和眼睛。

我下载了适当的分类器,它们位于同一目录中。我什至检查了我的相机设置,并在允许python的情况下将其设置为on。有什么办法解决这个问题吗?

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while True:
   ret, img = cap.read()
   gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
   faces = face_cascade.detectMultiScale(gray, 1.3, 5)
   for (x,y,w,h) in faces:
      cv2.rectange(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]
      eyes = eye_cascade.detectMultiScale(roi_gray)
      for (ex,ey,ew,ehh) in eyes:
        cv2.rectangle(roi_color, (ex,ey), (ex+ew,ey+eh), (0,255,0), 2)

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

cap.release()
cv2.destroyAllWindows()

为什么此OpenCV程序会给出错误

!_src.empty() error in function 'cv::cvtColor'

我的相机设置显示python正在使用它: Camera settings' screenshot

谢谢!

1 个答案:

答案 0 :(得分:1)

!_ src.empty()表示您的框架为空

您可以检查框架以确保您确实得到了图像:

ret, img = cap.read()
if img is not None: 
   gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else: < implement how you want to deal with empty frame >