在Matlab中使像素透明 [英] Make a pixel transparent in Matlab

查看:257
本文介绍了在Matlab中使像素透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在matlab中导入了图像,并且在显示之前如何使图像的背景透明?例如,我在白色背景上有一个红色的球,我该如何使图像的白色像素透明,以使只有红色的球可见并且白色像素是透明的?

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?

推荐答案

您需要确保图片以"png"格式保存.然后,您可以使用"Alpha"参数,该文件是一个矩阵,用于分别指定每个像素的透明度.本质上是一个布尔矩阵,如果像素是透明的,则为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);

这篇关于在Matlab中使像素透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆