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 in this post?
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 in this post?
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).