Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a pixel transparent in Matlab

I have imported an image in matlab and before I display it how would I make the background of the image transparent? For example I have a red ball on a white background, how would i make the white pixels of the image tranparent so that only the red ball is visible and the white pixels are transparent?

like image 592
omegaFlame Avatar asked Apr 18 '12 15:04

omegaFlame


1 Answers

You need to make sure the image is saved in the 'png' format. Then you can use the 'Alpha' parameter of a png file, which is a matrix that specifies the transparency of each pixel individually. It is essentially a boolean matrix that is 1 if the pixel is transparent, and 0 if not. This can be done easily with a for loop as long as the color that you want to be transparent is always the same value (i.e. 255 for uint8). If it is not always the same value then you could define a threshold, or range of values, where that pixel would be transparent.

Update :

First generate the alpha matrix by iterating through the image and (assuming you set white to be transparent) whenever the pixel is white, set the alpha matrix at that pixel as 1.

# X is your image
[M,N] = size(X);
# Assign A as zero
A = zeros(M,N);
# Iterate through X, to assign A
for i=1:M
   for j=1:N
      if(X(i,j) == 255)   # Assuming uint8, 255 would be white
         A(i,j) = 1;      # Assign 1 to transparent color(white)
      end
   end
end

Then use this newly created alpha matrix (A) to save the image as a ".png"

imwrite(X,'your_image.png','Alpha',A);
like image 173
Aaron Deming Avatar answered Sep 17 '22 15:09

Aaron Deming