且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Matlab中使像素透明

更新时间:2023-02-26 14:57:16

您需要确保图片以"png"格式保存.然后,您可以使用"Alpha"参数文件的a>,该文件是一个矩阵,用于分别指定每个像素的透明度.本质上是一个布尔矩阵,如果像素是透明的,则为1,否则为0.只要要透明的颜色始终是相同的值(即uint8为255),就可以使用for循环轻松完成此操作.如果它的值不总是相同,则可以定义一个阈值或值范围,该像素将是透明的.

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.

更新:

首先通过遍历图像来生成alpha矩阵,并(假设您将白色设置为透明)每当像素为白色时,将该像素处的alpha矩阵设置为1.

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

然后使用这个新创建的alpha矩阵(A)将图像另存为".png"

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

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