Add image to a live camera feed using OpenCV-Python
In this article, we are going to learn how to insert an image in your live camera feed using OpenCV in Python.
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.
Step 2: Get the webcams live feed
- 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.
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.
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.
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.
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.
By doing these simple steps we can insert any image or any logo by this method.