views:

356

answers:

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

The above is an example from the MATLAB documentation using a grayscale image. How can I make it work with an indexed image like alt text in this post?

+2  A: 

You can first convert the indexed image and its colormap into a grayscale image using the function IND2GRAY:

[X,map] = imread('SecCode.php.png');  %# Read the indexed image and colormap
grayImage = ind2gray(X,map);          %# Convert to grayscale image

Then you can apply the code you have above:

level = graythresh(grayImage);     %# Compute threshold
bwImage = im2bw(grayImage,level);  %# Create binary image
imshow(bwImage);                   %# Display image

EDIT:

If you wanted to make this a generalized approach for any type of image, here's one way you could do it:

%# 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);

This should cover most image types, with the exception of some outliers (like alternate color spaces for TIFF images).

gnovice
But RGB image is M*N*3,which is not grayscale image:M*N,right?
But seems it's working,strange..
@user198729: The function GRAYTHRESH still works for RGB images, but maybe not *exactly* the same way as it does for grayscale images, so I updated my answer to use IND2GRAY instead.
gnovice
Last question,how to make it a generalized function that can grayscale various kinda images?
@user198729: I updated my answer with a general solution.
gnovice
That is an impressively complete solution.
Jonas