可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to detect a face and write down area with the face in a separate file. How can I do it? I think that i must use "faces" (you can see this var in code). But how? from ffnet import mlgraph, ffnet, tmlgraph, imlgraph import pylab import sys import cv,cv2 import numpy cascade = cv.Load('C:\opencv\data\haarcascades\haarcascade_frontalface_alt.xml') def detect(image): bitmap = cv.fromarray(image) faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0)) if faces: for (x,y,w,h),n in faces: cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3) return image if __name__ == "__main__": cam = cv2.VideoCapture(0) while 1: _,frame =cam.read() frame = numpy.asarray(detect(frame)) cv2.imshow("features", frame) if cv2.waitKey(1) == 0x1b: # ESC print 'ESC pressed. Exiting ...' break
回答1:
This following code should extract face in images and save faces on disk def detect(image): image_faces = [] bitmap = cv.fromarray(image) faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0)) if faces: for (x,y,w,h),n in faces: image_faces.append(image[y:(y+h), x:(x+w)]) #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3) return image_faces if __name__ == "__main__": cam = cv2.VideoCapture(0) while 1: _,frame =cam.read() image_faces = [] image_faces = detect(frame) for i, face in enumerate(image_faces): cv2.imwrite("face-" + str(i) + ".jpg", face) #cv2.imshow("features", frame) if cv2.waitKey(1) == 0x1b: # ESC print 'ESC pressed. Exiting ...' break