def main(): # Initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictor_path) fa = FaceAligner(predictor, desiredFaceWidth=182) # Load the input image, resize it, and convert it to grayscale image = cv2.imread(image_path) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Show the original input image and detect faces in the grayscale image cv2.imshow("Input", image) rects = detector(gray, 2) # Loop over the face detections for rect in rects: # Extract the ROI of the *original* face, then align the face using facial landmarks (x, y, w, h) = rect_to_bb(rect) face_orig = imutils.resize(image[y:y + h, x:x + w], width=256) face_aligned = fa.align(image, gray, rect) # Display the output images cv2.imshow("Original", face_orig) cv2.imshow("Aligned", face_aligned) cv2.waitKey(0)
def alignFace(predictotDLIB, imagePath): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() # print(args["shape_predictor"]) # predictor = dlib.shape_predictor("face_detection_model/shape_predictor_68_face_landmarks.dat") predictor = dlib.shape_predictor(predictotDLIB) fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, resize it, and convert it to grayscale image = cv2.imread(imagePath) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image #cv2.imshow("Input", image) rects = detector(gray, 2) # loop over the face detections faceAligned = None for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256) faceAligned = fa.align(image, gray, rect) # display the output images #cv2.imshow("Original", faceOrig) #cv2.imshow("Aligned", faceAligned) #cv2.waitKey(0) return faceAligned
def alignFace(frame): img = cv.imread("snap"+str(frame)+".jpg", 0) fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, resize it, and convert it to grayscale gray = resize(img, width=600) # show the original input image and detect faces in the grayscale # image rects = detector(gray, 2) # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks # (x, y, w, h) = rect_to_bb(rect) # faceOrig = resize(frame[y:y + h, x:x + w], width=256) faceAligned = fa.align(img, gray, rect) # import uuid # f = str(uuid.uuid4()) # cv.imwrite("foo/" + f + ".png", faceAligned) # display the output images cv.imshow("Aligned", faceAligned) # cv.waitKey(0) cv.imwrite("roi"+str(frame)+".jpg", faceAligned)
def FaceAlign(image, shape_predictor="assets/shape_predictor_68_face_landmarks.dat"): ''' return a list of aligned faces ''' faceDetector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(shape_predictor) fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, rcv2_imshowesize it, and convert it to grayscale image = cv2.imread(image) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect faces in the grayscale image rects = faceDetector(gray, 2) # maintain a list of aligned images images = [] # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256) faceAligned = fa.align(image, gray, rect) cv2_imshow(faceAligned) # save output images images.append(faceAligned) return images
def __init__(self, shape_predictor_path="models\\shape_predictor_68_face_landmarks.dat"): try: self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor(shape_predictor_path) self.aligner = FaceAligner(self.predictor, desiredFaceWidth=256) except Exception as e: print(f"[ERROR] {self.__class__.__name__} model {shape_predictor_path} not found... : {e}")
def face_align(directory, embd): """ Aligns the face """ # initialize dlib's face detector (HOG+linear classifier) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() ### this is a pretrained model- trained on a labeled set of facial landmarks on images. This maps the location of (x,y) coordinates predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') fa = FaceAligner(predictor, desiredFaceWidth=256) directory = directory names = dict() for filename in os.listdir(directory): name, extension = filename.split(".") print(f'name: {name}') # load the input image, resize it, and convert it to grayscale image = cv2.imread(directory + '/' + name + '.jpg') image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image cv2.imshow("Input", image) rects = detector(gray, 2) # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) #faceOrig = imutils.resize(image[y:y + h, x:x + w], width=160) faceAligned = fa.align(image, gray, rect) faceAligned1 = imutils.resize(faceAligned, width=160) path = embd + f'{name}_aligned.jpg' cv2.imwrite(path, faceAligned1)
def __init__(self): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor( 'model/shape_predictor_68_face_landmarks.dat') self.fa = FaceAligner(self.predictor, desiredFaceWidth=256)
def create_database(group_folder): in_folder = group_folder + 'images/original/' out_folder = group_folder + 'images/faces/' if not os.path.exists(out_folder): os.mkdir(out_folder) detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( 'detectors/shape_predictor_68_face_landmarks.dat') fa = FaceAligner(predictor, desiredFaceWidth=256) for _dir in glob.glob(in_folder + '*'): _id = os.path.basename(_dir) if not os.path.exists(out_folder + _id + '/'): os.mkdir(out_folder + _id + '/') for _file in glob.glob(_dir + '/*'): filename = os.path.basename(_file) print(_file) image = cv2.imread(_file) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image rects = detector(gray, 2) i = 0 # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceAligned = fa.align(image, gray, rect) outputname = out_folder + _id + '/' + filename print(outputname) cv2.imwrite(outputname, faceAligned) i += 1
def align_face(path, output_path, width): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(SHAPE_PREDICTOR) fa = FaceAligner(predictor, desiredFaceWidth=width) # load the input image, resize it, and convert it to grayscale image = cv2.imread(path) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image cv2.imshow("Input", image) rects = detector(gray, 2) rect = rects[0] # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=width) faceAligned = fa.align(image, gray, rect) print('writing to {}'.format(output_path)) cv2.imwrite(output_path, faceAligned)
def __init__(self, desired_face_width=200): self.detector = dlib.get_frontal_face_detector() # TODO: allow less landmarks: https://github.com/davisking/dlib-models predictor = dlib.shape_predictor( "./Models/face_detection/shape_predictor_68_face_landmarks.dat") self.fa = FaceAligner(predictor, desiredFaceWidth=desired_face_width) self.desired_face_width = desired_face_width
def align_a_sample(img): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceWidth=256) #img = imutils.resize(img, width=800) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) rects = detector(gray, 2) faceAligned = 0 # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) #faceOrig = imutils.resize(img[y:y + h, x:x + w], width=256) faceAligned = fa.align(img, gray, rect) return faceAligned
def facealine(self, zippar): rpath, wpath, size = zippar detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("./shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceWidth=size) # load the input image, resize it, and convert it to grayscale image = cv2.imread(rpath) try: image = imutils.resize(image, width=1200) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) except: print(rpath) # show the original input image and detect faces in the grayscale # image try: rect = detector(gray, 2)[0] # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=size) faceAligned = fa.align(image, gray, rect) # display the output images cv2.imwrite(wpath, faceAligned) except: self.resizePic(rpath, wpath, size) return True
def crop_to_save(ac, face_path, save_path=None, cover=True): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictor_path) fa = FaceAligner(predictor, desiredFaceWidth=256) image = cv2.imread(face_path) # image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # cv2.imshow("Input", image) rects = detector(gray) if cover: save_path = face_path for rect in rects: (x, y, w, h) = face_utils.rect_to_bb(rect) faceAligned = fa.align(image, gray, rect) ac.crop(faceAligned, save_path) # cv2.imshow("Original", faceOrig) # cv2.imshow("Aligned", faceAligned) # cv2.waitKey(0) break # ac = AutoCrop() # crop_to_save(ac, face_path)
def __init__(self, imgs_path, blur=1, clusterSize=5, equalize=1, model='hog', sortpath="./Results", align_face=1): self.images = list() self.blur = True if blur == 1 else False self.equalize = True if equalize == 1 else False if model == 'hog' or model == 'cnn': self.model = model else: self.model = 'hog' self.clusterSize = clusterSize if clusterSize > 0 else 5 self.sortPath = sortpath self.alignFace = True if align_face == 1 else False predictor = dlib.shape_predictor('models/sp_68_point.dat') self.aligner = FaceAligner(predictor, desiredFaceWidth=300) if not os.path.exists(imgs_path): print('The specified image folder path does not exist.') exit(0) for root, dirnames, files in os.walk(imgs_path): for image in files: if image.lower().endswith('.jpg') or image.lower().endswith( '.png'): self.images.append(os.path.join(root, image)) self.images.sort()
def align_faces(image, h, w, net): shape_predictor = "/home/robocomp/robocomp/components/robocomp-viriato/components/faceTracking/files/shape_predictor_5_face_landmarks.dat" #faster # shape_predictor = "/home/robocomp/robocomp/components/robocomp-viriato/components/faceTracking/files/shape_predictor_68_face_landmarks.dat" predictor = dlib.shape_predictor(shape_predictor) fa = FaceAligner(predictor, desiredFaceWidth=300, desiredFaceHeight=400) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detections = net.forward() for i in range(0, detections.shape[2]): # # predictionextract the confidence (i.e., probability) associated with the confidence = detections[0, 0, i, 2] if confidence > 0.5: box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") rect = dlib.rectangle(left=startX, top=startY, right=endX, bottom=endY) print (rect) faceAligned = fa.align(image, gray, rect) return faceAligned
def faceAlign(image): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, resize it, and convert it to grayscale image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image # cv2.imshow("Input", image) rects = detector(gray, 2) # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256) faceAligned = fa.align(image, gray, rect) import uuid f = str(uuid.uuid4()) return faceAligned
def get_aligned_face(image, verbose=False): signature = 'utils.get_aligned_face' start_time = time.time() predictor = face_recognition.api.pose_predictor_68_point aligner = FaceAligner(predictor, desiredFaceWidth=256) if verbose: duration = time.time() - start_time print('%s:initialize aligner=%.4fs' % (signature, duration)) start_time = time.time() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) face_locations = face_recognition.face_locations(image) if len(face_locations) == 0: return None face_location = face_locations[0] top, right, bottom, left = face_location rect = dlib.rectangle(left=left, top=top, right=right, bottom=bottom) if verbose: duration = time.time() - start_time print('%s:locate face=%.4fs' % (signature, duration)) start_time = time.time() image = aligner.align(image, gray, rect) if verbose: duration = time.time() - start_time print('%s:align face=%.4fs' % (signature, duration)) return image
def detect_face(image_path, shape_predictor): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(shape_predictor) faceAligner = FaceAligner(predictor, desiredFaceWidth=160) image = cv2.imread(image_path, cv2.IMREAD_COLOR) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rectangles = detector(gray, 1) num_rectangles = len(rectangles) XY, aligned_images = [], [] if num_rectangles == 0: aligned_images.append(image) return aligned_images, image, XY else: for i in range(num_rectangles): aligned_image = faceAligner.align(image, gray, rectangles[i]) aligned_images.append(aligned_image) (x, y, w, h) = rect_to_bb(rectangles[i]) image = cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2) XY.append((x, y)) return np.array(aligned_images), image, XY
def align_faces(shape, path_to_images, image_name, path_to_aligned_images, rows, cols): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner try: print('ALIGNING AN IMAGE INSIDE ' + path_to_images) detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(shape) fa = FaceAligner(predictor, desiredLeftEye=(0.27, 0.27), desiredFaceWidth=cols, desiredFaceHeight=rows) # load the input image, resize it, and convert it to grayscale image = cv2.imread(os.path.join(path_to_images, image_name)) image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 2) if (len(rects) > 0): rect = rects[0] (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=cols, height=rows) faceAligned = fa.align(image, gray, rect) if path_to_aligned_images[-1] != '/': path_to_aligned_images += '/' img_split = image_name.split(".") path_adjust = path_to_images.replace('/', '_') image_name = path_adjust + img_split[0] + "_aligned.png" cv2.imwrite(path_to_aligned_images + image_name, faceAligned) except BaseException as e: print(e)
def load_image(image_path, shape_predictor): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(shape_predictor) fa = FaceAligner(predictor, desiredFaceWidth=160) image = cv2.imread(image_path, cv2.IMREAD_COLOR) if image is None: sys.exit(1) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 2) rect_nums = len(rects) XY, aligned_images = [], [] if rect_nums == 0: aligned_images.append(image) return aligned_images, image, rect_nums, XY else: for i in range(rect_nums): aligned_image = fa.align(image, gray, rects[i]) aligned_images.append(aligned_image) (x, y, w, h) = rect_to_bb(rects[i]) image = cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2) XY.append((x, y)) XY_ = str(XY) arr = str(np.array(aligned_images)) image_ = str(image) rect_nums_ = str(rect_nums) return np.array(aligned_images), image, rect_nums, XY
class DLIB: def __init__(self): self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor( 'models/shape_predictor_68_face_landmarks.dat') self.FaceAligner = FaceAligner(self.predictor, desiredFaceWidth=100, desiredLeftEye=(0.22, 0.22)) self.faces = np.empty(0) def detect(self, img): # return a np.ndarray containing datected grayscaled faces faces = [] if img.ndim == 2: gray = img else: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # grayscale rects = self.detector(gray, 2) # calculate rectangles of detected faces for rect in rects: if img.ndim == 2: faces.append(self.FaceAligner.align(img, gray, rect)) else: faces.append( cv2.cvtColor(self.FaceAligner.align(img, gray, rect), cv2.COLOR_BGR2GRAY)) self.faces = np.float16(faces)
def detect_face(path): detector = MTCNN() try: predictor = dlib.shape_predictor( "model/shape_predictor_68_face_landmarks.dat") except: print('can not open file shape_predictor_68_face_landmarks.dat ') fa = FaceAligner(predictor, desiredFaceWidth=256) #read image img = cv2.imread(path) gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # if result is empty then we try to replace size image faces = detector.detect_faces(img) print(np.array(faces).shape) if len(faces) == 0: return None, None, img box_news = [] faceAligneds = [] for i in range(0, len(faces)): box = faces[i]['box'] # only 1 face #convert dist to rtype: dlib.rectangle box_new = dlib.rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3]) box_news.append(box_new) #face alignment faceAligned = fa.align(img, gray_image, box_new) faceAligneds.append(faceAligned) return faceAligneds, box_news, img
def align_and_crop_face(image, shape_predictor='shape_predictor_68_face_landmarks.dat' ): # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( os.path.join(os.path.dirname(__file__), shape_predictor)) fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, resize it, and convert it to grayscale image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect faces in the grayscale image rects = detector(gray, 2) outputs = [] # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks faceAligned = fa.align(image, gray, rect) outputs.append(faceAligned) return outputs
def detect_face(self, image): # Create a face detector detector = dlib.get_frontal_face_detector() # Create a face aligner predictor = dlib.shape_predictor("./models/shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceHeight=64, desiredFaceWidth=64) # Get image directory image_name = image # Read, resize image and change to greyscale image = cv2.imread(image) image = imutils.resize(image, width=256) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Cropped and aligned faces face_imgs = np.empty((1, self.face_size, self.face_size, 3)) faces = detector(gray, 2) (x, y, w, h) = rect_to_bb(faces[0]) faceOrig = imutils.resize(image[y:y + h, x:x + w], height=64, width=64) faceAligned = fa.align(image, gray, faces[0]) face_imgs[0, :, :, :] = faceAligned # Get results results = self.model.predict(face_imgs) ages = np.arange(0, 70).reshape(70, 1) predicted_ages = results[0].dot(ages).flatten() index = int(round(predicted_ages[0], 0)) return index
def align_face_youtube_face(self): curr_directory = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) input_dir = os.path.join(curr_directory, 'input_dir') out_dir = os.path.join(curr_directory, 'out_dir') list_label = os.listdir(input_dir) # assert os.path.exists(out_dir) and len(os.listdir(out_dir)) <= 1 and self.args.shapePredictor is not None print('Face Aligning ...') detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( os.path.join(curr_directory, self.args.shapePredictor)) fa = FaceAligner(predictor, desiredFaceWidth=24, desiredFaceHeight=24) i = 0 while i < len(list_label): if list_label[i] is not '.DS_Store' and not os.path.exists( os.path.join(out_dir, list_label[i])): j = 0 print('label: ' + list_label[i]) label_path_in = os.path.join(input_dir, list_label[i]) label_path_out = os.path.join(out_dir, list_label[i]) frame_index_list = os.listdir(label_path_in) while j < len(frame_index_list): k = 0 frame_index_path = os.path.join(label_path_in, frame_index_list[j]) if frame_index_path is not '.DS_Store': input_label_dir = os.listdir(frame_index_path) while k < len(input_label_dir): if input_label_dir[k] is not '.DS_Store': image = cv2.imread( os.path.join(frame_index_path, input_label_dir[k])) if image is None: print('image failed: ' + os.path.join( frame_index_path, input_label_dir[k])) elif image is not None: # Bicubic Interpolation: # extension dari cubic interpolation, membuat permukaan gambar jadi lebih lembut # tuple dapat diisi dengan None (size'a bakal ngikutin yg default dari OpenCV) # a bicubic interpolation over 4x4 pixel neighborhood # image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC) gray = cv2.cvtColor( image, cv2.COLOR_RGB2BGR) rects = detector(gray, 3) for rect in rects: face_aligned = fa.align( image, gray, rect) if not os.path.exists(label_path_out): os.makedirs(label_path_out) cv2.imwrite( os.path.join( label_path_out, input_label_dir[k]), face_aligned) k += 1 j += 1 i += 1 print('Successfully face aligned and copy new dataset to output_dir')
def __init__(self): # initiate tensorflow object for face detection self.detection_graph = tf.Graph() with self.detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(self.file_face_detector, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') with self.detection_graph.as_default(): config = tf.ConfigProto() config.gpu_options.allow_growth = True self.sess = tf.Session(graph=self.detection_graph, config=config) self.windowNotSet = True # initiate face aligner predictor = dlib.shape_predictor(self.file_face_landmark) # percentage_face = (self.target_face_percent, self.target_face_percent) # construct face aligner self.faceAligner = FaceAligner( predictor, desiredFaceWidth=self.target_face_width, desiredFaceHeight=self.target_face_height, desiredLeftEye=(0.3, 0.3)) # load encodings self.load_encodings() # load svm models self.load_svm_model() # cascade haar self.face_cascade = cv2.CascadeClassifier(self.file_haar)
def detect_face(self, image): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( "./models/shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceHeight=64, desiredFaceWidth=64) image_name = image if (str(image_name).find(str.casefold(".jpg")) or str(image_name).find(str.casefold(".png"))): image_name_ = str(os.path.basename(image_name))[:-4] else: image_name_ = str(os.path.basename(image_name))[:-5] image = cv2.imread(image) image = imutils.resize(image, width=256) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) face_imgs = np.empty((1, self.face_size, self.face_size, 3)) faces = detector(gray, 2) (x, y, w, h) = rect_to_bb(faces[0]) faceOrig = imutils.resize(image[y:y + h, x:x + w], height=64, width=64) faceAligned = fa.align(image, gray, faces[0]) try: face_imgs[0, :, :, :] = faceAligned results = self.model.predict(face_imgs) predicted_genders = results[0] if (predicted_genders[0][0] > 0.5): gender = "Female" else: gender = "Male" except: pass return str(image_name_), gender
def alignFace_imutils(image): predictor = dlib.shape_predictor(PREDICTOR_PATH) cascade = cv2.CascadeClassifier(cascade_path) fa = FaceAligner(predictor, desiredFaceWidth=face_output_width) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=minNeighbors, minSize=minFaceSize, flags=cv2.CASCADE_SCALE_IMAGE) i = 0 for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) rect = dlib.rectangle(x, y, x + w, y + h) faceAligned = fa.align(image, gray, rect) cv2.imshow("Face #{}".format(i), image[y:y + h, x:x + w]) cv2.imshow("Aligned-{}".format(i), faceAligned) cv2.imwrite(output_folder + "align_" + str(i) + ".jpg", faceAligned) cv2.waitKey(0) i += 1 cv2.imwrite(output_folder + "faces.jpg", image)
def rotate_face(src_path, dst_path): ''' Function for de-rotating faces from tilted source images parameters: 'src_path' is the path to raw images; 'dst_path' is the path where de-rotated images are stored output: De-rotated face image at 1024x1024 resolution ''' landmarks_model_path = '../../cache/shape_predictor_68_face_landmarks.dat' detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(landmarks_model_path) # Use FaceAligner with parameters 'desiredFaceWidth' to set the output image resolution # and 'desiredLeftEye' to set the amount of zoom-out percentage fa = FaceAligner(predictor, desiredFaceWidth=1024, desiredLeftEye=(0.40, 0.40)) # load the input image and convert it to grayscale image = cv2.imread(src_path) gray = cv2.imread(src_path, 0) # Detect faces in the grayscale image rects = detector(gray) # loop over the detected faces for rect in rects: # Align the image and save it in PNG format faceAligned = fa.align(image, gray, rect) cv2.imwrite(dst_path, faceAligned)
def face_align(image): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("./model/shape_predictor_68_face_landmarks.dat") # 初始化 FaceAligner 类对象 fa = FaceAligner(predictor, desiredFaceWidth=256) # image = cv2.imread(img_path) image = imutils.resize(image, width=600) face_aligned = image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # cv2.imshow("gray", gray) # cv2.imshow("Input", image) rects = detector(gray, 2) #返回检测的人脸 print(rects) for rect in rects: # (x, y, w, h) = rect_to_bb(rect) # face_orig = imutils.resize(image[y:y + h, x:x + w], width=256) # 调用 align 函数对图像中的指定人脸进行处理 face_aligned = fa.align(image, gray, rect) # cv2.imshow("Original", face_orig) # cv2.imshow("Aligned", face_aligned) # cv2.waitKey(0) return face_aligned
def ff(img): """ :param img: :return: faceAligned[0] the aligned face version of the original input image """ # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor and the face aligner detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(str(_path) + "/shape_predictor_68_face_landmarks.dat") ######################## fa = FaceAligner(predictor, desiredFaceWidth=256) # load the input image, resize it, and convert it to grayscale image = img ########################################################## image = imutils.resize(image, width=800) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # show the original input image and detect faces in the grayscale # image #cv2.imshow("Input", image) rects = detector(gray, 2) lst = [] # loop over the face detections for rect in rects: # extract the ROI of the *original* face, then align the face # using facial landmarks (x, y, w, h) = rect_to_bb(rect) faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256) faceAligned = fa.align(image, gray, rect) import uuid f = str(uuid.uuid4()) cv2.imwrite("foo/" + f + ".png", faceAligned) # display the output images #cv2.imshow("Original", faceOrig) #cv2.imshow("Aligned", faceAligned) #cv2.waitKey(0) lst.append(faceAligned) return lst[0]
""" # if you want to use predefined path than define the path in a variable args = { "shape_predictor": "complete_path/shape_predictor_68_face_landmarks.dat", "image": "complete_path/input_image.jpg", "encodings": "complete_path/encodings.pickle", "detection_method": "cnn" } # initialize dlib's face detector and facial landmark predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(args["shape_predictor"]) face = FaceAligner(predictor, desiredFaceWidth=256) # Load input image, resize and convert it to grayscale image = cv2.imread(args["image"]) image = imutils.resize(image, width=500) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # detect faces in the grayscale image cv2.imshow("Input", image) rects = detector(gray, 1) # loop over the faces that are detected for (i, rect) in enumerate(rects): # Detected face landmark (x, y)-coordinates are converted into # Numpy array shape = predictor(gray, rect)