Make transparent pixel in matlab

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

+6
source share
2 answers

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

Update:

First create an alpha matrix by repeating the image and (assuming that the white color becomes transparent) whenever the pixel is white, set the alpha matrix in this pixel to 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 ".png"

 imwrite(X,'your_image.png','Alpha',A); 
+15
source

Note for loops in MATLAB should be avoided at all costs because they are slow. The rewrite code for loop removal is usually called a β€œvectorized” code. In the case of ademing2's answer, this can be done as follows:

 A = zeros(size(X)); A(X == 255) = 1; 
+10
source

Source: https://habr.com/ru/post/913555/


All Articles