The Wayback Machine - https://web.archive.org/web/20241001193439/https://www.geeksforgeeks.org/replace-green-screen-using-opencv-python/
Open In App

Replace Green Screen using OpenCV- Python

Last Updated : 04 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: OpenCV Python Tutorial
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. This library is cross-platform that is it is available on multiple programming languages such as Python, C++, etc.
Green Screen removal is used in the VFX industry for changing the scenes. Here, we will use OpenCV – Python to do the same. 
 

Approach:

  1. Import all necessary libraries
  2. Load the images or videos
  3. Resize the images and the videos to the same size
  4. Load the upper and lower BGR values of the green color
  5. Apply the mask and then use bitwise_and
  6. Subtract bitwise_and from the original green screen image
  7. Check for matrix value 0 after subtraction and replace it by the second image
  8. You get the desired results.


Below is the implementation. 

Python3
import cv2 
import numpy as np 

video = cv2.VideoCapture("green.mp4")
image = cv2.imread("bg.jpeg")

while True:

    ret, frame = video.read()

    frame = cv2.resize(frame, (640, 480))
    image = cv2.resize(image, (640, 480))


    u_green = np.array([104, 153, 70])
    l_green = np.array([30, 30, 0])

    mask = cv2.inRange(frame, l_green, u_green)
    res = cv2.bitwise_and(frame, frame, mask = mask)

    f = frame - res
    f = np.where(f == 0, image, f)

    cv2.imshow("video", frame)
    cv2.imshow("mask", f)

    if cv2.waitKey(25) == 27:
        break 

video.release()
cv2.destroyAllWindows()

Output: 
 

Screenshot-from-2020-04-21-22-42-28-copy



 


Previous Article
Next Article

Similar Reads

OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Step-by-Step Guide to Using RANSAC in OpenCV using Python
RANSAC (Random Sample Consensus) is an iterative method to estimate the parameters of a mathematical model from a set of observed data that contains outliers. In computer vision, it's often used for tasks like estimating the fundamental matrix, homography, or any fitting problem with noisy data. In Python, OpenCV provides built-in support for RANSA
4 min read
Getting screen's height and width using Tkinter | Python
Tkinter provides some methods with the help of which we can get the current screen height and width.Following methods can be used to decide height and width : winfo_screenheight() // Returns screen height in pixels winfo_screenmmheight() // Returns screen height in mm winfo_screenwidth() // Returns screen width in pixels winfo_screenmmwidth() // Re
1 min read
How to Control Laptop Screen Brightness using Python?
To control the brightness of the screen we are using the screen-brightness-control library. The screen-brightness-control library has only one class and few functions. The most useful functions are mentioned below: get_brightness()set_brightness()fade_brightness()list_monitors() Installation: We can install the package by running the following pip
4 min read
Create a Screen recorder using Python
Python is a widely used general-purpose language. It allows for performing a variety of tasks. One of them can be recording a video. It provides a module named pyautogui which can be used for the same. This module along with NumPy and OpenCV provides a way to manipulate and save the images (screenshot in this case) Modules neededNumpy: To install N
5 min read
Build an Application for Screen Rotation Using Python
In this article, we are going to write a python script for screen rotation and implement it with GUI. The display can be modified to four orientations using some methods from the rotatescreen module, it is a small Python package for rotating the screen in a system. Installation:pip install rotate-screenApproach: Step 1) Import the required module i
2 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Python | Play a video in reverse mode using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Converting Color video to grayscale using OpenCV in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
1 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
Image Pyramid using OpenCV | Python
Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
1 min read
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read
Python | Denoising of colored images using opencv
Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images. Syntax: cv2.fastNlMeansDenoisingColor
1 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Negative transformation of an image using Python and OpenCV
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest an
4 min read
Python | Image blurring using OpenCV
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in smoothing the image. Low intensity edges are remov
2 min read
Arithmetic operations using OpenCV | Python
Prerequisite: Arithmetic Operations on Images using OpenCV | Basics We can perform different Arithmetic operations on images e.g. Addition, Subtraction, etc. This is possible because images are actually stored as arrays (3 Dimensional for RGB images and 1 dimensional for the grayscale images). Importance of Arithmetic Operations on images: Image Bl
2 min read
Find and Draw Contours using OpenCV | Python
Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection. OpenCV has findContour() function that helps in extracting the contours from the image. It works best on binary images, so
2 min read
Article Tags :
Practice Tags :