Make white background transparent png matlab

岁酱吖の 提交于 2020-03-03 03:05:48

问题


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:

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?


回答1:


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);



回答2:


Here is how I did it. I have a png that does not have an alpha channel which is why I had a hard time making it transparent using the code presented above.

I managed to make it transparent by first adding an alpha channel then reading it back in and used the code above.

[RGBarray,map,alpha] = imread('image1.png'); % if alpha channel is empty the next 2 lines add it

imwrite(RGBarray, 'image1_alpha.png', 'png', 'Alpha', ones(size(RGBarray,1),size(RGBarray,2)) )
[I,map,alpha] = imread('image1_alpha.png');

I2 = imcrop(I,[284.5 208.5 634 403]);
alpha = imcrop(alpha,[284.5 208.5 634 403]);

alpha( all( I2==255, 3 ) ) = 1; 
imwrite(I2,'image1_crop.png','alpha',alpha);



回答3:


The following MATLAB codes can remove a white background (i.e. write data to a new image with transparent background):

% name the input and output files
im_src = 'im0.png';
im_out = 'out.png';

% read in the source image (this gives an m * n * 3 array)
RGB_in = imread( im_src );
[m, n] = size( RGB_in(:,:,1) );

% locate the pixels whose RGB values are all 255 (white points ? --to be verified)
idx1 = ones(m, n);
idx2 = ones(m, n);
idx3 = ones(m, n);
idx1( RGB_in(:,:,1) == 255 ) = 0;
idx2( RGB_in(:,:,2) == 255 ) = 0;
idx3( RGB_in(:,:,3) == 255 ) = 0;

% write to a PNG file, 'Alpha' indicates the transparent parts
trans_val = idx1 .* idx2 .* idx3;
imwrite( RGB_in, im_out, 'png', 'Alpha', trans_val );

Voilà, hope that helps!



来源:https://stackoverflow.com/questions/29660771/make-white-background-transparent-png-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!