OpenCV 3.4.0.12 with Python3.5 AttributeError:' cv2.VideoCapture'对象没有属性' imread'

时间:2018-01-11 20:20:31

标签: python numpy opencv face-recognition

我第一次使用python 3.5和OpenCV 3.4.0.12尝试进行面部识别,并且在运行代码时出现此错误。

  File "/Users/connorwoodford/anaconda3/envs/chatbot/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/connorwoodford/Desktop/temp.py", line 11, in <module>
    ret, img = cap.imread()

AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'

代码:

import cv2
import numpy as np

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

eye_cascade = cv2.CascadeClassifier('CascadeClassifier')

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.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]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) 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()

1 个答案:

答案 0 :(得分:0)

你的eye_cascade指的是错误的级联文件,它应以.xml扩展名结尾。您可以从此处haarcascade_eye.xml下载。

另请注意,您对cv2.rectangle的调用格式不正确。

更改它
cv2.rectangle(img, (x+y), (x+w, y+h), (255,0,0), 2)

cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)

你需要做的就是将捕获逻辑包装在一个方法中。完整代码如下:

import numpy as np
import cv2

def sample_demo():

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

    cap = cv2.VideoCapture(0)

    while 1:
        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.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]

            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) 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()

并简单地调用方法sample_demo()

sample_demo()