|
| 1 | +## This program first ensures if the face of a person exists in the given image or not then if it exists, it crops |
| 2 | +## the image of the face and saves to the given directory. |
| 3 | + |
| 4 | +## Importing Modules |
| 5 | +import cv2 |
| 6 | +import os |
| 7 | + |
| 8 | + |
| 9 | +################################################################################# |
| 10 | + |
| 11 | +##Make changes to these lines for getting the desired results. |
| 12 | + |
| 13 | +## DIRECTORY of the images |
| 14 | +directory = "#" |
| 15 | + |
| 16 | +## directory where the images to be saved: |
| 17 | +f_directory = "#" |
| 18 | + |
| 19 | +################################################################################ |
| 20 | + |
| 21 | +def facecrop(image): |
| 22 | + ## Crops the face of a person from any image! |
| 23 | + |
| 24 | + ## OpenCV XML FILE for Frontal Facial Detection using HAAR CASCADES. |
| 25 | + facedata = "haarcascade_frontalface_alt.xml" |
| 26 | + cascade = cv2.CascadeClassifier(facedata) |
| 27 | + |
| 28 | + ## Reading the given Image with OpenCV |
| 29 | + img = cv2.imread(image) |
| 30 | + |
| 31 | + try: |
| 32 | + ## Some downloaded images are of unsupported type and should be ignored while raising Exception, so for that |
| 33 | + ## I'm using the try/except functions. |
| 34 | + |
| 35 | + minisize = (img.shape[1],img.shape[0]) |
| 36 | + miniframe = cv2.resize(img, minisize) |
| 37 | + |
| 38 | + faces = cascade.detectMultiScale(miniframe) |
| 39 | + |
| 40 | + for f in faces: |
| 41 | + x, y, w, h = [ v for v in f ] |
| 42 | + cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2) |
| 43 | + |
| 44 | + sub_face = img[y:y+h, x:x+w] |
| 45 | + |
| 46 | + f_name = image.split('/') |
| 47 | + f_name = f_name[-1] |
| 48 | + |
| 49 | + ## Change here the Desired directory. |
| 50 | + cv2.imwrite(f_directory + f_name, sub_face) |
| 51 | + print ("Writing: " + image) |
| 52 | + |
| 53 | + except: |
| 54 | + pass |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + images = os.listdir(directory) |
| 58 | + i = 0 |
| 59 | + |
| 60 | + for img in images: |
| 61 | + file = directory + img |
| 62 | + print (i) |
| 63 | + facecrop(file) |
| 64 | + i += 1 |
0 commit comments