Why might you want to blur faces in an image? One motivation would be if you are publicly releasing a dataset of imagery: it is common practice to blur faces in order to preserve the privacy of individuals whose faces were captured without their consent.

If you find yourself needing to do this, you could train a face detector yourself or use a pre-trained Haar Cascade model. However, the common standard for preserving privacy in public datsets is “best effort” obfuscation, so you may want a better model. You’re in luck, because Google Cloud Vision provides a very good face detection API.

A full script for blurring imagery via the Cloud Vision API is here. This is the part that conducts the blurring (I also tried Gaussian blur, but linear blur was better at hiding the face in this case):

def blur_image(image_content, faces, output_path):
    img = Image.open(StringIO(image_content))
    img = np.array(img)
    # RGB/BGR channel flip for PIL-OpenCV compatibility
    img = img[:, :, ::-1]
    for face in faces:
      box = [(bound.x_coordinate, bound.y_coordinate)
               for bound in face.bounds.vertices]
      ...
      roi = img[y:y+h, x:x+w]
      roi_blurred = cv2.blur(roi, (15,15))
      img[y:y+h, x:x+w] = roi_blurred

    return img

Here is an example of how the blurring looks:

before

Original and blurred images