Remove Background of Image Using Python OpenCV

It is easy to remove the background of an image using python opencv. In this tutorial, we will introduce you how to do.

Remove Background of Image Using Python OpenCV

1.Import library

import cv2
import numpy as np

2.Read an image and convert the image into a grayscale image

img = cv2.imread("py.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

If you only want to convert a color image to a gray image, you can read:

Read and Write Color Images in Grayscale with Python OpenCV

3.Find the color threshold

_, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

4.Find the image contours by color threshold

img_contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]

5.Sort contours

img_contours = sorted(img_contours, key=cv2.contourArea)

for i in img_contours:

    if cv2.contourArea(i) > 100:


6.Generate the mask using np.zeros()

mask = np.zeros(img.shape[:2], np.uint8)

7.Draw contours with mask in step 6.

cv2.drawContours(mask, [i],-1, 255, -1)

8.Apply the bitwise_and operator in opencv

new_img = cv2.bitwise_and(img, img, mask=mask)

9.Display the original image

cv2.imshow("Original Image", img)

10.Display the resultant image

cv2.imshow("Image with background removed", new_img)

Remove Background of Image Using Python OpenCV example