%# 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);
以上代码兼容各种图片格式。
加个效果对比:
处理前

处理后
