Search code examples
imagematlabpictureboximread

Make white background transparent png matlab


I am trying to remove the white background on my png picture I get from a code I created. This is the picture I get: enter image description here

I want to make the white background transparent, because I have several of those images that I want to combine using imfuse.

What I do is this (my picture is called 'A1.png'):

A1=imread('A1.png');
D=zeros(size(A1));
D(A1==255) =1;
imwrite(A1,'A11.png','alpha',D);

However I get an error like this Error using writepng>parseInputs (line 349) The value of 'alpha' is invalid. Expected input to be of size 829x600 when it is actually size 829x600x3.

829x600x3 uint8 is the size of A1. I understand I need to get rid of the x3 thing. But i don't know if it's when I save the pic or earlier in my code.

What do you guys think?


Solution

  • You need simply create D with one less dimension. Here is the code

    D = zeros( size(A(:,:,1)) );
    D( all( A==255, 3 ) ) = 1; 
    imwrite(A,'A11.png','alpha',D);