Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Face detect and crop by using OpenCV
import cv2
import sys
import os
class FaceCropper(object):
CASCADE_PATH = "data/haarcascades/haarcascade_frontalface_default.xml"
def __init__(self):
self.face_cascade = cv2.CascadeClassifier(self.CASCADE_PATH)
def generate(self, image_path, show_result):
img = cv2.imread(image_path)
if (img is None):
print("Can't open image file")
return 0
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(img, 1.1, 3, minSize=(100, 100))
if (faces is None):
print('Failed to detect face')
return 0
if (show_result):
for (x, y, w, h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
facecnt = len(faces)
print("Detected faces: %d" % facecnt)
i = 0
height, width = img.shape[:2]
for (x, y, w, h) in faces:
r = max(w, h) / 2
centerx = x + w / 2
centery = y + h / 2
nx = int(centerx - r)
ny = int(centery - r)
nr = int(r * 2)
faceimg = img[ny:ny+nr, nx:nx+nr]
lastimg = cv2.resize(faceimg, (32, 32))
i += 1
cv2.imwrite("image%d.jpg" % i, lastimg)
if __name__ == '__main__':
args = sys.argv
argc = len(args)
if (argc != 2):
print('Usage: %s [image file]' % args[0])
quit()
detecter = FaceCropper()
detecter.generate(args[1], True)
@aniket822
Copy link

aniket822 commented Dec 7, 2019

Hi Sir, i am trying this code but showing this error

detecter.generate(args[1], True)

IndexError: list index out of range

out of range is showing

@MohammedYaseen97
Copy link

MohammedYaseen97 commented Mar 9, 2020

Hi Sir, i am trying this code but showing this error

detecter.generate(args[1], True)

IndexError: list index out of range

out of range is showing

hii .. you have to run the file using the following command :

"python face_cropper.py [your_image_path]"

here, [your_image_path] is a string which contains the location/name of the image you want to crop, which the code takes as args[1] .. you cannot leave that blank

@Tun555
Copy link

Tun555 commented May 7, 2020

hey ammm. i am begining pls tell me . how to run this code in spyder now i can import every module but i can't run anything. it tell IndexError: list index out of range

@aleemahmed96
Copy link

aleemahmed96 commented Oct 29, 2020

For all having problems use this line from documentation and insert on line 7 (don't need to use CASCADE_PATH now; it will automatically detect the path your filesystem has):
Cascade_path is useful only the places where have you deployed the code remotely i.e Docker container, Cloud Services etc

        self.face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

Documentation Reference: opencv-Pypi

@aleemahmed96
Copy link

aleemahmed96 commented Oct 29, 2020

hey ammm. i am begining pls tell me . how to run this code in spyder now i can import every module but i can't run anything. it tell IndexError: list index out of range

This is a problem with your image, I suggest you compress the image and then run, I had the same issue and compressed the image to <500kB then it worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment