简体   繁体   中英

OpenCV: how to keep only transparent pixels and set them to White?

I have an inputMat (RGBA format). I want to keep only the transparent pixels and set them to white color. All the other pixels (that are consequently non transparent) should be changed to transparent.

Beginning of my Java code:

Mat inputMat = new Mat();
Utils.bitmapToMat(bitmap, inputMat);

How can I do what I want to do? (answers in all languages - not only Java - accepted!)

Thanks !

That is the idea.

Mat inputMat = new Mat();
Utils.bitmapToMat(bitmap, inputMat);

Split image to channels:

List<Mat> channels = new ArrayList<>(4);
Core.split(inputMat, channels);

Get alpha channel:

Mat alpha = channels.get(3);

Invert alpha channel:

Core.bitwise_not(alpha,alpha);

Make new list of channels:

List<Mat> channelsOut = new ArrayList<>();
channelsOut.add(alpha);
channelsOut.add(alpha);
channelsOut.add(alpha);
channelsOut.add(alpha);

Merge them to image:

Mat outputMat = new Mat();
Core.merge(channelsOut,outputMat);

OpenCV's Mat class has a setTo method that takes a mask argument. OpenCV has the split procedure that can separate color planes (channels). Mats support comparison . OpenCV Mats support "normal" math expressions .

assert input.shape[2] == 4, "it's not a four-channel picture"

alpha = input[..., 3] # select alpha plane
assert ((alpha == 0) | (alpha == 255)).all(), "assuming alpha values to be binary"

mask = (alpha == 0) # boolean array representing the transparent pixels

# change input; if you want a new array, copy it or create an empty one of the same shape
input[mask] = (255, 255, 255, 255) # white, opaque
# ~mask inverts the mask
input[~mask] = (0, 0, 0, 0) # set transparent, clear color information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM