-2

I am having problems getting face detection and cropping an image to the face working, below is my code.

import cv2

class Crop:
    #constructor
    def __init__(self, image):
        self.data = image
    def facechop(self):
        # read xml for training data
        facedata = "haarcascade_frontalface_default.xml"
        cascade = cv2.CascadeClassifier(facedata)
        # read image file
        img = cv2.imread(self.data, 0)

        minisize = (img.shape[1], img.shape[0])
        miniframe = cv2.resize(img, minisize)

        faces = cascade.detectMultiScale(miniframe)
        for f in faces:
            x, y, w, h = [ v for v in f ]
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255))

            sub_face = self.data[y:y + h, x:x + w]

        # Show picture
        cv2.imshow('img', sub_face)
        return

input image file

picture = 'izz.jpg'
pic = Crop(gambar)

pic.facechop()

# keyboard input to destroy the window
while(True):
    key = cv2.waitKey(0)
    if key in [27, ord('Q'), ord('q')]:
        break

when it's running, it doesn't do raw after for function till sub_face = self.data[y:y + h, x:x + w]. It directly goes to cv2.imshow('img', sub_face). So, sub_face is not known. Why does it not work well? I'm using Aptana to debug it. Thank you.

Aphire
  • 1,621
  • 25
  • 55
Gusan
  • 411
  • 3
  • 5
  • 19

1 Answers1

0

Try changing your code to as follows:

import cv2

def crop(img):
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    sub_face = img

    faces = face_cascade.detectMultiScale(img, 1.1, 5)
    for (x,y,w,h) in faces:
        sub_face = img[y:y+h, x:x+w]

    return sub_face


imageToCrop = cv2.imread('izz.jpg',0)
croppedImage = crop(imageToCrop)

cv2.imshow('img',croppedImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
Aphire
  • 1,621
  • 25
  • 55
  • Thank you @Aphire, actually your code can running, but when i try to input this code to input the image file which has one face. `picture = 'izz.jpg' `pic = Crop(picture)` `pic.facechop()` like my post before. It's still get same error. – Gusan Apr 27 '15 at 15:16
  • Hang on, I will upload everything as a function inside the script, containing the correct way to load in an image. I will edit my post in a second. – Aphire Apr 27 '15 at 15:22
  • Okay try that, if no face is found, it will return the image uncropped – Aphire Apr 27 '15 at 15:28
  • It's working now. Now i'm trying to call it from another script. Thank you – Gusan Apr 27 '15 at 15:50
  • I would suggest just moving that function into the script you are working from, easier solution. If you accept my answer it will ensure this question doesn't get put in the "unanswered". (or get closed) – Aphire Apr 27 '15 at 15:53
  • Okay. I'll try to do that. – Gusan Apr 27 '15 at 16:08