I = imread('coins.png');
level = graythresh(I);
BW = im2bw(I,level);
imshow(BW)
上面是 MATLAB 文档中使用灰度图像的示例。我如何将其用于像
![alt text](https://istack.dev59.com/OsccS.webp)
I = imread('coins.png');
level = graythresh(I);
BW = im2bw(I,level);
imshow(BW)
您可以使用函数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图像的备用颜色空间)。