def original_image_processing(filename):
    input_img = plt.imread(filename)
    trained_file = data.lbp_frontal_face_cascade_filename()

    # Initialize the detector cascade.
    detector = Cascade(trained_file)

    # Detect faces with scale factor to 1.2 and step ratio to 1
    detected = detector.detect_multi_scale(img=input_img,
                                           scale_factor=1.2,
                                           step_ratio=1,
                                           min_size=(50, 50),
                                           max_size=(200, 200))
    original_img = np.copy(input_img)
    original_img = input_img / 255
    i = 0
    for d in detected:
        i += 1
        # Obtain the face cropped from detected coordinates
        face = get_face_coordinates(d, input_img)
        print("Face -", i)
        plt.imshow(face)
        plt.show()
        blurred_face = gaussian(face, multichannel=True, sigma=8)
        print("Blurred Face -", i)
        plt.imshow(blurred_face)
        plt.show()
        resulting_image = merge_with_original(d, original_img, blurred_face)

    return resulting_image
def re():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    cwd = os.getcwd()
    print(cwd)
    os.chdir(dir_path)
    image1 = ""
    image = io.imread("somefilename.jpg")
    # Load the trained file from data
    trained_file = data.lbp_frontal_face_cascade_filename()

    # Initialize the detector cascade
    detector = Cascade(trained_file)
    detected = detector.detect_multi_scale(img=image,
                                           scale_factor=1.2,
                                           step_ratio=1,
                                           min_size=(50, 50),
                                           max_size=(100, 100))
    resulting_image = image
    for detected_face in detected:
        face = get_face(image, detected_face)
        blurred_face = gaussian(face, multichannel=True, sigma=10)
        #show_image(face)
        resulting_image = merge_blurry_face(image, detected_face, blurred_face)
    show_image(resulting_image, "Blurred faces")
    os.remove("somefilename.jpg")
    return 'Its Done!'
Beispiel #3
0
def get_face(img1, **kwargs):
    """
    Given an image, and (optionally) a feature set, return a roi that is cropped into containing a face
    :param img1:
    :param kwargs:
    :return: a cropped image of a face
    """
    # create a detector from Cascade
    if 'detector' in kwargs:
        detector = kwargs['detector']
    else:
        if 'features_xml_url' in kwargs:
            detector = Cascade(kwargs['features_xml_url'])
        else:
            detector = Cascade(
                os.path.join(WORK_ROOT, 'RES', 'FD',
                             'lbpcascade_frontalface.xml'))

    # detecting face in an image
    detected = detector.detect_multi_scale(img=img1,
                                           scale_factor=1.2,
                                           step_ratio=1,
                                           min_size=(60, 60),
                                           max_size=(123, 123))
    if len(detected) == 0:
        return None
    # print(f'img is {type(img)}, size is {img.shape}, {type(img.reshape((200, 180)))}, {len(detected)}')
    c = detected[0]['c']
    r = detected[0]['r']
    return img1.reshape((200, 180))[c:c + detected[0]['height'],
                                    r:r + detected[0]['width']]
Beispiel #4
0
class SkimageCascadeModel(BaseModel):

    def __init__(self):
        super(SkimageCascadeModel, self).__init__()

    def load_weight(self, weight_path: Path) -> Any:
        if weight_path.exists():
            # TODO: Implement loading weight file from local path
            pass
        else:
            logger.warning("No existing path was provided, using default weights")
            weight_path = skimage_data.lbp_frontal_face_cascade_filename()

        return weight_path

    def initialize_model(self, weights: Any=None) -> None:
        if weights is None:  # passing a non existent directory
            weights = self.load_weight(weight_path=Path("fdagkjhkjhlkfytfkjhfg"))
        else:
            weights = self.load_weight(weight_path=Path(weights))

        self.model = Cascade(weights)

    def predict(self, x) -> Iterable[Dict[str, int]]:
        w, h = x.shape[:-1]
        min_w, min_h = w * 0.01, h * 0.01
        max_w, max_h = w * 0.9, h * 0.9

        # detected contain {'c':int, 'r':int, 'width':int, 'height':int}
        detected = self.model.detect_multi_scale(img=x,
                                                 scale_factor=1.2,
                                                 step_ratio=1,
                                                 min_size=(min_w, min_h),
                                                 max_size=(max_w, max_h))
        return detected
Beispiel #5
0
def test_detector_astronaut():

    # Load the trained file from the module root.
    trained_file = data.lbp_frontal_face_cascade_filename()

    # Initialize the detector cascade.
    detector = Cascade(trained_file)

    img = data.astronaut()

    detected = detector.detect_multi_scale(img=img,
                                           scale_factor=1.2,
                                           step_ratio=1,
                                           min_size=(60, 60),
                                           max_size=(123, 123))

    assert len(detected) == 1, 'One face should be detected.'
def test_detector_astronaut():

    # Load the trained file from the module root.
    trained_file = data.lbp_frontal_face_cascade_filename()

    # Initialize the detector cascade.
    detector = Cascade(trained_file)

    img = data.astronaut()

    detected = detector.detect_multi_scale(img=img,
                                           scale_factor=1.2,
                                           step_ratio=1,
                                           min_size=(60, 60),
                                           max_size=(123, 123))

    assert len(detected) == 1, 'One face should be detected.'
Beispiel #7
0
def face_detections(image,
                    scale_factor=1.1,
                    step_ratio=1.3,
                    min_size=(10, 10),
                    max_size=(400, 400)):
    # Load the trained file from data
    trained_file = data.lbp_frontal_face_cascade_filename()

    # Initialize the detector cascade
    detector = Cascade(trained_file)

    # Detect faces with min and max size of searching window
    detected_faces = detector.detect_multi_scale(
        img=image,
        scale_factor=scale_factor,
        step_ratio=step_ratio,
        min_size=min_size,
        max_size=max_size,
    )
    return detected_faces
Beispiel #8
0
    def fd():
        from skimage.feature import Cascade
        from skimage import data, color
        import matplotib.pyplot as plt
        from matplotlib.patches import Rectangle

        path = ''
        img = plt.imread(path)
        plt.axis('off')
        plt.imshow(img)

        train_set = data.lbp_frontal_face_cascade_filename()
        detector = Cascade(train_set)
        detected = detector.detect_multi_scale(img=img,
                                               scale_factor=1.2,
                                               step_ratio=1,
                                               min_size=(10, 10),
                                               max_size=(200, 200))
        print('Detected')

        def show_detected_face(result, detected, title="Detected Faces"):
            plt.imshow(result)
            img_desc = plt.gca()
            plt.set_cmap('gray')
            plt.title(title)
            plt.axis('off')

            for rec in detected:
                img_desc.add_patch(
                    Rectangle((rec['c'], rec['r']),
                              rec['width'],
                              rec['height'],
                              fill=False,
                              color='g',
                              line_width=3))
            plt.show()

        show_detected_face(img, detected)
from skimage.feature import Cascade

import matplotlib.pyplot as plt
from matplotlib import patches

# Load the trained file from the module root.
trained_file = data.lbp_frontal_face_cascade_filename()

# Initialize the detector cascade.
detector = Cascade(trained_file)

img = data.astronaut()

detected = detector.detect_multi_scale(img=img,
                                       scale_factor=1.2,
                                       step_ratio=1,
                                       min_size=(60, 60),
                                       max_size=(123, 123))

plt.imshow(img)
img_desc = plt.gca()
plt.set_cmap('gray')

for patch in detected:

    img_desc.add_patch(
        patches.Rectangle((patch['c'], patch['r']),
                          patch['width'],
                          patch['height'],
                          fill=False,
                          color='r',
Beispiel #10
0
from skimage import data
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

#Getting the image
path = ''
img = plt.imread(path)
plt.axis('off')
plt.imshow(img)

#reading the dataset for facial detection
train_set = data.lbp_frontal_face_cascade_filename()
detector = Cascade(train_set)
detected = detector.detect_multi_scale(img=img,
                                       scale_factor=1.2,
                                       step_ratio=1,
                                       min_size=(10, 10),
                                       max_size=(200, 200))


#function to draw a rectangle around the detected faces
def show_detected_face(result, detected, title='Detected Faces'):
    plt.imshow(result)
    desc = plt.gca()
    plt.set_cmap('gray')
    plt.title(title)
    plt.axis('off')
    for rec in detected:
        desc.add_patch(
            Rectangle((rec['c'], rec['r']),
                      rec['width'],
Beispiel #11
0
# Initialize the detector cascade.
detector = Cascade(trained_file)

from PIL import Image
from numpy import asarray

# Open the image form working directory
file_image = Image.open("images/pp.jpg")

# convert image to numpy array
image = asarray(file_image)

detected = detector.detect_multi_scale(img=image,
                                       scale_factor=1.2,
                                       step_ratio=1,
                                       min_size=(60, 60),
                                       max_size=(500, 500))

plt.imshow(image)
iamge_shape = plt.gca()
plt.set_cmap("gray")

for patch in detected:

    iamge_shape.add_patch(
        patches.Rectangle(
            (patch["c"], patch["r"]),
            patch["width"],
            patch["height"],
            fill=False,
from skimage.feature import Cascade

import matplotlib.pyplot as plt
from matplotlib import patches

# Load the trained file from the module root.
trained_file = data.lbp_frontal_face_cascade_filename()

# Initialize the detector cascade.
detector = Cascade(trained_file)

img = data.astronaut()

detected = detector.detect_multi_scale(img=img,
                                       scale_factor=1.2,
                                       step_ratio=1,
                                       min_size=(60, 60),
                                       max_size=(123, 123))

plt.imshow(img)
img_desc = plt.gca()
plt.set_cmap('gray')

for patch in detected:

    img_desc.add_patch(
        patches.Rectangle(
            (patch['c'], patch['r']),
            patch['width'],
            patch['height'],
            fill=False,
Beispiel #13
0
        title='Image 1 opencv, Image 2 matplotlib')

    my_detected = None
    if control[1]:
        """
        This is a follow up section to demonstrates taking the image from previous code block, and cropping the face 
        image
        """
        # create a detector from Cascade
        my_detector = Cascade(
            os.path.join(WORK_ROOT, 'RES', 'FD', 'lbpcascade_frontalface.xml'))

        # detecting face in an image
        my_detected = my_detector.detect_multi_scale(img=test_img_cv,
                                                     scale_factor=1.2,
                                                     step_ratio=1,
                                                     min_size=(60, 60),
                                                     max_size=(123, 123))

    img_desc = plt.gca()
    plt.set_cmap('gray')
    roi_color = []
    for face in my_detected:
        roi_color.append(test_img_cv[face['c']:face['c'] + face['height'],
                                     face['r']:face['r'] + face['width']])

    plt.imshow(roi_color[0])
    plt.axis('off')
    plt.show()

if control[2]:
Beispiel #14
0
		img_desc.add_patch(patches.Rectangle((patch['c'], patch['r']), patch['width'], patch['height'], fill=False, color='r', linewidth=2))
		
	plt.show()
'''	
		
#load the trained file from the module root
trained_file = data.lbp_frontal_face_cascade_filename()

#initialize the detector cascade
detector = Cascade(trained_file)

while (video_capture.isOpened()):

	ret, image = video_capture.read()
	image = cv2.resize(image,(640,480))

	#if not ret:
	#	break

	#detect the faces
	detected = detector.detect_multi_scale(img=image, scale_factor=1.3, step_ratio=1.2, min_size=(30,30), max_size=(600,450))
	#to display detected faces
	showDetectedFaces(image,detected)

	#Break the loop when user hits 'esc' key
	if cv2.waitKey(1) & 0xFF ==27:
		break

video_capture.release()
cv2.destroyAllWindows()