Add image to a live camera feed using OpenCV-Python - GeeksforGeeks

03 Feb, 2022
In this article, we are going to learn how to insert an image in your live camera feed using OpenCV in Python.
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
# importing librariesimport cv2import numpy as np
The next step is to get the live feed from our webcam or any other connected camera. As you know a video is a collection of images. So, what we are going to do is get our webcams to feed every millisecond as an image and put it in a while loop to make it as a loop of different images showing back to back to get our live webcam feed.
Obviously, this is not going to be a never-ending loop so we are setting a key to breaking out of the loop
What these two lines of code are going to do is, it will wait for the specified key and if the key is pressed it will break out of the loop.
Python3
# Setup cameracap = cv2.VideoCapture(0) # While loopwhile True:       # Capture frame-by-frame    ret, frame = cap.read()         # Show the captured image    cv2.imshow('WebCam', frame)         # wait for the key and come out of the loop    if cv2.waitKey(1) == ord('q'):        break # Discussed belowcap.release()cv2.destroyAllWindows()
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
# Read logo and resizelogo = cv2.imread('image.png')size = 100logo = cv2.resize(logo, (size, size))
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
# Create a mask of logoimg2gray = 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
# Region of Interest (ROI), where we want# to insert logoroi = frame[-size-10:-10, -size-10:-10] # Set an index of where the mask isroi[np.where(mask)] = 0roi += logo
 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 # When everything done, release the capturecap.release()cv2.destroyAllWindows()
By doing these simple steps we can insert any image or any logo by this method.  
Complete Code
Python3
# importing the librariesimport cv2import numpy as np # Setup cameracap = cv2.VideoCapture(0) # Read logo and resizelogo = cv2.imread('image.png')size = 100logo = cv2.resize(logo, (size, size)) # Create a mask of logoimg2gray = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)ret, mask = cv2.threshold(img2gray, 1, 255, cv2.THRESH_BINARY) while True:    # Capture frame-by-frame    ret, frame = cap.read()     # Region of Image (ROI), where we want to insert logo    roi = frame[-size-10:-10, -size-10:-10]     # Set an index of where the mask is    roi[np.where(mask)] = 0    roi += logo     cv2.imshow('WebCam', frame)    if cv2.waitKey(1) == ord('q'):        break # When everything done, release the capturecap.release()cv2.destroyAllWindows()
Output:
Media error: Format(s) not supported or source(s) not found
surinderdawra388
jamesalbert10ac
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()