Exemple #1
0
def _detect_faces(image_container):
    """Detects faces in a given image and returns it's bounding boxes and\
 facial landmarks.

    ### Parameters
        image: image to be searched on.

    ### Returns
        (bounding_box, facial_landmarks) for the face.
    """
    #print('_detect_faces - PID: {}'.format(os.getpid()))
    detected_faces = _mtcnn_detect_faces(image_container.image)

    if not detected_faces:
        return Result(
            'Failure',
            f' File: {image_container.image_path} had zero faces detected.')

    if len(detected_faces) > 1:
        _, keypoints = _extract_center_face(image_container.image.shape,
                                            detected_faces)
    else:
        #bounding_box = detected_faces[0]['box']
        keypoints = detected_faces[0]['keypoints']

    facial_landmarks = (keypoints['left_eye'], keypoints['right_eye'],
                        keypoints['nose'], keypoints['mouth_left'],
                        keypoints['mouth_right'])

    return Result('Success', image_container, args=facial_landmarks)
def _log_results(Result):
    """"""
    if Result.get_result() == "Success":
        logger.info(Result.get_payload())
        return True
    else:
        logger.error(Result.get_payload())
    return False
def _align_face(image_container, facial_landmarks, crop_shape=(112, 112)):
    """Align faces using the facial landmarks or the bounding box and crops\
 them.

    ### Parameters
        image: face image to be aligned.
        facial_landmarks: facial landmarks for the face in the image.
        bounding_box: optional bounding box.
        crop_shape: optional shape for the crop.

    ### Returns
        Face image aligned and cropped.
    """
    # print('_align_faces - PID: {}'.format(os.getpid()))

    # if crop_shape == (112, 112):
    #    pass
    # else:
    #    pass

    source_landmarks = np.array(
        [
            [30.2946, 51.6963],
            [65.5318, 51.5014],
            [48.0252, 71.7366],
            [33.5493, 92.3655],
            [62.7299, 92.2041],
        ],
        dtype=np.float32,
    )
    if crop_shape == (112, 112):
        source_landmarks[:, 0] += 8.0

    facial_landmarks = np.asfarray(facial_landmarks)

    transformation = transform.SimilarityTransform()
    transformation.estimate(facial_landmarks, source_landmarks)
    transformation_matrix = transformation.params[0:2, :]

    try:
        aligned_image = cv2.warpAffine(image_container.image,
                                       transformation_matrix,
                                       crop_shape,
                                       borderValue=0.0)
        return Result(
            "Success",
            ImageContainer(image=aligned_image,
                           image_path=image_container.image_path),
        )
    except Exception as exception:
        return Result(
            "Failure",
            f"An error occurred, probably transformation_matrix is None -\
            Error: {str(exception)}",
        )
def _save_image(image_container, destination_path):
    """"""
    # print('_save_image - PID: {}'.format(os.getpid()))

    folder, file_name = _split_file_path(image_container.image_path)

    destination_path = os.path.join(destination_path, folder)
    if not os.path.exists(destination_path):
        os.makedirs(destination_path)

    destination_path = os.path.join(destination_path, file_name + ".jpg")

    if cv2.imwrite(destination_path,
                   cv2.cvtColor(image_container.image, cv2.COLOR_RGB2BGR)):
        return Result("Success", f" Created file - Path: {destination_path}")
    return Result("Failure", f" File {destination_path} not saved")
Exemple #5
0
def _read_image(file_path):
    """
    """
    #print('_read_image - PID: {}'.format(os.getpid()))
    #class_id, sample = _split_file_path(file_path)
    #image = cv2.imread(file_path)
    #if not image:
    #    print('ué')
    #    logger.error(
    #        " Image couldn't be loaded - path: {}".format(file_path)
    #    )
    #    return None
    #print('foi')
    #return cv2.cvtColor(image, cv2.COLOR_BGR2RGB), '{}/{}'.format(class_id, sample)

    try:
        image = cv2.cvtColor(cv2.imread(file_path), cv2.COLOR_BGR2RGB)
        return Result('Success',
                      ImageContainer(image=image, image_path=file_path))
    except OSError as exception:
        return Result(
            'Failure',
            f" Image couldn't be loaded - path: {file_path}, Exception: \
                {str(exception)}")