2

我正在尝试删除从我创建的代码中获得的 png 图片上的白色背景。这是我得到的图片: 在此处输入图像描述

我想让白色背景透明,因为我有几个想要使用 imfuse 组合的图像。

我做的是这个(我的图片叫做'A1.png'):

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

但是,我得到一个错误,如使用 writepng>parseInputs 的错误(第 349 行)'alpha' 的值无效。实际大小为 829x600x3 时,预期输入大小为 829x600。

829x600x3 uint8 是 A1 的大小。我知道我需要摆脱 x3 的东西。但我不知道是在我保存图片时还是在我的代码中更早的时候。

你们有什么感想?

4

3 回答 3

2

您只需创建D少一维即可。这是代码

D = zeros( size(A(:,:,1)) );
D( all( A==255, 3 ) ) = 1; 
imwrite(A,'A11.png','alpha',D);
于 2015-04-16T18:27:58.733 回答
1

以下 MATLAB 代码可以去除白色背景(即将数据写入具有透明背景的新图像):

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

瞧,希望有帮助!

于 2017-06-11T15:31:45.623 回答
0

这是我的做法。我有一个没有 alpha 通道的 png,这就是为什么我很难使用上面提供的代码使其透明。

我设法通过首先添加一个 alpha 通道然后将其读回并使用上面的代码来使其透明。

[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);
于 2017-01-05T04:25:50.480 回答