|
| 1 | +''' |
| 2 | +Recognize and blur all faces in photos. |
| 3 | +''' |
| 4 | +import sys |
| 5 | +import cv2 |
| 6 | +import face_recognition |
| 7 | + |
| 8 | +def face_blur(src_img, dest_img, zoom_in=1): |
| 9 | + ''' |
| 10 | + Recognize and blur all faces in the source image file, then save as destination image file. |
| 11 | + ''' |
| 12 | + # Initialize some variables |
| 13 | + face_locations = [] |
| 14 | + photo = face_recognition.load_image_file(src_img) |
| 15 | + # Resize image to 1/zoom_in size for faster face detection processing |
| 16 | + small_photo = cv2.resize(photo, (0, 0), fx=1/zoom_in, fy=1/zoom_in) |
| 17 | + |
| 18 | + # Find all the faces and face encodings in the current frame of video |
| 19 | + face_locations = face_recognition.face_locations(small_photo, model="cnn") |
| 20 | + |
| 21 | + if face_locations: |
| 22 | + print(face_locations) |
| 23 | + else: |
| 24 | + print('Face not found') |
| 25 | + exit(1) |
| 26 | + |
| 27 | + #Blur all face |
| 28 | + photo = cv2.imread(src_img) |
| 29 | + for top, right, bottom, left in face_locations: |
| 30 | + # Scale back up face locations since the frame we detected in was scaled to 1/zoom_in size |
| 31 | + top *= zoom_in |
| 32 | + right *= zoom_in |
| 33 | + bottom *= zoom_in |
| 34 | + left *= zoom_in |
| 35 | + |
| 36 | + # Extract the region of the image that contains the face |
| 37 | + face_image = photo[top:bottom, left:right] |
| 38 | + |
| 39 | + # Blur the face image |
| 40 | + face_image = cv2.GaussianBlur(face_image, (21, 21), 0) |
| 41 | + |
| 42 | + # Put the blurred face region back into the frame image |
| 43 | + photo[top:bottom, left:right] = face_image |
| 44 | + |
| 45 | + #Save image to file |
| 46 | + cv2.imwrite(dest_img, photo) |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + if len(sys.argv) < 2: |
| 50 | + print('faceblur v1.0.0 (c) telesoho.com') |
| 51 | + print('Usage:python faceblur <src image> <dest image>') |
| 52 | + else: |
| 53 | + face_blur(sys.argv[1], sys.argv[2]) |
0 commit comments