Open In App

Removing Black Background and Make Transparent using Python OpenCV

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to remove the black background and make it transparent in Python OpenCV.

cv2.cvtColor method

cv2.cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV.

Syntax: cv2.cvtColor(src, code[, dst[, dstCn]])

Parameters:

  • src: Image
  • code: It is the color space conversion code.
  • dst: (optional), It is the output image of the same size and depth as src image.
  • dstCn: (optional),It is the number of channels in the destination image

Return Value: It returns an image.

Image used for demonstration:

 

Stepwise Implementation:

Step 1: First of all, import the library OpenCV.

import cv2

Step 2: Now, import the image from your computer.

file_name = "#Image-Location"

Step 3: Then, read the image in OpenCV.

src = cv2.imread(file_name, 1)

Step 4: Then, convert the image background to gray image background.

tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

Step 5: Moreover, apply the thresholding technique.

_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)

Step 6: Further, use cv2.split() to split channels of colored image.

b, g, r = cv2.split(src)

Step 7: Later on, make a list of Red, Green, and Blue Channels and alpha.

rgba = [b,g,r, alpha]

Step 8: Next, use cv2.merge() to merge rgba into a coloured/multi-channeled image.

dst = cv2.merge(rgba,4)

Step 9: Finally, write and save to a new image location.

cv2.imwrite("#New-Image-Location", dst)

Below is the complete implementation:

Python3




# Import the library OpenCV
import cv2
  
# Import the image
file_name = "gfg_black.png"
  
# Read the image
src = cv2.imread(file_name, 1)
  
# Convert image to image gray
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
  
# Applying thresholding technique
_, alpha = cv2.threshold(tmp, 0, 255, cv2.THRESH_BINARY)
  
# Using cv2.split() to split channels 
# of coloured image
b, g, r = cv2.split(src)
  
# Making list of Red, Green, Blue
# Channels and alpha
rgba = [b, g, r, alpha]
  
# Using cv2.merge() to merge rgba
# into a coloured/multi-channeled image
dst = cv2.merge(rgba, 4)
  
# Writing and saving to a new image
cv2.imwrite("gfg_white.png", dst)


Output:

Removing black background and make transparent in python opencv

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads