How to change background of green screen in python

0

 If you love watching movies then you might have heard about green screen. In modern days each and every movie uses the green screen . Using green screen the cost of movie decreases and it is very time saving. 

In this tutorial today we will see how we can take an image with the green background and will take another image and we will merge these two images.



import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("C:\\Img\\hcc.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


lr = np.array([5, 40, 5])
ur = np.array([78, 255, 150])


mask = cv2.inRange(img, lr, ur)


img[mask != 0] = [0, 0, 0]



bg_img = cv2.imread("C:\\Img\\bg.png")
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB)


bg_img = cv2.resize(bg_img, (img.shape[1], img.shape[0]) )

bg_img[mask == 0 ] = [0, 0, 0]

final_img = bg_img + img

plt.imshow(final_img)
plt.savefig("new.jpg")

So lets understand  the coding part . 

Prerequisite :

1. Python Language

2. Basic knowledge about opencv, numpy 

3. Any code editor in which opencv-python and matplotlib module is installed . ( I have used VS code for this )


* Import all the important modules 


import cv2
import numpy as np
import matplotlib.pyplot as plt



* Import green screen image


In this we will first import our green screen image which loos like this :



Here in this image you can clearly see that the background color is green. We will import this image to our code : 



img = cv2.imread("C:\\Img\\hcc.png")
img = cv2.cvtColor(marvel_image, cv2.COLOR_BGR2RGB)

Note : Always give the complete path of the image otherwise it will throw an error.

Now we will define the range to exclude the green color from the image that we have provided.

To do this we will use numpy array and exclude it.


lr = np.array([5, 40, 5])
ur = np.array([78, 255, 150])

Here lr and ur are the lower and upper range value of green color.

Now we will create a mask and set all the other areas to zero except mask


mask = cv2.inRange(img, lr, ur)

img[mask != 0] = [0, 0, 0]


* Background Image

Now we will do the same operations on our background image which something looks like this :



bg_img = cv2.imread("C:\\Img\\bg.png")
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB)


It is quite possible that the baground image may not be same size as our green screen image. So to make it same size we use cv2.resize to ensure that those image are of the same size and again that mask operation.


bg_img = cv2.resize(bg_img, (img.shape[1], img.shape[0]) )

bg_img[mask == 0 ] = [0, 0, 0]


*Merge 

Now comes the last and important part that is merging . We can do it simply and save it as new.jpg.

See how it looks 


final_img = bg_img + img

plt.imshow(final_img)
plt.savefig("new.jpg")



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !