Live Webcam Effects App

pip install opencv-python dlib numpy imutils


live_webcam_filters.py


import cv2
import dlib
import numpy as np

# Load face detector and landmark predictor
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# Load overlay images (with transparency)
glasses = cv2.imread("filters/glasses.png", cv2.IMREAD_UNCHANGED)
mustache = cv2.imread("filters/mustache.png", cv2.IMREAD_UNCHANGED)
dog_ears = cv2.imread("filters/dog_ears.png", cv2.IMREAD_UNCHANGED)

def overlay_transparent(background, overlay, x, y, scale=1):
    """Overlay PNG with alpha channel"""
    overlay = cv2.resize(overlay, (0, 0), fx=scale, fy=scale)
    h, w, _ = overlay.shape

    if x + w > background.shape[1] or y + h > background.shape[0]:
        return background

    alpha_overlay = overlay[:, :, 3] / 255.0
    for c in range(0, 3):
        background[y:y+h, x:x+w, c] = background[y:y+h, x:x+w, c] * (1 - alpha_overlay) + overlay[:, :, c] * alpha_overlay
    return background

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Flip frame for mirror effect
    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector(gray)

    for face in faces:
        landmarks = predictor(gray, face)

        # Coordinates for glasses
        left_eye = (landmarks.part(36).x, landmarks.part(36).y)
        right_eye = (landmarks.part(45).x, landmarks.part(45).y)
        eye_center = ((left_eye[0] + right_eye[0]) // 2, (left_eye[1] + right_eye[1]) // 2)
        eye_width = int(1.5 * abs(right_eye[0] - left_eye[0]))
        glasses_resized = cv2.resize(glasses, (eye_width, int(glasses.shape[0] * eye_width / glasses.shape[1])))
        frame = overlay_transparent(frame, glasses_resized, eye_center[0] - eye_width // 2, eye_center[1] - 25)

        # Coordinates for mustache
        nose = (landmarks.part(33).x, landmarks.part(33).y)
        mustache_resized = cv2.resize(mustache, (eye_width, int(mustache.shape[0] * eye_width / mustache.shape[1])))
        frame = overlay_transparent(frame, mustache_resized, nose[0] - eye_width // 2, nose[1] + 10)

        # Dog ears
        top_head = (landmarks.part(27).x, landmarks.part(27).y - 100)
        ears_resized = cv2.resize(dog_ears, (eye_width * 2, int(dog_ears.shape[0] * (eye_width * 2) / dog_ears.shape[1])))
        frame = overlay_transparent(frame, ears_resized, top_head[0] - eye_width, top_head[1])

    cv2.imshow("Live Webcam Filters 🧑‍🎤", frame)
    if cv2.waitKey(1) == 27:
        break  # ESC to quit

cap.release()
cv2.destroyAllWindows()

No comments: