Ask Your Question
0

convert png transparent pixels to white

asked 2016-11-03 03:48:07 -0600

mika S gravatar image

updated 2016-11-03 09:27:36 -0600

I have a png as a base64 that contains some transparent pixels whose rgb is (0,0,0). I want to convert the rgb of these pixels to white and set the alpha to 255. I read the image through:

    vector<uchar> vectordata(string.begin(), strong.end());
    mat = imdecode(vectordata, IMREAD_UNCHANGED);

Then I change the pixels, by going one by one in the mat array and converting rgb values of the transparent pixels and fixing their transparency back to 255. Is there a faster way to do that? Like composting with a white image ?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-11-03 04:35:26 -0600

berak gravatar image

there's a couple of ways to do so:

  1. just change the flag: imdecode(vectordata, IMREAD_COLOR);
  2. or convert it later: cvtColor(mat,mat,COLOR_BGRA2BGR);

but those will just discard the alpha channel. to replace pixels, try like:

Mat channels[4];
split(mat, channels);
merge(channels,3,mat);
mat.setTo(Scalar::all(255), (channels[3]<255));

(though i doubt, that this will be faster, than your loop)

in general, try to avoid images with alpha, they were made to look good on a web-page, but are a bat fit for computer-vision

edit flag offensive delete link more

Comments

I'm using javaCV and have the same problem, could you please let me know what is the best way to do that in javaCV the way you used the setTo() is not working in javaCV I tried to rewrite your code and here is the result

        MatVector channels = new MatVector();
        split(img,channels);
        merge(channels.get(0),1,orgImg);
        merge(channels.get(1),1,orgImg);
        merge(channels.get(2),1,orgImg);
        orgImg.setTo(new Mat(Scalar.all(255)), channels.get(3) )   ;
reza777 gravatar imagereza777 ( 2017-10-05 18:25:06 -0600 )edit

don't use javaCV, it is not supported from opencv at all, and we cannot help you with it.

berak gravatar imageberak ( 2017-10-05 18:35:00 -0600 )edit

the fact that you are not supporting something is OK and I can understand, but not your recommendation. thanks.

reza777 gravatar imagereza777 ( 2017-10-05 18:43:30 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2016-11-03 03:48:07 -0600

Seen: 3,970 times

Last updated: Nov 03 '16