Exemple #1
0
def DetectRedEyes(image, faceCascade, eyeCascade):
    min_size = (20, 20)
    image_scale = 2
    haar_scale = 1.2
    min_neighbors = 2
    haar_flags = 0

    # Allocate the temporary images
    gray = cv.CreateImage((image.width, image.height), 8, 1)
    smallImage = cv.CreateImage((cv.Round(
        image.width / image_scale), cv.Round(image.height / image_scale)), 8,
                                1)

    # Convert color input image to grayscale
    cv.CvtColor(image, gray, cv.CV_BGR2GRAY)

    # Scale input image for faster processing
    cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR)

    # Equalize the histogram
    cv.EqualizeHist(smallImage, smallImage)

    # Detect the faces
    faces = cv.HaarDetectObjects(smallImage, faceCascade,
                                 cv.CreateMemStorage(0), haar_scale,
                                 min_neighbors, haar_flags, min_size)

    # If faces are found
    if faces:
        print "face detected"
        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(image, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)
            face_region = cv.GetSubRect(image,
                                        (x, int(y + (h / 4)), w, int(h / 2)))

        cv.SetImageROI(
            image,
            (pt1[0], pt1[1], pt2[0] - pt1[0], int((pt2[1] - pt1[1]) * 0.7)))
        eyes = cv.HaarDetectObjects(image, eyeCascade, cv.CreateMemStorage(0),
                                    haar_scale, min_neighbors, haar_flags,
                                    (15, 15))

        # if eyes:
        # 	# For each eye found
        # 	for eye in eyes:
        # 		# Draw a rectangle around the eye
        # 		cv.Rectangle(image,
        # 		(eye[0][0],
        # 		eye[0][1]),
        # 		(eye[0][0] + eye[0][2],
        # 		eye[0][1] + eye[0][3]),
        # 		cv.RGB(255, 0, 0), 1, 8, 0)

    cv.ResetImageROI(image)
    return image
Exemple #2
0
def get_face_roi(img):
    frontals = cv.HaarDetectObjects(img, feature_detectors[0],
                                    cv.CreateMemStorage())
    if len(frontals) == 0:
        profiles = cv.HaarDetectObjects(img, feature_detectors[1],
                                        cv.CreateMemStorage())
        return profiles
    return frontals
Exemple #3
0
def detectRedEyes(image, faceCascade, eyeCascade):
    min_size = (20, 20)
    image_scale = 2
    haar_scale = 1.2
    min_neighbors = 2
    haar_flags = 0

    # Allocate the temporary images
    gray = cv.CreateImage((image.width, image.height), 8, 1)
    smallImage = cv.CreateImage((cv.Round(
        image.width / image_scale), cv.Round(image.height / image_scale)), 8,
                                1)
    # Convert color input image to grayscale
    cv.CvtColor(image, gray, cv.CV_BGR2GRAY)
    # Scale input image for faster processing
    cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR)
    # Equalize the histogram
    cv.EqualizeHist(smallImage, smallImage)

    # Detect the faces
    faces = cv.HaarDetectObjects(smallImage, faceCascade,
                                 cv.CreateMemStorage(0), haar_scale,
                                 min_neighbors, haar_flags, min_size)

    # If faces are found
    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(image, pt1, pt2, cv.RGB(255, 0, 0), 3, 8,
                         0)  # If faces are found

    # Estimate the eyes position
    # First, set the image region of interest
    # The last division removes the lower part of the face to lower probability for false recognition
    cv.SetImageROI(
        image, (pt1[0], pt1[1], pt2[0] - pt1[0], int((pt2[1] - pt1[1]) * 0.6)))

    # Detect the eyes
    eyes = cv.HaarDetectObjects(image, eyeCascade, cv.CreateMemStorage(0),
                                haar_scale, min_neighbors, haar_flags,
                                (20, 15))
    # If eyes were found
    if eyes:
        # For each eye found
        for eye in eyes:
            # Draw a rectangle around the eye
            cv.Rectangle(image, (eye[0][0], eye[0][1]),
                         (eye[0][0] + eye[0][2], eye[0][1] + eye[0][3]),
                         cv.RGB(255, 0, 0), 1, 8, 0)

    # Finally, reset the image region of interest (otherwise this won t
    # be drawn correctly
    cv.ResetImageROI(image)

    return image
Exemple #4
0
    def detect_face(self, cv_image):
        if self.grey is None:
            """ Allocate temporary images """
            self.grey = cv.CreateImage(self.image_size, 8, 1)

        if self.small_image is None:
            self.small_image = cv.CreateImage(
                (cv.Round(self.image_size[0] / self.image_scale),
                 cv.Round(self.image_size[1] / self.image_scale)), 8, 1)
        """ Convert color input image to grayscale """
        cv.CvtColor(cv_image, self.grey, cv.CV_BGR2GRAY)
        """ Equalize the histogram to reduce lighting effects. """
        cv.EqualizeHist(self.grey, self.grey)
        """ Scale input image for faster processing """
        cv.Resize(self.grey, self.small_image, cv.CV_INTER_LINEAR)
        """ First check one of the frontal templates """
        if self.cascade_frontal_alt:
            faces = cv.HaarDetectObjects(self.small_image,
                                         self.cascade_frontal_alt,
                                         cv.CreateMemStorage(0),
                                         self.haar_scale, self.min_neighbors,
                                         self.haar_flags, self.min_size)
        """ If that fails, check the profile template """
        if not faces:
            if self.cascade_profile:
                faces = cv.HaarDetectObjects(self.small_image,
                                             self.cascade_profile,
                                             cv.CreateMemStorage(0),
                                             self.haar_scale,
                                             self.min_neighbors,
                                             self.haar_flags, self.min_size)

            if not faces:
                """ If that fails, check a different frontal profile """
                if self.cascade_frontal_alt2:
                    faces = cv.HaarDetectObjects(
                        self.small_image, self.cascade_frontal_alt2,
                        cv.CreateMemStorage(0), self.haar_scale,
                        self.min_neighbors, self.haar_flags, self.min_size)

        if not faces:
            return None

        fs = []
        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 * self.image_scale), int(y * self.image_scale))
            pt2 = (int(
                (x + w) * self.image_scale), int((y + h) * self.image_scale))
            if (pt2[0] - pt1[0]) * (pt2[1] - pt1[1]) == 0:
                logger.warn("Area of detected face is 0")
                continue
            fs.append((pt1, pt2))
        added = self.detect_box.addFaces(fs)
        self.save_faces(added)
        return self.detect_box.faces
Exemple #5
0
def DetectFace(image, faceCascade, eyeCascade):
    min_size = (20, 20)
    image_scale = 2
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0
    # Allocate the temporary images
    gray_scale = cv.CreateImage((image.width, image.height), 8, 1)
    small_Image = cv.CreateImage((cv.Round(
        image.width / image_scale), cv.Round(image.height / image_scale)), 8,
                                 1)
    # Convert color input image to grayscale
    cv.CvtColor(image, gray_scale, cv.CV_BGR2GRAY)
    # Scale input image for faster processing
    cv.Resize(gray_scale, small_Image, cv.CV_INTER_LINEAR)
    # Equalize the histogram
    cv.EqualizeHist(small_Image, small_Image)
    faces = cv.HaarDetectObjects(  # Haarcascade objects for face detection
        small_Image, faceCascade, cv.CreateMemStorage(0), haar_scale,
        min_neighbors, haar_flags, min_size)

    eyes = cv.HaarDetectObjects(
        small_Image,
        eyeCascade,  # Haarcascade objects for eyes detection
        cv.CreateMemStorage(0),
        haar_scale,
        min_neighbors,
        haar_flags,
        min_size)
    # If face is detected
    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(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)
        # if eyes detected once face is detected
        if eyes:
            for ((x, y, w, h), n) in eyes:
                # the input to cv.HaarDetectObjects was resized, so scale the
                # bounding box of each eye 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(image, pt1, pt2, cv.RGB(0, 255, 0), 5, 8, 0)
        else:
            os.system("scrot ab.png")
            os.system("python detect.py")
        #   os.system("mplayer 1.mp3")
    else:
        os.system("scrot noface.png")
        print('User not detected')
    #  os.system("mplayer 1.mp3")
    return image
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
Exemple #7
0
    def detect_faces(self, cv_image):
        if self.grey is None:
            """ Allocate temporary images """
            self.grey = cv.CreateImage(self.image_size, 8, 1)

        if self.small_image is None:
            self.small_image = cv.CreateImage(
                (cv.Round(self.image_size[0] / self.image_scale),
                 cv.Round(self.image_size[1] / self.image_scale)), 8, 1)
        """ Convert color input image to grayscale """
        cv.CvtColor(cv_image, self.grey, cv.CV_BGR2GRAY)
        """ Equalize the histogram to reduce lighting effects. """
        cv.EqualizeHist(self.grey, self.grey)
        """ Scale input image for faster processing """
        cv.Resize(self.grey, self.small_image, cv.CV_INTER_LINEAR)
        """ First check one of the frontal templates """
        frontal_faces = cv.HaarDetectObjects(self.small_image,
                                             self.cascade_frontal_alt,
                                             cv.CreateMemStorage(0),
                                             self.haar_scale,
                                             self.min_neighbors,
                                             self.haar_flags, self.min_size)
        """ Now check the profile template """
        profile_faces = cv.HaarDetectObjects(self.small_image,
                                             self.cascade_profile,
                                             cv.CreateMemStorage(0),
                                             self.haar_scale,
                                             self.min_neighbors,
                                             self.haar_flags, self.min_size)
        """ Lastly, check a different frontal profile """
        #faces = cv.HaarDetectObjects(self.small_image, self.cascade_frontal_alt2, cv.CreateMemStorage(0),
        #                                 self.haar_scale, self.min_neighbors, self.haar_flags, self.min_size)
        #profile_faces.extend(faces)
        '''if not frontal_faces and not profile_faces:
            if self.show_text:
                text_font = cv.InitFont(cv.CV_FONT_VECTOR0, 3, 2, 0, 3)
                cv.PutText(self.marker_image, "NO FACES!", (50, int(self.image_size[1] * 0.9)), text_font, cv.RGB(255, 255, 0))'''

        faces_boxes = []
        for ((x, y, w, h), n) in frontal_faces + profile_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 * self.image_scale), int(y * self.image_scale))
            pt2 = (int(
                (x + w) * self.image_scale), int((y + h) * self.image_scale))

            face_box = (pt1[0], pt1[1], pt2[0], pt2[1])
            faces_boxes.append(face_box)
        return faces_boxes
    def find_face(self, image):

        w, h = cv.GetSize(image)

        # I actually think cv.CreateImage returns a BGR image, but it gets gray-scaled in the line after:
        grayscale = cv.CreateImage((w, h), 8, 1)
        cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)

        # note: if face detecton seems off you might have to tweak the minimum object size argument
        faces = cv.HaarDetectObjects(grayscale, self.face_cascade,
                                     self.storage, 1.2, 2, 0, (300, 250))

        if faces:
            print 'face detected!'

            # TODO: if it found more than 1 face it will return before cycling through each:
            for f in faces:
                self.frames_since_face = 0
                self.last_face_position = f  # remember this face as the last one, again for the no-face-detected case
                self.drawrect(
                    image, f[0], (0, 255, 0)
                )  # this draws a green (black in grayscale) rectangle to frame the object that was found
                return f

        # if it didn't find a face it will draw one where the last one was, so there's no blank. this is a good guess anyway
        # (BUG (sorta): I think if 2 or more faces were detected in the last frame, this will only draw the most recent of them)
        elif self.last_face_position:
            # print 'can\'t find face, using old postion'
            self.frames_since_face += 1
            f = self.last_face_position
            self.drawrect(image, f[0], (0, 100, 200))  # gray in grayscale
            return f
        else:
            print 'no face'
Exemple #9
0
def detect_and_draw(img, cascade):
    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, cascade, cv.CreateMemStorage(0),
                                     haar_scale, min_neighbors, haar_flags, min_size)
        index = 0 
        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
                x1, y1 = (int(x * image_scale), int(y * image_scale))
                x2, y2 = (int((x + w) * image_scale), int((y + h) * image_scale))

                pi = Image.fromstring("L", cv.GetSize(gray), gray.tostring())
                pi = pi.crop((x1, y1, x2, y2))
                pi = pi.resize((64, 64), Image.ANTIALIAS)
                path = os.path.join(sys.argv[1])
                pi.save(path)
                index += 1 
        else:
            os.remove(sys.argv[1])
def show_photo():
    # Get the photo
    img = c.get_photo() \
        .get_response() \
        .resize((300, 300), Img.ANTIALIAS)

    # Convert the photo for OpenCV
    cv_img = cv.CreateImageHeader(img.size, cv.IPL_DEPTH_8U, 1)
    cv.SetData(cv_img, img.tostring())

    # Find any faces in the image
    storage = cv.CreateMemStorage(0)
    cv.EqualizeHist(cv_img, cv_img)
    faces = cv.HaarDetectObjects(cv_img, cascade, storage, 1.2, 2,
                                 cv.CV_HAAR_DO_CANNY_PRUNING)

    if faces:
        for f in faces:
            # Draw a border around a found face.
            draw = ImageDraw.Draw(img)
            draw.setfill(0)
            draw.rectangle([(f[0][0], f[0][1]),
                            (f[0][0] + f[0][2], f[0][1] + f[0][3])])

    image = PhotoImage(img)
    img_face.config(image=image)
    img_face.img = image

    img_face.after(10, show_photo)
Exemple #11
0
def detectFaces(im):
    # This function takes a PIL image and finds the patterns defined in the
    # haarcascade function modified from: http://www.lucaamore.com/?p=638

    # Convert a PIL image to a greyscale cv image
    # from: http://pythonpath.wordpress.com/2012/05/08/pil-to-opencv-image/
    im = im.convert('L')
    cv_im = cv.CreateImageHeader(im.size, cv.IPL_DEPTH_8U, 1)
    cv.SetData(cv_im, im.tobytes(), im.size[0])

    # variables
    min_size = (20, 20)
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Equalize the histogram
    cv.EqualizeHist(cv_im, cv_im)

    # Detect the faces
    faces = cv.HaarDetectObjects(cv_im, faceCascade, cv.CreateMemStorage(0),
                                 haar_scale, min_neighbors, haar_flags,
                                 min_size)

    return faces
Exemple #12
0
def detect_faces(image):
    faces = []
    detected = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))
    if detected:
        for (x,y,w,h),n in detected:
            faces.append((x,y,w,h))
    return faces
Exemple #13
0
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, 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)

    cv.ShowImage("result", img)
def normalisation(src):

    res = []

    # On fait une copie l'image pour le traitement (en gris)
    gris = cv.CreateImage((src.width, src.height), cv.IPL_DEPTH_8U, 1)
    normal = cv.CreateImage((NORM_W, NORM_H), cv.IPL_DEPTH_8U, 1)
    cv.CvtColor(src, gris, cv.CV_BGR2GRAY)

    # On detecte les visages (objects) sur l'image copiee
    faces = cv.HaarDetectObjects(gris, face_path, cv.CreateMemStorage())
    print "Nombre faces detectes : " + str(len(faces))
    for (x, y, w, h), n in faces:
        tmp = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)
        cv.GetRectSubPix(gris, tmp, (float(x + w / 2), float(y + h / 2)))

        cv.Resize(tmp, normal)
        cv.EqualizeHist(normal, normal)

        #Detection oeil nez bouche sur l'image source:
        d = detection(normal)

        # On detecte au moins 2 yeux "normaux", au moins un oeil avec lunette, au moins une bouche et au moins un nez
        if ((len(d['eyes']) >= 2 or len(d['eyes2']) >= 1)
                and len(d['mouth']) >= 1 and len(d['nose']) >= 1):
            print "Visage detecte dans la photo"
            res.append((normal, (x, y, w, h)))
    return res
Exemple #15
0
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
Exemple #16
0
    def detect(self, im):
        ''' Runs the cascade classifer on an image. '''
        image = im.asOpenCV()

        min_size = (self.min_size[0], self.min_size[1])

        # Create a resized gray scale image
        if image.nChannels == 3:
            gray = cv.CreateImage((image.width, image.height), image.depth, 1)
            cv.CvtColor(image, gray, cv.CV_BGR2GRAY)
            image = gray

        image = self._resizeImage(image, self.image_scale)

        # Equalize the image
        cv.EqualizeHist(image, image)

        # Detect faces
        faces = cv.HaarDetectObjects(image, self.cascade, self.storage,
                                     self.haar_scale, self.min_neighbors,
                                     self.haar_flags, min_size)

        # Transform and return the points
        result = []
        for r in faces:
            rect = pv.Rect(r[0][0] / self.image_scale,
                           r[0][1] / self.image_scale,
                           r[0][2] / self.image_scale,
                           r[0][3] / self.image_scale)
            result.append(rect)

        return result
    def __init__(self, image_name, cascade):
        try:
            image = cv.LoadImage(image_name, 1)
        except IOError:
            return
        except:
            return
        else:
            self.faces = []
            #Allocate Space for grayscale image and tiny image
            #Dramatically reduces computation time in exchange for temporary space
            grayscale = cv.CreateImage((image.width, image.height), 8, 1)
            img = cv.CreateImage((cv.Round(image.width / IMAGE_SCALE),
                                  cv.Round(image.height / IMAGE_SCALE)), 8, 1)

            cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
            cv.Resize(grayscale, img, cv.CV_INTER_LINEAR)
            cv.EqualizeHist(img, img)

            matches = cv.HaarDetectObjects(img, cascade,
                                           cv.CreateMemStorage(0), HAAR_SCALE,
                                           IMAGE_SCALE, HAAR_FLAGS, MIN_SIZE)
            for ((x, y, width, height), wat) in matches:
                self.faces.append({
                    "x": x,
                    "y": y,
                    "width": width,
                    "height": height
                })
            self.name = image_name
Exemple #18
0
def detect_and_save(img, cascade, output_name):
    # 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, cascade,
                                     cv.CreateMemStorage(0), haar_scale,
                                     min_neighbors, haar_flags, min_size)
        t = cv.GetTickCount() - t
        print "detection time = %gms" % (t / (cv.GetTickFrequency() * 1000.))
        f = open(output_name, 'w')
        if faces:
            for ((x, y, w, h), n) in faces:
                f.write("%d %d %d %d\n" % (x, y, w, h))
Exemple #19
0
    def detect(self, image):
        """
        Determines the location of one or more faces in the given image.
        """
        if isinstance(image, basestring):
            image = cv.LoadImage(image)

        image_size = cv.GetSize(image)

        # Convert to grayscale.
        grayscale = cv.CreateImage(image_size, 8, 1)
        cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
        #cv.EqualizeHist(grayscale, grayscale)
        _image = image
        image = grayscale

        # Assume an image equal to the target size contains a single face.
        target_size = (self.target_width, self.target_height)
        if image_size == target_size:
            rect = 0, 0, self.target_width, self.target_height
            neighbors = None
            return [(rect, neighbors)], image

        # Locate one or more faces in the image.
        t0 = time.time()
        faces = cv.HaarDetectObjects(image, self.face_cascade,
                                     cv.CreateMemStorage(0), 1.2, 2, 0,
                                     (20, 20))
        t1 = time.time() - t0
        LOG.info('Haar detect took %.2f seconds.' % (t1, ))
        return faces, image
Exemple #20
0
    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 []
Exemple #21
0
    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()
Exemple #22
0
def Detect_Face(Img, faceCascade, Give_Image=False):
    # Detects face with haarcascade -- http://www.lucaamore.com/?p=638

    # Set haarcascade object options
    HaarScale = 1.1
    HaarFlags = 0
    MinSize = (20, 20)
    MinNeighbouring = 3

    # Equalize the histogram
    cv.EqualizeHist(Img, Img)

    # Detection of the user's face
    Faces = cv.HaarDetectObjects(Img, faceCascade, cv.CreateMemStorage(0),
                                 HaarScale, MinNeighbouring, HaarFlags,
                                 MinSize)

    # Draw rectangles when found
    if Faces and Give_Image:
        for ((x, y, w, h), n) in Faces:
            # Set two CV Points in order to draw the rectangular box.
            Point1 = (int(x), int(y))
            Point2 = (int(x + w), int(y + h))
            cv.Rectangle(Img, Point1, Point2, cv.RGB(255, 0, 0), 5, 8, 0)

    if Give_Image:
        return Img
    else:
        return Faces
def DetectFace(image, faceCascade, returnImage=False):
    # This function takes a grey scale cv image and finds
    # the patterns defined in the haarcascade function
    # modified from: http://www.lucaamore.com/?p=638

    #variables
    min_size = (20, 20)
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Equalize the histogram
    cv.EqualizeHist(image, image)

    # Detect the faces
    faces = cv.HaarDetectObjects(image, faceCascade, cv.CreateMemStorage(0),
                                 haar_scale, min_neighbors, haar_flags,
                                 min_size)

    # If faces are found
    if faces and returnImage:
        for ((x, y, w, h), n) in faces:
            # Convert bounding box to two CvPoints
            pt1 = (int(x), int(y))
            pt2 = (int(x + w), int(y + h))
            cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)

    if returnImage:
        return image
    else:
        return faces
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 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)
Exemple #26
0
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)
Exemple #27
0
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)
Exemple #28
0
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 []
Exemple #29
0
    def get_features(self):
        engine = self.context.modules.engine

        mode, converted_image = engine.image_data_as_rgb(False)
        size = engine.size

        image = cv.CreateImageHeader(size, cv.IPL_DEPTH_8U, 3)
        cv.SetData(image, converted_image)

        gray = cv.CreateImage(size, 8, 1)
        convert_mode = getattr(cv, 'CV_%s2GRAY' % mode)
        cv.CvtColor(image, gray, convert_mode)

        min_size = self.get_min_size_for(size)
        haar_scale = 1.2
        min_neighbors = 3

        cv.EqualizeHist(gray, gray)

        faces = cv.HaarDetectObjects(gray, self.__class__.cascade,
                                     cv.CreateMemStorage(0), haar_scale,
                                     min_neighbors,
                                     cv.CV_HAAR_DO_CANNY_PRUNING, min_size)

        faces_scaled = []

        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
            x2, y2 = (x + w), (y + h)
            faces_scaled.append(((x, y, x2 - x, y2 - y), n))

        return faces_scaled
Exemple #30
0
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