Face Detection And Blur Face Using Face-Recognition and Pillow Python Package

 

About this Post

In this post I will be sharing a simple python script to detect faces in image using face-recognition package and blurring the face using Pillow package 

Prerequisite

  • Python 2 / Python 3

Python Packages Required


Sample Image Link



Python Code

from PIL import Image, ImageDraw
from PIL import ImageFilter
import face_recognition

image_path = "test.jpeg"
# Open an image
im = Image.open(image_path)

# Load the jpg file into a numpy array - face recognition
image = face_recognition.load_image_file(image_path)


def get_face_in_image(loaded_image):
    # face_locations method returns list of coordinates (top, right, bottom, left) of faces found
    faces = face_recognition.face_locations(loaded_image)
    return faces

#Function to blur image using mask
def blur(x1, y1, x2, y2):
    # Create rectangle mask
    mask = Image.new('L', im.size, 0)
    draw = ImageDraw.Draw(mask)
    draw.rectangle([(x1, y1), (x2, y2)], fill=255)

    # Blur image
    blurred = im.filter(ImageFilter.GaussianBlur(52))
    im.paste(blurred, mask=mask)


face_locations = get_face_in_image(image)

# Loop through faces coordinates
for face_location in face_locations:
    top, right, bottom, left = face_location
    blur(left, top, right, bottom)

# Save final blurred image
im.save("blur.jpg")

Input and Output Image

test.jpeg





blur.jpg



Comments

Popular posts from this blog

Highlight Text In PDF With Different Colors Using Python

Basic of Python - Variable and Memory Address