Make a pixel transparent in Matlab
Asked Answered
P

2

9

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?

Paedo answered 18/4, 2012 at 15:59 Comment(0)
T
17

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);
Threepiece answered 18/4, 2012 at 16:9 Comment(2)
Thanks @ademing2. Do you have a brief example?Paedo
Thanks. But, the image output is only 1x1 and 87 bytes. Any ideas?Paedo
P
14

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;
Percolation answered 27/9, 2013 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.