Make a pixel transparent in Matlab

12,920

Solution 1

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

Solution 2

Note for loops in MATLAB should be avoided at all costs because they are slow. Rewriting code to remove the loops is commonly referred to as "vectorizing" code. In the case of ademing2's answer, it could be done as follows:

A = zeros(size(X));
A(X == 255) = 1;
Share:
12,920
omegaFlame
Author by

omegaFlame

Updated on July 27, 2022

Comments

  • omegaFlame
    omegaFlame almost 2 years

    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?

  • omegaFlame
    omegaFlame about 12 years
    Thanks @ademing2. Do you have a brief example?
  • omegaFlame
    omegaFlame about 12 years
    Thanks. But, the image output is only 1x1 and 87 bytes. Any ideas?