使用opencv python进行人脸检测和roi裁剪

时间:2016-06-03 03:03:52

标签: python-2.7 opencv

我从这篇文章中获取了代码: how to crop the detected face in opencv and save roi as image in opencv python

问题在于,当我运行此代码时,它会显示灰色屏幕而不是显示来自网络摄像头的视频。

这是我的编码:

import cv2
import os, sys

TRAINSET = "haarcascade_frontalface_default.xml"
DOWNSCALE = 4

cam = cv2.VideoCapture(0) #capture a video

cv2.namedWindow("preview")
classifier = cv2.CascadeClassifier(TRAINSET) 

Compare_images=[]
for file in os.listdir("D:/Python code"):
    if file.endswith(".jpg"):
       Compare_images.append(file)
while True: # try to get the first frame
    _, frame = cam.read() 

key = cv2.waitKey(20)
if(key==32):

    print "Name of Image:"

    n= raw_input()

    value=len(Compare_images)
    cv2.imwrite('images/image'+str(n)+'.jpg', frame)
    saved_image=cv2.imread("images/image"+str(n)+".jpg")
    minisize = (saved_image.shape[1]/DOWNSCALE,saved_image.shape[0]/DOWNSCALE)
    miniframe = cv2.resize(saved_image, minisize)
    faces = classifier.detectMultiScale(miniframe)
    for f in faces:
        x, y, w, h = [ v*DOWNSCALE for v in f ]     
        print x 
        print y,w,h      

        x0,y0=int(x),int(y)
        x1,y1=int(x+w),int(y+h)
        print x0,y0,y1,y0

        image = cv2.rectangle(saved_image, (x0,y0), (x1,y1), (0,0,255),2)

        roi=saved_image[y0:y1,x0:x1]#crop 
        cv2.imwrite('roi.jpg',roi)
        cv2.imshow("adsa", saved_image) 


cv2.putText(frame, "Press ESC to close.", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255,255,255))
cv2.imshow("preview", frame)

我真的很喜欢python,如果你能提供帮助我真的很感激!

0 个答案:

没有答案