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

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

以上是使用灰度图像的MATLAB文档中的示例.如何在this post中使用索引图像(如alt text http://internationalpropertiesregistry.com/Server/showFile.php?file=%2FUpload%2FSecCode.php.pngffe2c2ae5fd4fffb0c9bc4a75bde89da.png)?

最佳答案 您可以使用函数
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);

这应该涵盖大多数图像类型,除了一些异常值(如alternate color spaces for TIFF images).

点赞