如何在MATLAB中对索引图像使用graythresh?

4
I = imread('coins.png');
level = graythresh(I);
BW = im2bw(I,level);
imshow(BW)

上面是 MATLAB 文档中使用灰度图像的示例。我如何将其用于像alt text这样的索引图像,就像在此贴文中所述?
1个回答

2

您可以使用函数IND2GRAY将索引图像及其颜色映射转换为灰度图像:

[X,map] = imread('SecCode.php.png');  %# Read the indexed image and colormap
grayImage = ind2gray(X,map);          %# Convert to grayscale image

然后您可以应用上面的代码:

level = graythresh(grayImage);     %# Compute threshold
bwImage = im2bw(grayImage,level);  %# Create binary image
imshow(bwImage);                   %# Display image

编辑:

如果你想将这个方法推广到任何类型的图像中,以下是一种实现方式:

%# Read an image file:

[X,map] = imread('an_image_file.some_extension');

%# Check what type of image it is and convert to grayscale:

if ~isempty(map)                %# It's an indexed image if map isn't empty
  grayImage = ind2gray(X,map);  %# Convert the indexed image to grayscale
elseif ndims(X) == 3            %# It's an RGB image if X is 3-D
  grayImage = rgb2gray(X);      %# Convert the RGB image to grayscale
else                            %# It's already a grayscale or binary image
  grayImage = X;
end

%# Convert to a binary image (if necessary):

if islogical(grayImage)         %# grayImage is already a binary image
  bwImage = grayImage;
else
  level = graythresh(grayImage);     %# Compute threshold
  bwImage = im2bw(grayImage,level);  %# Create binary image
end

%# Display image:

imshow(bwImage);

这应该涵盖大多数图像类型,但一些异常情况除外(例如TIFF图像的备用颜色空间)。


但是RGB图像是MN3,这不是灰度图像:M*N,对吗? - user198729
@user198729:函数GRAYTHRESH仍适用于RGB图像,但可能与灰度图像的使用方式不完全相同,因此我更新了我的答案,改用IND2GRAY。 - gnovice
最后一个问题,如何将其变成通用函数,可以将各种类型的图像转换为灰度图像? - user198729
这是一个令人印象深刻的完整解决方案。 - Jonas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接