Python OpenCV实时面部检测作物已保存

时间:2016-11-03 18:06:58

标签: python opencv

我已经对此进行了大量的研究,我认为我的逻辑已经磨损,几乎在那里但似乎无法理解为什么在cv2.imshow()窗口中只显示灰色框没有任何内容,但是好消息是我能够检测到脸部和裁剪脸部,然后将其保存在文件夹中。

你能不能说清楚我出错的地方

#Author: Waheed Rafiq
#Research Student Birmingham City University
#Date: 03/11/2016
#Description :detect and Save capture face in a folder.

#Import library required for Capture face.

import cv2


#import the cascade for face detection
FaceClassifier =cv2.CascadeClassifier
('haarcascade_frontalface_default.xml')
# access the webcam (every webcam has 
capture = cv2.VideoCapture(0)

   while(True):
     # Capture frame-by-frame

    ret, frame = capture.read()
    if not capture:
    print "Error opening webcam device"
    sys.exit(1)


    # to detect faces in video
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = FaceClassifier.detectMultiScale(gray, 1.3, 5)

    # Resize Image 
    minisize = (frame.shape[1],frame.shape[0])
    miniframe = cv2.resize(frame, minisize)
    # Store detected frames in variable name faces
   faces =  FaceClassifier.detectMultiScale(miniframe)
   # Draw rectangle 
   for f in faces:
    x, y, w, h = [ v for v in f ]
    cv2.rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
    #Save just the rectangle faces in SubRecFaces
    sub_face = frame[y:y+h, x:x+w]
    FaceFileName = "unknowfaces/face_" + str(y) + ".jpg"
    cv2.imwrite(FaceFileName, sub_face)
    #Display the image 
    cv2.imshow('Result',frame)


    break

    # When everything done, release the capture

    img.release()
    cv2.waitKey(20)
    cv2.destroyAllWindows()

确实会支持你的支持

3 个答案:

答案 0 :(得分:4)

我不得不改进我的代码,并再次重新考虑逻辑:对于那些希望知道如何使用Opencv从网络摄像头或Raspberry PI中检测到面部然后裁剪检测到的面部的人,这就是你的工作方式在python 2.7中使用OpenCV 2.4.12

# croppfacedetection.py
#Author: Waheed Rafiq
#Research Student Birmingham City University
#Date: 03/11/2016
#Description : Save capture face in a folder.

#Import library required for Capture face.
# Should you wish to use this code for 
#education purpose in your assignment or dissertation
# please use the correct citation and give credit where required. 


import cv2
size = 4
webcam = cv2.VideoCapture(0) #Use camera 0

# We load the xml file
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#  Above line normalTest
#classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') 
#Above line test with different calulation
#classifier = cv2.CascadeClassifier('haarcascade_frontalface_alt_tree.xml')
#classifier = cv2.CascadeClassifier('lbpcascade_frontalface.xml')


while True:
    (rval, im) = webcam.read()
    im=cv2.flip(im,1,0) #Flip to act as a mirror

    # Resize the image to speed up detection
    mini = cv2.resize(im, (im.shape[1] / size, im.shape[0] / size))

    # detect MultiScale / faces 
    faces = classifier.detectMultiScale(mini)

    # Draw rectangles around each face
    for f in faces:
        (x, y, w, h) = [v * size for v in f] #Scale the shapesize backup
        cv2.rectangle(im, (x, y), (x + w, y + h),(0,255,0),thickness=4)
        #Save just the rectangle faces in SubRecFaces
        sub_face = im[y:y+h, x:x+w]
        FaceFileName = "unknowfaces/face_" + str(y) + ".jpg"
        cv2.imwrite(FaceFileName, sub_face)

    # Show the image
    cv2.imshow('BCU Research by Waheed Rafiq (c)',   im)
    key = cv2.waitKey(10)
    # if Esc key is press then break out of the loop 
    if key == 27: #The Esc key
    break

记住你需要创建一个文件夹,在该区域内你需要一个名为unknownfaces的文件夹从文件夹的根目录运行脚本,它应该将它检测到的任何面部保存到unknowfaces文件夹中。 有关此代码的更多信息将很快在我的网站上提供 waheedrafiq.net

答案 1 :(得分:1)

您的代码似乎无法访问cv2.waitKey(20)。您应该在break语句之前移动它。

在OpenCV中cv2.waitKey完成图像显示任务。这不仅仅是为了添加暂停。

答案 2 :(得分:1)

这是使用Python 3.6 OpenCV 4+的代码的“有效”版本。您不必推荐任何人,就可以自由使用它。

import cv2
import os

classifier = cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml")

dirFace = 'cropped_face'

# Create if there is no cropped face directory
if not os.path.exists(dirFace):
    os.mkdir(dirFace)
    print("Directory " , dirFace ,  " Created ")
else:    
    print("Directory " , dirFace ,  " has found.")

webcam = cv2.VideoCapture(0) # Camera 0 according to USB port
# video = cv2.VideoCapture(r"use full windows path") # video path

while (True):
    (f, im) = webcam.read() # f returns only True, False according to video access
    # (f, im) = video.read() # video 

    if f != True:
       break

    # im=cv2.flip(im,1,0) #if you would like to give mirror effect

    # detectfaces 
    faces = classifier.detectMultiScale(
        im, # stream 
        scaleFactor=1.10, # change these parameters to improve your video processing performance
        minNeighbors=20, 
        minSize=(30, 30) # min image detection size
        ) 

    # Draw rectangles around each face
    for (x, y, w, h) in faces:

        cv2.rectangle(im, (x, y), (x + w, y + h),(0,0,255),thickness=2)
        # saving faces according to detected coordinates 
        sub_face = im[y:y+h, x:x+w]
        FaceFileName = "cropped_face/face_" + str(y+x) + ".jpg" # folder path and random name image
        cv2.imwrite(FaceFileName, sub_face)

    # Video Window
    cv2.imshow('Video Stream',im)
    key = cv2.waitKey(1) & 0xFF
    # q for exit
    if key == ord('q'): 
        break
webcam.release()