Removing Black Background and Make Transparent using Python OpenCV
Last Updated :
03 Jan, 2023
In this article, we will discuss how to remove the black background and make it transparent in Python OpenCV.
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 cv2
file_name = "gfg_black.png"
src = cv2.imread(file_name, 1 )
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_, alpha = cv2.threshold(tmp, 0 , 255 , cv2.THRESH_BINARY)
b, g, r = cv2.split(src)
rgba = [b, g, r, alpha]
dst = cv2.merge(rgba, 4 )
cv2.imwrite( "gfg_white.png" , dst)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...