def __init__(self): path = 'haarcascade_frontalface_default.xml' if os.path.exists(path): self._cascade = cv.Load(path) else: path = 'fixtures/haarcascade_frontalface_default.xml' if os.path.exists(path): self._cascade = cv.Load(path) else: raise ValueError("Can't find .xml file!")
def __init__(self): path = 'haarcascade_frontalface_default.xml' if os.path.exists(path): self._cascade = cv.Load(path) else: path = 'fixtures/haarcascade_frontalface_default.xml' if os.path.exists(path): self._cascade = cv.Load(path) else: raise ValueError("Can't find .xml file!") self._output_boxes = 'OUTPUT_BOXES' in os.environ
def findmouth(img): # INITIALIZE: loading the classifiers haarFace = cv.Load(path_to_file + '/haarcascade_frontalface_default.xml') haarMouth = cv.Load(path_to_file + '/haarcascade_mouth.xml') # running the classifiers storage = cv.CreateMemStorage() detectedFace = cv.HaarDetectObjects(img, haarFace, storage) detectedMouth = cv.HaarDetectObjects(img, haarMouth, storage) # FACE: find the largest detected face as detected face maxFaceSize = 0 maxFace = 0 if detectedFace: # face: [0][0]: x; [0][1]: y; [0][2]: width; [0][3]: height for face in detectedFace: if face[0][3] * face[0][2] > maxFaceSize: maxFaceSize = face[0][3] * face[0][2] maxFace = face if maxFace == 0: # did not detect face return 2 def mouth_in_lower_face(mouth, face): # if the mouth is in the lower 2/5 of the face # and the lower edge of mouth is above that of the face # and the horizontal center of the mouth is the center of the face if (mouth[0][1] > face[0][1] + face[0][3] * 3 / float(5) and mouth[0][1] + mouth[0][3] < face[0][1] + face[0][3] and abs((mouth[0][0] + mouth[0][2] / float(2)) - (face[0][0] + face[0][2] / float(2))) < face[0][2] / float(10)): return True else: return False # FILTER MOUTH filteredMouth = [] if detectedMouth: for mouth in detectedMouth: if mouth_in_lower_face(mouth, maxFace): filteredMouth.append(mouth) maxMouthSize = 0 for mouth in filteredMouth: if mouth[0][3] * mouth[0][2] > maxMouthSize: maxMouthSize = mouth[0][3] * mouth[0][2] maxMouth = mouth try: return maxMouth except UnboundLocalError: return 2
def __init__(self): self.storage = cv.CreateMemStorage(0) self.last_face_position = None self.face_cascade = cv.Load( os.path.expanduser('haarcascade_frontalface_default.xml')) #self.face_cascade = cv.Load('haarcascade_frontalface_alt.xml') #self.eye_cascade = cv.Load(os.path.expanduser('~/Downloads/parojos-22x15.xml')) self.eye_cascade = cv.Load(os.path.expanduser('parojosG-45x11.xml')) self.detect_times = [] self.eye_pair_history = [] self.xamount_histories = [[], []] self.yamount_histories = [[], []] self.xpos_history = [] self.ypos_history = []
def detect(image): image_size = cv.GetSize(image) # create grayscale version grayscale = cv.CreateImage(image_size, 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY) # create storage storage = cv.CreateMemStorage(0) # cv.ClearMemStorage(storage) # equalize histogram cv.EqualizeHist(grayscale, grayscale) # detect objects cascade = cv.Load('haarcascade_frontalface_alt.xml') faces = cv.HaarDetectObjects( grayscale, cascade, storage, 1.2, 2, ) if faces: print 'face detected!' for i in faces: print i cv.Rectangle(image, (i[0][0], i[0][1]), (int(i[0][0] + i[0][2]), int(i[0][1] + i[0][3])), cv.RGB(0, 255, 0), 3, 8, 0)
def __init__(self): self.haarbase = '/usr/share/opencv/' #'/opt/ros/hydro/share/OpenCV/' #'/usr/share/opencv/' self.faceCascade = cv.Load(self.haarbase + "haarcascades/haarcascade_frontalface_alt.xml") self.pub = rospy.Publisher('/facedetect', targets, queue_size=10) cv.NamedWindow("ImageShow", 1) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/cv_camera/image_raw",Image,self.callback)
def faceCrop(imagePattern, boxScale=1): # Select one of the haarcascade files: # haarcascade_frontalface_alt.xml <-- Best one? # haarcascade_frontalface_alt2.xml # haarcascade_frontalface_alt_tree.xml # haarcascade_frontalface_default.xml # haarcascade_profileface.xml faceCascade = cv.Load('haarcascade_frontalface_default.xml') imgList = glob.glob(imagePattern) if len(imgList) <= 0: print 'No Images Found' return n = 0 for img in imgList: pil_im = Image.open(img) cv_im = pil2cvGrey(pil_im) faces = DetectFace(cv_im, faceCascade) if faces: for face in faces: croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale) path = getResultPath(img) if (path != ""): croppedImage.thumbnail([TARGET_SIZE, TARGET_SIZE], Image.ANTIALIAS) croppedImage.save(path) n += 1 else: print 'No faces found:', img print n
def detect_faces(self, cascade_filename='haarcascade_frontalface_alt2.xml'): cv = _cv() # If a relative path was provided, check local cascades directory if not os.path.isabs(cascade_filename): cascade_filename = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'data/cascades', cascade_filename, ) # Load cascade file cascade = cv.Load(cascade_filename) # Equalise the images histogram equalised_image = cv.CloneImage(self.image) cv.EqualizeHist(self.image, equalised_image) # Detect faces min_size = (40, 40) haar_scale = 1.1 min_neighbors = 3 haar_flags = 0 faces = cv.HaarDetectObjects(equalised_image, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) return [( face[0][0], face[0][1], face[0][0] + face[0][2], face[0][1] + face[0][3], ) for face in faces]
def detect_faces(self): if opencv_available: cascade_filename = os.path.join( os.path.dirname(__file__), 'face_detection', 'haarcascade_frontalface_alt2.xml') cascade = cv.Load(cascade_filename) image = self.opencv_grey_image() cv.EqualizeHist(image, image) min_size = (40, 40) haar_scale = 1.1 min_neighbors = 3 haar_flags = 0 faces = cv.HaarDetectObjects(image, cascade, cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) if faces: return [ FocalPoint.from_square(face[0][0], face[0][1], face[0][2], face[0][3]) for face in faces ] return []
def detect_and_draw(img, cascade): # allocate temporary images gray = cv.CreateImage((img.width, img.height), 8, 1) small_img = cv.CreateImage((cv.Round( img.width / image_scale), cv.Round(img.height / image_scale)), 8, 1) # convert color input image to grayscale cv.CvtColor(img, gray, cv.CV_BGR2GRAY) # scale input image for faster processing cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) cv.EqualizeHist(small_img, small_img) if (cascade): t = cv.GetTickCount() faces = cv.HaarDetectObjects(small_img, cv.Load(cascade), cv.CreateMemStorage(0), haar_scale, min_neighbors, haar_flags, min_size) t = cv.GetTickCount() - t print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.)) if faces: for ((x, y, w, h), n) in faces: # the input to cv.HaarDetectObjects was resized, so scale the # bounding box of each face and convert it to two CvPoints pt1 = (int(x * image_scale), int(y * image_scale)) pt2 = (int((x + w) * image_scale), int((y + h) * image_scale)) cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0) print "face detected" cv.SaveImage("result.png", img)
def detect(self, obj, event): # First, reset image, in case of previous detections: active_handle = self.get_active('Media') media = self.dbstate.db.get_media_from_handle(active_handle) self.load_image(media) min_face_size = (50, 50) # FIXME: get from setting self.cv_image = cv.LoadImage(self.full_path, cv.CV_LOAD_IMAGE_GRAYSCALE) o_width, o_height = self.cv_image.width, self.cv_image.height cv.EqualizeHist(self.cv_image, self.cv_image) cascade = cv.Load(HAARCASCADE_PATH) faces = cv.HaarDetectObjects(self.cv_image, cascade, cv.CreateMemStorage(0), 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, min_face_size) references = self.find_references() rects = [] o_width, o_height = [ float(t) for t in (self.cv_image.width, self.cv_image.height) ] for ((x, y, width, height), neighbors) in faces: # percentages: rects.append((x / o_width, y / o_height, width / o_width, height / o_height)) self.draw_rectangles(rects, references)
def detect(image): image_size = cv.GetSize(image) # create grayscale version grayscale = cv.CreateImage(image_size, 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY) # create storage storage = cv.CreateMemStorage(0) # equalize histogram cv.EqualizeHist(grayscale, grayscale) # show processed image #cv.ShowImage('Processed', grayscale) # detect objects cascade = cv.Load( '/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml') faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING) if faces: for i in faces: cv.Rectangle(image, (i[0][0], i[0][1]), (i[0][0] + i[0][2], i[0][1] + i[0][3]), (0, 0, 255), 1, 8, 0)
def __init__(self): self.image_pub = rospy.Publisher("/imagecv",Image) cv.NamedWindow("Image window", 1) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/usb_cam/image_raw",Image,self.callback) self.cascade = cv.Load("/home/anton/work_files/ros/my_package/haarcascade_frontalface_alt2.xml")
def detect_eyes(img): haarEyes = cv.Load('haarcascade_eye.xml') #haarEyes = cv.Load('haarcascade_eye_tree_eyeglasses.xml') allEyes = cv.HaarDetectObjects(img, haarEyes, cv.CreateMemStorage(), scale_factor=1.25, min_neighbors=10, flags=0, min_size=(10, 10)) print('All Eyes: ' + str(allEyes)) #print('LENGTH: '+str(len(allEyes))) if (allEyes != []): if (len(allEyes) == 1): return allEyes else: eye_confid = [c for ((x, y, w, h), c) in allEyes] eye_confid_inds = np.argsort(eye_confid)[::-1][:2] #print(eye_confid_inds) eye0 = allEyes[eye_confid_inds[0]] eye1 = allEyes[eye_confid_inds[1]] return [eye0, eye1] return []
def detect(image): image_size = cv.GetSize(image) #create greyscale version grayscale = cv.CreateImage(image_size, 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY) # create storage storage = cv.CreateMemStorage(0) #cv.ClearMemStorage(storage) # equalize histogram cv.EqualizeHist(grayscale, grayscale) # detect objects cascade = cv.Load('haarcascade_frontalface_alt.xml') faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, cv.HAAR_DO_CANNY_PRUNING, CV.SIZE(50, 50)) if faces: print 'face detected!' for i in faces: cv.Rectangle(image, cv.Point(int(i.x), int(i.y)), cv.Point(int(i.x + i.width), int(i.y + i.height)), cv.RGB(0, 255, 0), 3, 8, 0) cv.ShowImage('Video', image) return faces
def Init(self): self.frame = 'none' self.videoCapture = 'none' self.cascade = 'none' self.storage = 'none' cv.NamedWindow("Ex", cv.CV_WINDOW_FULLSCREEN) self.videoCapture = cv.CreateCameraCapture(0) cv.SetCaptureProperty(self.videoCapture,cv.CV_CAP_PROP_FRAME_WIDTH,80) cv.SetCaptureProperty(self.videoCapture,cv.CV_CAP_PROP_FRAME_HEIGHT,60) cv.SetCaptureProperty(self.videoCapture,cv.CV_CAP_PROP_FPS,10) if( self.videoCapture == 'none' ): print("OpenCV error: Could not create cam capture") return self.cascade = cv.Load("./haarcascade_frontalface_alt.xml") self.storage = cv.CreateMemStorage( 0 ) assert(self.cascade and self.storage and self.videoCapture) key = cv.WaitKey(10) while(( key != 'none') and (key != 'q')): self.frame = cv.QueryFrame(self.videoCapture) # if( frame == 'none'): # break # cvFlip(self.frame, self.frame, -1) # self.DetectFaces() cv.ShowImage("videoCapture", self.frame) key = cv.WaitKey(10) return
def faceCrop(imagePattern, boxScale=1): # Select one of the haarcascade files: # haarcascade_frontalface_alt.xml <-- Best one? # haarcascade_frontalface_alt2.xml # haarcascade_frontalface_alt_tree.xml # haarcascade_frontalface_default.xml # haarcascade_profileface.xml faceCascade = cv.Load('haarcascade_frontalface_alt.xml') imgList = glob.glob(imagePattern) if len(imgList) <= 0: print 'No Images Found' return for img in imgList: pil_im = Image.open(img) croppedImage = cropImgToCenter(pil_im) cv_im = pil2cvGrey(croppedImage) faces = DetectFace(cv_im, faceCascade) if faces: for face in faces: croppedImage = imgCrop(croppedImage, face[0], boxScale=boxScale) fname, ext = os.path.splitext(img) croppedImage.save(fname + ext) else: print 'No faces found:', img
def measure(im, debug=False): im2 = image.max_size(im, (800, 600)) b,g,r = image.split(im2) #cv.EqualizeHist(r,r) ##cv.EqualizeHist(g,g) ##cv.EqualizeHist(b,b) im2 = image.merge(b,g,r) eyes = 0 #objs = [] #for cascade in eye_cascades: # print cascade # cascade = cv.Load(cascade) # objs = filter_overlap(detect(im, cascade)) # draw_objects(im, objs, color=cv.RGB(0,255,0)) # eyes += len(objs) #faces = 0 if debug: im3 = cv.CloneImage(im2) faces = [] for cascade in face_cascades:#(face_cascades[0],face_cascades[-1]): cascade = cv.Load(cascade) detected_faces = detect(im2, cascade) faces += detected_faces if debug: for i,rect in enumerate(faces): rect.draw(im3, color=cv.RGB(255,16*i,16*i)) if debug: image.show(im3, "Faces + Repeats") faces = filter_overlap(faces) #print (objs[1], objs[6]) #draw_objects(im2, map(tuple, faces.keys())) for rect, count in faces.iteritems(): rect.draw(im2, color=cv.RGB(255,0,0)) #print (objs[3],objs[13]) #draw_objects(im, filter_overlap((objs[3],objs[13]))) #objs = [] #for cascade in body_cascades: # print cascade # cascade = cv.Load(cascade) # objs += detect(im, cascade) #draw_objects(im, filter_overlap(objs), color=cv.RGB(0,0,255)) #objs = [] #for cascade in mouth_cascades: # print cascade # cascade = cv.Load(cascade) # objs += detect(im, cascade) #draw_objects(im, filter_overlap(objs), color=cv.RGB(255,0,255)) score = 0 for face_rect, count in faces.iteritems(): score += count * 0.25 + 0.15 print faces if debug: image.show(im2, "Faces") return (im2, faces), score
def crop_face_and_landmarks(img, landmark_points): """ Crop an image to the face and adjust the landmark points so that they match the crop :param img: a PIL image containing a face :param landmark_points: np array for eyes [[Lx,Ly],[Rx,Ry]] """ faceCascade = cv.Load("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml") pil_im=img cv_im=pil2cvGrey(pil_im) face_bounds=DetectFace(cv_im,faceCascade)[0][0] cropped_landmark_points = [] for eye_pt in landmark_points: if (eye_pt[0] < face_bounds[0] or eye_pt[0] > face_bounds[0] + face_bounds[2] or eye_pt[1] < face_bounds[1] or eye_pt[1] > face_bounds[1] + face_bounds[3]): print("WARNING: Eyes outside of facial bounds!") cropped_landmark_points.append([eye_pt[0]-face_bounds[0], eye_pt[1]-face_bounds[1]]) cropped_image=imgCrop(pil_im, face_bounds, boxScale=0.9) return (cropped_image, np.array(cropped_landmark_points, dtype=np.float32))
def __init__(self, cascade_name=DEFAULT_CASCADE, orig_size=None, min_size=(60, 60), image_scale=1.3, haar_scale=1.2, min_neighbors=2, haar_flags=0): ''' Init the detector and create the cascade classifier ''' self.cascade_name = cascade_name self.min_size = min_size self.image_scale = image_scale self.haar_scale = haar_scale self.min_neighbors = min_neighbors self.haar_flags = haar_flags if cascade_name != None: if not os.path.isfile(cascade_name): raise CascadeNotFound("Could not find file: " + cascade_name) # Save data for later pickling if orig_size == None: orig_size = (1, 1) else: orig_size = (orig_size[0], orig_size[1]) self.cascade_data = open(cascade_name).read() self.cascade = cv.Load(cascade_name) self.storage = cv.CreateMemStorage(0) self.trained = True
def faceCrop(imagePattern, boxScale=1): # Select one of the haarcascade according to crop files: # haarcascade_frontalface_alt.xml <-- we use this # haarcascade_frontalface_alt2.xml # haarcascade_frontalface_alt_tree.xml # haarcascade_frontalface_default.xml # haarcascade_profileface.xml faceCascade = cv.Load('haarcascade_frontalface_alt_tree.xml') imgList = glob.glob(imagePattern) if len(imgList) <= 0: print('No Images Found') return for img in imgList: pil_im = Image.open(img) pil = resizeImage(pil_im) cv_im = pil2cvGrey(pil_im) faces = DetectFace(cv_im, faceCascade) if faces: n = 1 for face in faces: croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale) fname, ext = os.path.splitext(img) croppedImage.save("cropped/" + fname + '_crop' + str(n) + ext) n += 1 else: print('No faces found:') print(img)
class Mustashify: supported = { "image/gif": "GIF", "image/png": "PNG", "image/jpg": "JPEG", "image/jpeg": "JPEG", } def __init__(self, mustache_image, haar_xml): try: self.im = Image.open(mustache_image) except Exception, e: #log.err() print("Mustache image %s could not be opened" % mustache_image) sys.exit(1) self.min_size = (20, 20) self.image_scale = 2 self.haar_scale = 1.2 self.min_neighbors = 2 self.haar_flags = 0 try: self.cascade = cv.Load(haar_xml) except Exception, e: #log.err() print("Haar file %s could not be opened" % haar_xml) sys.exit(1)
def detectObjects(image): """Converts an image to grayscale and prints the locations of any faces found""" grayscale = cv.CreateImage(cv.GetSize(image), 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY) # Deprecated v1 code??? storage = cv.CreateMemStorage(0) #cv.ClearMemStorage(storage) cv.EqualizeHist(grayscale, grayscale) cascade = cv.Load( '/home/brian/code/twisted-faces/haarcascade_frontalface_default.xml') faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING) # if faces: coords = [] if faces.total > 0: for f in faces: #print("[(%d,%d) -> (%d,%d)]" % (f.x, f.y, f.x+f.width, f.y+f.height)) coords.append({ 'start': { 'x': f.x, 'y': f.y }, 'end': { 'x': f.x + f.width, 'y': f.y + f.height } }) return coords
def faceCrop(imagePattern, boxScale=1): # Select one of the haarcascade files: # haarcascade_frontalface_alt.xml <-- Best one? # haarcascade_frontalface_alt2.xml # haarcascade_frontalface_alt_tree.xml # haarcascade_frontalface_default.xml # haarcascade_profileface.xml faceCascade = cv.Load( "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml") imgList = glob.glob(imagePattern) if len(imgList) <= 0: print 'No Images Found' return for img in imgList: pil_im = Image.open(img) cv_im = pil2cvGrey(pil_im) faces = DetectFace(cv_im, faceCascade) if faces: n = 1 for face in faces: croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale) fname, ext = os.path.splitext(img) croppedImage.save(fname + '_crop' + str(n) + ext) n += 1 else: print 'No faces found:', img
def runFaces(self): HAAR_CASCADE_PATH = "haarcascade_frontalface_default.xml" CAMERA_INDEX = 0 cv.NamedWindow("Video", cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(CAMERA_INDEX) self.storage = cv.CreateMemStorage() self.cascade = cv.Load(HAAR_CASCADE_PATH) faces = [] i = 0 c = -1 while (c == -1): image = cv.QueryFrame(capture) # Only run the Detection algorithm every 5 frames to improve performance #if i%5==0: faces = self.detect_faces(image) detected = 0 for (x, y, w, h) in faces: detected = 1 cv.Rectangle(image, (x, y), (x + w, y + h), 255) print x, y self.WriteXY(x, y) if detected == 0: self.WriteXY(-1, -1) cv.ShowImage("Video", image) i += 1 c = cv.WaitKey(10)
def Crop_Face(Img_Pattern, Box_Scale=1): faceCascade = cv.Load('../cv/haarcascade_frontalface_alt.xml' ) # Used frontalface_alt instead of _default Images = glob.glob(Img_Pattern) if len(Images) <= -1: print 'No Images Found' return for Img in Images: PIL_Image = Image.open(Img) OpenCV_Image = Grey_Scale(PIL_Image) Faces = Detect_Face(OpenCV_Image, faceCascade) if Faces: n = 1 for Face in Faces: Cropped_Image = PIL_Scale(PIL_Image, Face[0], Box_Scale) fname, ext = os.path.splitext(Img) max = 128, 128 Cropped_Image.thumbnail(max, Image.ANTIALIAS) Cropped_Image.save(fname + '_crop' + ext) ++n else: print 'No faces found: ', Img
def faceCrop(imagePattern, boxScale=1): # Select one of the haarcascade files: # haarcascade_frontalface_alt.xml <-- Best one? # haarcascade_frontalface_alt2.xml # haarcascade_frontalface_alt_tree.xml # haarcascade_frontalface_default.xml # haarcascade_profileface.xml faceCascade = cv.Load('haarcascade_frontalface_default.xml') imgList = glob.glob(imagePattern) if len(imgList) <= 0: print 'No Images Found' return for img in imgList: pil_im = Image.open(img) cv_im = pil2cvGrey(pil_im) faces = DetectFace(cv_im, faceCascade) if len(faces) != 1: print('Faces not equal to 1') continue if faces: n = 1 for face in faces: croppedImage = imgCrop(pil_im, face[0], boxScale=boxScale) fname, ext = os.path.splitext(img) print('cropped image should be made now') croppedImage.save(fname + '_cropped' + ext) n += 1 else: print 'No faces found:', img
def find_faces(self, file_name=None): try: import cv except ImportError: return if file_name is None: return logger.debug("%s: %s" % (self.__class__.__name__, file_name)) imcolor = cv.LoadImage(file_name) #@UndefinedVariable detectors = [ "haarcascade_frontalface_default.xml", "haarcascade_profileface.xml" ] for detector in detectors: haarFace = cv.Load(os.path.join(settings.STATIC_ROOT, detector)) # @UndefinedVariable storage = cv.CreateMemStorage() #@UndefinedVariable detectedFaces = cv.HaarDetectObjects( imcolor, haarFace, storage, min_size=(200, 200)) #@UndefinedVariable if detectedFaces: for face in detectedFaces: fata = DetectedFace(imagine=self, x=face[0][0], y=face[0][1], width=face[0][2], height=face[0][3]) fata.save() self.is_face_processed = True self.save()
def detect(image): #cv.Rectangle(image, (10,10), (50,50), cv.RGB(255,0,0)) image_size = cv.GetSize(image) # create grayscale version grayscale = cv.CreateImage(image_size, 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY) # create storage storage = cv.CreateMemStorage(0) #cv.ClearMemStorage(storage) # equalize histogram cv.EqualizeHist(grayscale, grayscale) # detect objects cascade = cv.Load('haarcascade_frontalface_alt.xml') #, cv.Size(1,1)) faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100, 100)) if faces: #print len(faces), 'face(s) detected!' #if len(faces)>1: print '2 faces found' for i in faces: j = i[0] cv.Rectangle(image, (int(j[0]), int(j[1])), (int(j[0] + j[2]), int(j[1] + j[3])), cv.RGB(0, 255, 0), 3, 8, 0)
def detect_faces(self, image_filename): """ Detects all faces and returns a list with images and corresponding coordinates""" logging.debug( 'Start method "detect_faces" for file %s (face-detector.py)' % image_filename) cascade = cv.Load(parameter.cascadefile) # load face cascade image = cv.LoadImage(image_filename) # loads and converts image # detect and save coordinates of detected faces coordinates = cv.HaarDetectObjects( image, cascade, cv.CreateMemStorage(), parameter.scaleFactor, parameter.minNeighbors, parameter.flags, parameter.min_facesize) # Convert to greyscale - better results when converting AFTER facedetection with viola jones if image.channels == 3: logging.debug( 'Bild %s wird in Graustufenbild umgewandelt (face-detector.py)' % image_filename) grey_face = (cv.CreateImage((image.width, image.height), 8, 1)) # Create grey-scale Image cv.CvtColor(image, grey_face, cv.CV_RGB2GRAY ) # convert Image to Greyscale (necessary for SURF) image = grey_face logging.debug( '%d faces successfully detected in file %s (face-detector.py)' % (len(coordinates), image_filename)) return image, coordinates