I = imread('coins.png');
level = graythresh(I);
BW = im2bw(I,level);
imshow(BW)
以上是 MATLAB 文档中使用灰度图像的示例。我怎样才能让它与像 这样的索引图像一起工作? 在 this post ?
您可以先使用函数 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 )。
我是一名优秀的程序员,十分优秀!