REPLACE GREEN SCREEN USING OPENCV AND PYTHON 🤓
- In this post, we are going to discuss how to replace a video which is having green screen background with a background image using OpenCV and Python🐍.
- To understand this, you have to know how to detect colors using OpenCV and Python and you can check out by clicking here🐱🏍.
Input video and background image😄:
Code😄:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python program to replace the green screen in the video | |
# with the background image | |
import cv2 | |
import numpy | |
# reading the background image | |
bg_img = cv2.imread('Background image location') | |
# getting the height and width of the background image | |
height, width = bg_img.shape[0:2] | |
# reading the video which is having green screen background | |
video = cv2.VideoCapture('Green screen video location') | |
while True: | |
# reading the input video frame by frame | |
_, green_img = video.read() | |
# resizing the image in the video with the background image | |
green_img = cv2.resize(green_img, (width, height)) | |
# converting the BGR image to HSV image | |
green_img_hsv = cv2.cvtColor(green_img, cv2.COLOR_BGR2HSV) | |
# getting the mask image with lower and higher HSV of green color | |
lower_hsv = numpy.array([40, 150, 20]) | |
higher_hsv = numpy.array([150, 250, 255]) | |
mask = cv2.inRange(green_img_hsv, lower_hsv, higher_hsv) | |
# getting the masked image | |
bitwise = cv2.bitwise_and(green_img, green_img, mask=mask) | |
# getting the final output (replacing the green screen with the background) | |
diff = green_img - bitwise | |
result = numpy.where(diff == 0, bg_img, diff) | |
# showing the result | |
cv2.imshow('Result', result) | |
# press enter to end the loop | |
if cv2.waitKey(1) == 13: | |
break |
Output😄:
I hope it will help you😊.
Comments