简体   繁体   中英

How do I use graythresh on an indexed image in MATLAB?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM