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

时间:2010-04-06 17:56:38

标签: matlab image-processing

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

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

1 个答案:

答案 0 :(得分: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);

这应涵盖大多数图片类型,但有些异常值除外(例如alternate color spaces for TIFF images)。