Invisible Cloak using OpenCV in Python

This mission demonstrates how to create an “invisible cloak” impact the usage of OpenCV in Python. The concept is based on covering and historical past subtraction strategies to make a specific coloration disappear and reveal the heritage in its place. This fun and creative application of OpenCV showcases actual-time photo processing and computer vision concepts.

How to Create Invisible Cloak using OpenCV in Python

Step 1:  Import the OpenCV library for image processing and NumPy for dealing with arrays, that is vital for developing masks and acting pixel manipulations.

import cv2
import numpy as np

Step 2: Use the webcam to capture a static history frame. Flipping the image horizontally guarantees the ideal orientation of the background.

cap = cv2.VideoCapture(0)
for i in range(30):
    ret, background = cap.read()
background = cv2.flip(background, 1)

Step 3: Continuously seize frames from the webcam for actual-time video processing. Each frame is flipped horizontally to preserve alignment with the heritage:

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv2.flip(frame, 1)

Step 4: Convert the body to the HSV color area and outline the color variety for the cloak (e.G., purple). Create masks to isolate the desired color inside this variety.

hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([0, 120, 70])
upper_red = np.array([10, 255, 255])
mask1 = cv2.inRange(hsv, lower_red, upper_red)

lower_red = np.array([170, 120, 70])
upper_red = np.array([180, 255, 255])
mask2 = cv2.inRange(hsv, lower_red, upper_red)
mask = mask1 + mask2

Step 5: Apply morphological alterations to put off noise from the mask, making sure better segmentation of the cloak area.

mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8))

Step 6: Use the mask to extract the background where the cloak appears. Combine it with the relaxation of the frame (except the cloak place) to create the final output.

cloak = cv2.bitwise_and(background, background, mask=mask)
inverse_mask = cv2.bitwise_not(mask)
rest = cv2.bitwise_and(frame, frame, mask=inverse_mask)
final_output = cv2.addWeighted(cloak, 1, rest, 1, 0)

Step 7: Display the final output in a window. The user can exit the program by pressing the ‘q’ key. Release the webcam and close all OpenCV windows.

cv2.imshow('Invisible Cloak', final_output)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()

OUTPUT:

When the program runs, the region of the cloak becomes invisible, revealing the captured background in its place. This effect works in real-time using your webcam.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top