Make a pixel transparent in Matlab

前端 未结 2 1065

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 19:52

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

提交回复
热议问题