简体   繁体   English

使用opencv和python进行人脸检测

[英]Face Detection using opencv and python

I'm working on Face Detection in OpenCV(2.4.6) and python(2.7). 我正在OpenCV(2.4.6)和python(2.7)中进行人脸检测。 I have a very simple code, but its not giving me the desired output. 我有一个非常简单的代码,但是没有给我想要的输出。

This is my code: 这是我的代码:

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

When I run this code, my webcam will start and it will give me a blank window like this 当我运行此代码时,我的网络摄像头将启动,并且会给我一个空白窗口,如下所示

Then the webcam will turn off, and in the editor I will get an error as follows: 然后,网络摄像头将关闭,在编辑器中,我将收到如下错误:

%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

Any suggestions are welcome. 欢迎任何建议。 Thanks in advance. 提前致谢。

some webcams need a warmup time, and deliver empty frames on startup. 一些网络摄像头需要预热时间,并在启动时提供空帧。 you want to check for that. 您想检查一下。

also, who said , that cv2.rectangle returns anything ? 还有谁说cv2.rectangle返回什么? where did you get that idea ? 你从哪里得到这个主意的? from SO ? 从SO?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM