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
Exemplo n.º 2
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']]
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!'
Exemplo n.º 4
0
    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)
Exemplo n.º 5
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
Exemplo n.º 6
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.'
Exemplo n.º 7
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.'
Exemplo n.º 8
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
Exemplo n.º 9
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)
Exemplo n.º 10
0
you want to have a really precise detector, you will have to train it yourself
using `OpenCV train cascade utility
<https://docs.opencv.org/2.4/doc/user_guide/ug_traincascade.html>`_.
"""

from skimage import data
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:
Exemplo n.º 11
0
#header files required
from skimage.feature import Cascade
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(
Exemplo n.º 12
0
def showDetectedFaces(image,detected):
	plt.imshow(image)
	img_desc = plt.gca()
	plt.set_cmap('rainbow')
	plt.axis('off')

	for patch in detected:
		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)

#detect the faces
detected = detector.detect_multi_scale(img=image, scale_factor=1.2, step_ratio=1, min_size=(20,20), max_size=(100,100))
#to display detected faces
showDetectedFaces(image,detected)

'''
To extract the face rectangle from the image using
the coordinates of the detected
'''

def getFace(d):
	
	#X & Y are the starting points of the face rectangle
	x,y = d['r'], d['c']
Exemplo n.º 13
0
you want to have a really precise detector, you will have to train it yourself
using `OpenCV train cascade utility
<https://docs.opencv.org/doc/user_guide/ug_traincascade.html>`_.
"""

from skimage import data
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:
Exemplo n.º 14
0
    # show the two images
    sw_utils.functions.show_two_images(
        test_img_cv,
        test_img_gray,
        cmap2='gray',
        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']])
Exemplo n.º 15
0
	plt.imshow(image)
	img_desc = plt.gca()
	plt.set_cmap('rainbow')
	plt.axis('off')

	for patch in detected:
		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