MATLAB Answers

Kazi
0

Can you help me with this code? It's about setting the 'Alpha' of an image with an Alpha channel.

Asked by Kazi
on 25 Nov 2016
Latest activity Edited by Ruben Costa on 8 Jul 2019
Hi, I am trying to convert the background of an image into transparent.
I took an image as input, then created an alpha channel. The alpha channel is supposed to be a matrix with 1 where there is white color. Then the output image will be transparent where there were initially white color pixels.
This is the code I wrote ...
clc
clear
img=imread('practice.jpg'); % Taking the truecolor image as input.
alphachannel = all(img == 255, 3);% convert the white colors in each pixel
% into 1, and all other color into
% zero. The type of the output image is
% logical.
alphachannel_2=uint8(alphachannel); % convert the logical array into uint8 type
imwrite(img, 'practice_2.png', 'Alpha', alphachannel_2); % output image
I practiced with the following image ...
The white color is supposed to be transparent in the output image. But as it turns out the whole image is being transparent in the output image. The red,blue and black boxes aren't appearing in the output image.
But instead, if I use the ' Transparency' attribute of imwrite() function, then it works.
clc
clear
img=imread('practice.jpg'); % Taking the truecolor image as input.
imwrite(img, 'practice_2.png', 'Transparency',[1 1 1]); % output image
But, using 'Transparency' lets me to convert the image into transparent background based on only a single color, not on a certain Alpha Channel. What am I doing wrong with the first code ?
I am including the image and the matlab file, if you need.
Thanks in advance :)

  0 Comments

Sign in to comment.

2 Answers

回答者: Walter Roberson
2016 年 11 月 25 日

It appears to me that the PNG alpha parameter should be floating point in the range 0 to 1, not uint8.

  0 Comments

Sign in to comment.


回答者: Ruben Costa 2019 年 7 月 5 日
編集済み: Ruben Costa 2019 年 7 月 8 日

I picked up your code and try to do some changes and for me this works! Probably you don´t need it already but is here for people like me, who needs to solve the same problem and are searching for a solution!
You can change the condition to the colour that you want to remove but i used this condition to solve the problem of Kazi!
clc
clear
img=imread('practice.jpg'); % Taking the truecolor image as input.
lin=size(img,1);
col=size(img,2);
M=ones(lin,col); % set a matrix of ones with the same dimensions as original image
for lines=1:lin
for columns=1:col
if (img(lines,columns,1)>=250) & (img(lines,columns,2)>=250) & (img(lines,columns,3)>=250)
M(lines,columns)=0; %setting the value on the matrix to 0 when the condition is true
end
end
end
%the M is a mask and when M is 0 the pixel will be transparent
imwrite(img, 'practice_final.png', 'Alpha', M); % output image

  0 Comments

Sign in to comment.