使用opencv和python进行人脸检测

0 投票
1 回答
2209 浏览
提问于 2025-04-18 06:05

我正在使用OpenCV(2.4.6)和Python(2.7)进行人脸检测。我写了一段很简单的代码,但它没有给我想要的结果。

这是我的代码:

import numpy as np
import cv2
cam = cv2.VideoCapture(0)
name = 'detect'
face_cascade = cv2.CascadeClassifier('C:\opencv\data\haarcascades\haarcascade_frontalface_default.xml')
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE)
while True:
    s, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    for (x,y,w,h) in faces:
        img = cv2.rectangle(gray,(x,y),(x+w,y+h),(255,0,0),2)
        cv2.imshow(name, img)    
    k = cv2.waitKey(0)
    if k == 27:
        cv2.destroyWindow(name)
    break

当我运行这段代码时,我的摄像头会启动,但窗口却是空白的,像这样:

然后摄像头会关闭,编辑器里会出现如下错误:

%run "D:/6th sem/1.OpenCV + Python/det.py"
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
C:\Users\HP\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.3.0.1715.win-x86\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
195             else:
196                 filename = fname
--> 197             exec compile(scripttext, filename, 'exec') in glob, loc
198     else:
199         def execfile(fname, *where):

D:\6th sem\1.OpenCV + Python\det.py in <module>()
  7 while True:
  8     s, img = cam.read()
 ----> 9     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 10     faces = face_cascade.detectMultiScale(img, 1.3, 5)
 11     #print s

error: ..\..\..\src\opencv\modules\imgproc\src\color.cpp:3402: error: (-215) scn == 3 || scn == 4

欢迎任何建议。提前谢谢大家。

1 个回答

3

有些网络摄像头在启动时需要预热时间,这段时间它们会发送空的画面。你需要检查一下这个情况。

还有,谁说过 cv2.rectangle 会返回什么东西呢?你是从哪里听说的?是从 Stack Overflow 吗?

while cap.isOpened():
    s, img = cam.read()
    if s == None:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5) #hmm, 5 required neighbours is actually a lot.
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # if you want colors, don't paint into a grayscale...
        cv2.imshow(name, img)    
    k = cv2.waitKey(0)
    if k == 27:
        cv2.destroyWindow(name)
        break

撰写回答