Adding Sunglasses to Faces in Photos Using Python

mdshamsfiroz
4 min readAug 13, 2023

--

Introduction: Ever wondered how those cool sunglasses filters on photos work? They’re a fun way to add style to your images. In this blog post, we’ll explain how you can use a simple Python code with the OpenCV library to automatically detect a face in a photo and place a pair of sunglasses on it. Don’t worry if you’re not a coding expert — we’ll walk you through each step in easy-to-understand language!

Prerequisites: Before we begin, make sure you have:

  • Basic knowledge of Python programming.
  • Python installed on your computer.
  • A photo of a face where you want to add sunglasses.
  • An image of sunglasses with a clear background (PNG format).

Step 1: Importing Libraries We start by bringing in the tools we need:

  • cv2 (OpenCV) for working with images.
  • numpy for handling arrays.
import cv2
import numpy as npp

Step 2: Detecting the Face We create a function called detect_face(image_path) that takes an image's path as input. Here's what it does:

  • It uses a pre-trained “face detection” tool from OpenCV.
  • Loads your picture.
  • Converts it to a simpler version (grayscale) that’s easier to work with.
  • Uses the face detector to spot faces in the grayscale image.
import cv2
import numpy as np

def detect_face(image_path):
# Load the face detection classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Read the input image
image = cv2.imread(image_path)

# Convert the image to grayscale (face detection requires grayscale)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)

# Assuming there's only one face in the image, return its coordinates
if len(faces) == 1:
return faces[0]
else:
return None

def main():
# Path to the input photo
image_path = 'path_to_your_photo.jpg'

# Load the photo
image = cv2.imread(image_path)

# Detect the face in the photo
face_coords = detect_face(image_path)
if face_coords is None:
print("No face found in the photo.")
return

# Load the sunglass image with an alpha channel (transparency)
sunglass_img = cv2.imread('path_to_sunglass_image.png', cv2.IMREAD_UNCHANGED)

# Check if the sunglass image was successfully loaded
if sunglass_img is None:
print("Error: Could not read the sunglass image.")
return

# Resize the sunglass image to fit the detected face
face_width, face_height = face_coords[2], face_coords[3]
sunglass_img_resized = cv2.resize(sunglass_img, (face_width, face_height))

# Get the region of interest (ROI) on the face where the sunglass will be placed
roi = image[face_coords[1]:face_coords[1]+face_height, face_coords[0]:face_coords[0]+face_width]

# Extract the alpha channel from the sunglass image and create a 3-channel alpha array
alpha_sunglass = sunglass_img_resized[:, :, 3] / 255.0
alpha_sunglass = np.stack([alpha_sunglass] * 3, axis=-1)

# Remove the alpha channel from the sunglass image and convert it to BGR
sunglass_bgr = sunglass_img_resized[:, :, :3]

# Perform alpha blending to overlay the sunglass on the face
overlay = (1 - alpha_sunglass) * roi + alpha_sunglass * sunglass_bgr

# Replace the ROI in the original image with the sunglass overlay
image[face_coords[1]:face_coords[1]+face_height, face_coords[0]:face_coords[0]+face_width] = overlay

# Display the result
cv2.imshow('Sunglass Overlay', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

if __name__ == "__main__":
main()

Step 3: Loading and Preparing Images In the main() function:

  • Tell the code where your photo is.
  • Load your photo.
  • Ask the face detector to find the face in your photo.
  • If it doesn’t find any face, you’ll see a message saying so.

Step 4: Getting Sunglasses Ready

  • Load the sunglasses picture that you want to add.
  • Adjust its size to match the detected face’s size.
  • Make the sunglasses transparent where they should be.
  • Get the sunglasses’ colors ready.

Step 5: Putting on the Sunglasses

  • Select the part of the face where the sunglasses should go.
  • Blend the sunglasses with the face, making sure they look natural.
  • Replace the chosen face part with the sunglass-covered one.

Step 6: Seeing the Result

  • You get to see the photo with the sunglasses!
  • You can press a key to close the window when you’re done looking.

Conclusion: Now you’ve learned how to use Python and OpenCV to put sunglasses on a face in a photo. This process shows how you can use computer magic to create fun effects. You can play around with different images and sunglasses to make your own cool filters. This code is just the beginning — you can take it even further to create your own unique photo transformations.

So go ahead and have some fun adding sunglasses to your photos with the code! Happy experimenting!

Thank you @Vimal Daga Sir for teaching me fundamentals to explore.

--

--

mdshamsfiroz

Trying to learn tool by putting heart inside to make something