How to create a transparent mask in opencv-python

2024/9/16 23:36:19

I have sign (signs with arbitrary shape) images with white background and I want to get an image of the sign with transparent background.

I have managed to create a mask and apply it to the image and thought making the mask transparent would be doable. I searched a lot here and elsewhere, but nothing really helped me.

import cv2
import numpy as npfile_name = "/path/to/input/img/Unbenannt.jpg" # can be also .pngimg = cv2.imread(file_name)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)_, roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)mask = np.zeros(img.shape, img.dtype)cv2.fillPoly(mask, roi, (255,)*img.shape[2], )masked_image = cv2.bitwise_and(img, mask)cv2.imwrite("/path/to/output/mask_test.png", masked_image)

Input:

enter image description here

Current Output:

enter image description here

As already mentioned I want to make the background transparent.

Help is highly appreciated.

Answer

I found that I have to convert the image to BGRA to get a transparent background. I have also added a method to cut the image to its bounding rectangle. As promised, the working code:

import cv2
import numpy as npfile_name = "/path/to/img.png"def cut(img):# crop imagegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)_, cnts, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnt = sorted(cnts, key=cv2.contourArea)[-1]x,y,w,h = cv2.boundingRect(cnt)new_img = img[y:y+h, x:x+w]return new_img        def transBg(img):   gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)_, roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)mask = np.zeros(img.shape, img.dtype)cv2.fillPoly(mask, roi, (255,)*img.shape[2], )masked_image = cv2.bitwise_and(img, mask)return masked_imagedef fourChannels(img):height, width, channels = img.shapeif channels < 4:new_img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)return new_imgreturn imgs_img = cv2.imread(file_name, -1)# set to 4 channels
s_img = fourChannels(s_img)# remove white background
s_img = cut(s_img)# set background transparent
s_img = transBg(s_img)cv2.imwrite("/path/to/store/img.png", s_img)

input is:

enter image description here

output is an image with transparent background:

enter image description here

https://en.xdnf.cn/q/73047.html

Related Q&A

Variables with dynamic shape TensorFlow

I need to create a matrix in TensorFlow to store some values. The trick is the matrix has to support dynamic shape.I am trying to do the same I would do in numpy: myVar = tf.Variable(tf.zeros((x,y), va…

python protobuf cant deserialize message

Getting started with protobuf in python I face a strange issue:a simple message proto definition is:syntax = "proto3"; package test;message Message {string message = 1;string sender = 2; }gen…

Seaborn: title and subtitle placement

H all,Id like to create a scatterplot with a title, subtitle, colours corresponding to a specific variable and size corresponding to another variable. I want to display the colour legend but not the si…

Calculate a rolling regression in Pandas and store the slope

I have some time series data and I want to calculate a groupwise rolling regression of the last n days in Pandas and store the slope of that regression in a new column.I searched the older questions an…

Python read microphone

I am trying to make python grab data from my microphone, as I want to make a random generator which will use noise from it. So basically I dont want to record the sounds, but rather read it in as a da…

How to tell pytest-xdist to run tests from one folder sequencially and the rest in parallel?

Imagine that I have test/unit/... which are safe to run in parallel and test/functional/... which cannot be run in parallel yet.Is there an easy way to convince pytest to run the functional ones sequen…

PyPDF4 - Exported PDF file size too big

I have a PDF file of around 7000 pages and 479 MB. I have create a python script using PyPDF4 to extract only specific pages if the pages contain specific words. The script works but the new PDF file,…

Jupyter install fails on Mac

Im trying to install Jupyter on my Mac (OS X El Capitan) and Im getting an error in response to:sudo pip install -U jupyterAt first the download/install starts fine, but then I run into this:Installing…

Python Error Codes are upshifted

Consider a python script error.pyimport sys sys.exit(3)Invokingpython error.py; echo $?yields the expected "3". However, consider runner.pyimport os result = os.system("python error.py&…

Running dozens of Scrapy spiders in a controlled manner

Im trying to build a system to run a few dozen Scrapy spiders, save the results to S3, and let me know when it finishes. There are several similar questions on StackOverflow (e.g. this one and this oth…