def test_image(image_to_check, tolerance=0.6): recognized_faces = [] unknown_image = face_recognition.load_image_file(image_to_check) # Scale down image if it's giant so things run a little faster unknown_image = scale_image(unknown_image) unknown_encodings = face_recognition.face_encodings(unknown_image) face_landmarks_list = face_recognition.face_landmarks(unknown_image) face_locations = face_recognition.face_locations(unknown_image) pil_image = Image.fromarray(unknown_image) d = ImageDraw.Draw(pil_image) if not unknown_encodings: # print out fact that no faces were found in image print_result(image_to_check, "no_persons_found", None) else: for unknown_encoding, face_landmarks, face_location in zip(unknown_encodings, face_landmarks_list, face_locations): distances = face_recognition.face_distance(known_face_encodings, unknown_encoding) for distance, name in zip(distances, known_names): if distance <= tolerance: print_result(image_to_check, name, distance) recognized_faces.append( {'name': name, 'dist': distance, 'landmarks': face_landmarks, 'face_location': face_location} ) else: print_result(image_to_check, "unknown_person", None) for item in recognized_faces: face_landmarks = item['landmarks'] face_location = item['face_location'] # Print the location of each facial feature in this image # Let's trace out each facial feature in the image with a line! for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) d.line(face_landmarks[facial_feature], width=3) # Print the location of each face in this image top, right, bottom, left = face_location print( "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right)) d.rectangle(((left, top), (right, bottom)), outline=4) font = ImageFont.truetype("font/arial.ttf", size=30) title = item['name'] text_size = d.textsize(title, font) d.text((left, bottom - text_size[1]), title, font=font, fill='white') pil_image.save("data/recognition_results/result.jpg") return recognized_faces
def get_face(img, target_encodings): img = np.array(img) locations = face_recognition.face_locations(img, model="cnn") encodings = face_recognition.face_encodings(img, locations) landmarks = face_recognition.face_landmarks(img, locations) if len(locations) == 0: return None, None, None, None, None if target_encodings is not None: distances = [ face_recognition.face_distance([target_encodings], encoding) for encoding in encodings ] idx_closest = distances.index(min(distances)) target_face, target_landmarks = locations[idx_closest], landmarks[idx_closest] else: target_face, target_landmarks = locations[0], landmarks[0] top, right, bottom, left = target_face x, y, w, h = left, top, right-left, bottom-top return x, y, w, h, target_landmarks
def get_image(): image_b64 = request.values['imageBase64'] file = io.BytesIO(urllib.request.urlopen(image_b64).read()) image_PIL = Image.open(file) print ('image opened pil') #image_np = np.array(image_PIL) #print ('Image received: {}'.format(image_np.shape)) image_PIL.save('static/img/rec.png') print ('Image received') image = face_recognition.load_image_file('static/img/rec.png') face_landmarks_list = face_recognition.face_landmarks(image) pil_image = Image.fromarray(image) prettyImg = makePretty(face_landmarks_list,pil_image,'static/img/') return ''
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("biden.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) for face_landmarks in face_landmarks_list: pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image, 'RGBA') # Make the eyebrows into a nightmare d.polygon(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 128)) d.polygon(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 128)) d.line(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 150), width=5) d.line(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 150), width=5) # Gloss the lips d.polygon(face_landmarks['top_lip'], fill=(150, 0, 0, 128)) d.polygon(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128)) d.line(face_landmarks['top_lip'], fill=(150, 0, 0, 64), width=8) d.line(face_landmarks['bottom_lip'], fill=(150, 0, 0, 64), width=8) # Sparkle the eyes d.polygon(face_landmarks['left_eye'], fill=(255, 255, 255, 30)) d.polygon(face_landmarks['right_eye'], fill=(255, 255, 255, 30)) # Apply some eyeliner d.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill=(0, 0, 0, 110), width=6)
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", help="If image based, path to image") args = vars(ap.parse_args()) if not args.get("image", True): process_this_frame = True # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0,0), fx=0.25, fy=0.25) face_landmark_list = face_recognition.face_landmarks(small_frame) for landmark in face_landmark_list: cv2.fillPoly(small_frame, np.array([landmark['left_eye']]), (255,255,255)) cv2.fillPoly(small_frame, np.array([landmark['right_eye']]), (255,255,255)) cv2.fillPoly(small_frame, np.array([get_eye_circ_coord(landmark['left_eye'])], dtype=np.int32), (0,0,0)) cv2.fillPoly(small_frame, np.array([get_eye_circ_coord(landmark['right_eye'])], dtype=np.int32), (0,0,0)) cv2.imshow("Video", small_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
def detect_landmarks(face_img): landmakrs = face_recognition.face_landmarks(face_img) return landmakrs[0] if len(landmakrs) > 0 else None
import face_recognition import cv2 import PIL.Image import PIL.ImageDraw import os from PIL import Image, ImageDraw a="kn.png" image=cv2.imread(a) pil_image = PIL.Image.fromarray(image) face_landmarks_list = face_recognition.face_landmarks(image) d = ImageDraw.Draw(pil_image) print(face_landmarks_list) k = face_landmarks_list[0]['top_lip'] left =right=face_landmarks_list[0]['top_lip'][0][0] bottom = face_landmarks_list[0]['top_lip'][0][1] for k1 in k : if(left>k1[0]): left = k1[0] if(right<k1[0]): right = k1[0] if(bottom>k1[1]): bottom=k1[1] k = face_landmarks_list[0]['nose_tip'] top =face_landmarks_list[0]['nose_tip'][0][1] for k1 in k : if(top<k1[1]): top=k1[1] print("ss")
def detect_lmks(frame): lmks = face_recognition.face_landmarks(frame) return lmks[0]
def mask_processing(face_image_file_name): # 이미지 경로 생성 face_image_path = 'data/without_mask/' + face_image_file_name mask_image_path = 'data/mask.png' # 얼굴 영역 추출, 얼굴 랜드마크 추출 face_image_np = face_recognition.load_image_file(face_image_path) face_locations = face_recognition.face_locations(face_image_np) face_landmarks = face_recognition.face_landmarks(face_image_np, face_locations) # 결과 이미지 생성 face_image = Image.fromarray(face_image_np) mask_image = Image.open(mask_image_path) face_count = 0 # 마스크 합성 for face_landmark in face_landmarks: if ('nose_bridge' not in face_landmark) or ('chin' not in face_landmark): continue # 마스크 너비 보정값 mask_width_ratio = 1.2 # 마스크 높이 계산 (nose_bridge 2번째 점, chin 9번째 점의 길이) mask_height = int( distance_point_to_point(face_landmark['nose_bridge'][1], face_landmark['chin'][8])) # 마스크 좌/우 분할 mask_left_image = mask_image.crop( (0, 0, mask_image.width // 2, mask_image.height)) mask_right_image = mask_image.crop( (mask_image.width // 2, 0, mask_image.width, mask_image.height)) # 왼쪽 얼굴 너비 계산 mask_left_width = int( distance_point_to_line( face_landmark['chin'][0], face_landmark['nose_bridge'][0], face_landmark['chin'][8]) * mask_width_ratio) # 왼쪽 마스크 크기 조절 mask_left_image = mask_left_image.resize( (mask_left_width, mask_height)) # 오른쪽 얼굴 너비 계산 mask_right_width = int( distance_point_to_line( face_landmark['chin'][16], face_landmark['nose_bridge'][0], face_landmark['chin'][8]) * mask_width_ratio) # 오른쪽 마스크 크기 조절 mask_right_image = mask_right_image.resize( (mask_right_width, mask_height)) # 좌/우 마스크 연결 mask_image = Image.new( 'RGBA', (mask_left_width + mask_right_width, mask_height)) mask_image.paste(mask_left_image, (0, 0), mask_left_image) mask_image.paste(mask_right_image, (mask_left_width, 0), mask_right_image) # 얼굴 회전 각도 계산 dx = face_landmark['chin'][8][0] - face_landmark['nose_bridge'][0][0] dy = face_landmark['chin'][8][1] - face_landmark['nose_bridge'][0][1] face_radian = np.arctan2(dy, dx) face_degree = np.rad2deg(face_radian) # 마스크 회전 mask_degree = (90 - face_degree + 360) % 360 mask_image = mask_image.rotate(mask_degree, expand=True) # 마스크 위치 계산 mask_radian = np.deg2rad(-mask_degree) center_x = (face_landmark['nose_bridge'][1][0] + face_landmark['chin'][8][0]) // 2 center_y = (face_landmark['nose_bridge'][1][1] + face_landmark['chin'][8][1]) // 2 p1 = rotate_point( (center_x, center_y), (center_x - mask_left_width, center_y - mask_height // 2), mask_radian) p2 = rotate_point( (center_x, center_y), (center_x - mask_left_width, center_y + mask_height // 2), mask_radian) p3 = rotate_point( (center_x, center_y), (center_x + mask_right_width, center_y - mask_height // 2), mask_radian) p4 = rotate_point( (center_x, center_y), (center_x + mask_right_width, center_y + mask_height // 2), mask_radian) box_x = int(min(p1[0], p2[0], p3[0], p4[0])) box_y = int(min(p1[1], p2[1], p3[1], p4[1])) # 마스크 합성(붙여넣기) face_image.paste(mask_image, (box_x, box_y), mask_image) face_count += 1 # 결과 이미지 반환 return face_image, face_count
def find_landmarks(img): landmarks_found = face_landmarks(np.array(img)) if len(landmarks_found) > 0: return dict_to_list(landmarks_found[0]) else: raise Exception("Failed to find face landmarks for one of the images.")