Add image to a live camera feed using OpenCVPython (original) (raw)

Add image to a live camera feed using OpenCV-Python

Last Updated : 03 Jan, 2023

In this article, we are going to learn how to insert an image in your live camera feed using OpenCV in Python.

Stepwise Implementation

Step 1: Importing the libraries

CV reads and stores all the images as a NumPy array. We need the NumPy library to manipulate the image and as expected we need the cv2 module.

Python3

import cv2

import numpy as np

Step 2: Get the webcams live feed

Python3

cap = cv2.VideoCapture( 0 )

while True :

`` ret, frame = cap.read()

`` cv2.imshow( 'WebCam' , frame)

`` if cv2.waitKey( 1 ) = = ord ( 'q' ):

`` break

cap.release()

cv2.destroyAllWindows()

Step 3: Read the image

The next step is to read the image and store it in a variable to access it by cv2.imread and resize the image.

Python3

logo = cv2.imread( 'image.png' )

size = 100

logo = cv2.resize(logo, (size, size))

Step 4: Create a mask in the live feed

Next, we should set a space for the image where it is going to be placed in the webcam feed By masking out that area for a smooth placement of the image.

For that, we are going to use the cv2.cvtColor (To know more visit cv2.cvtColor ) to first convert the given image into a grayscale image, because it is easy to process the image in OpenCV if the image is in grayscale, and mask out the area by thresholding the pixels in that range by cv2.THRESH_BINARY ( To know more visit cv2.THRESH_BINARY ) to create a space for the image to appear.

Python3

img2gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(img2gray, 1 , 255 , cv2.THRESH_BINARY)

Now we are going to find the ROI (range of interest) where the image should be placed and mask out the area and insert the image into the live feed.

Python3

roi = frame[ - size - 10 : - 10 , - size - 10 : - 10 ]

roi[np.where(mask)] = 0

roi + = logo

Step 6: Show the Video

Now it is a good practice to release the webcam for other sources after using it we can do this by cv2.release() and use cv2.destroyAllWindows() after we broke out of the loop.

Python3

cv2.imshow( 'WebCam' , frame)

if cv2.waitKey( 1 ) = = ord ( 'q' ):

`` break

cap.release()

cv2.destroyAllWindows()

By doing these simple steps we can insert any image or any logo by this method.

Complete Code

Python3

import cv2

import numpy as np

cap = cv2.VideoCapture( 0 )

logo = cv2.imread( 'image.png' )

size = 100

logo = cv2.resize(logo, (size, size))

img2gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(img2gray, 1 , 255 , cv2.THRESH_BINARY)

while True :

`` ret, frame = cap.read()

`` roi = frame[ - size - 10 : - 10 , - size - 10 : - 10 ]

`` roi[np.where(mask)] = 0

`` roi + = logo

`` cv2.imshow( 'WebCam' , frame)

`` if cv2.waitKey( 1 ) = = ord ( 'q' ):

`` break

cap.release()

cv2.destroyAllWindows()

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20211005142957/Output-video.mp4