-
Notifications
You must be signed in to change notification settings - Fork 0
/
CropFaceFromImage.py
36 lines (25 loc) · 998 Bytes
/
CropFaceFromImage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import cv2
class CropFace:
def __init__(self, imagepath):
self.imagepath = imagepath
def cropimages(self):
image = cv2.imread(self.imagepath)
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
faces = face_cascade.detectMultiScale(
image_gray, scaleFactor=1.3, minNeighbors=5)
faces_found = []
for x, y, w, h in faces:
facecrop = image[y:y + h, x:x + w]
faces_found.append(facecrop)
return faces_found
def saveimages(self, facesarray):
if len(facesarray) == 0:
print("No faces found, try another image please")
for i, face in enumerate(facesarray):
cv2.imwrite("face-" + str(i) + ".jpg", face)
print("Saved image as face-" + str(i))
if __name__ == "__main__":
crop = CropFace("img1.jpg")
faces = crop.cropimages()
crop.saveimages(faces)