How to use grethresh on indexed image in MATLAB?

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

Above is an example from the MATLAB documentation using grayscale images. How can I get this to work with the indexed image as alt text in this post ?

+4
source share
1 answer

You can first convert the indexed image and its color correction to a grayscale image using the IND2GRAY function:

 [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 want to make this a generalized approach for any type of image, here is one way to do this:

 %# 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 an indexed image if map isn't empty grayImage = ind2gray(X,map); %# Convert the indexed image to grayscale elseif ndims(X) == 3 %# It an RGB image if X is 3-D grayImage = rgb2gray(X); %# Convert the RGB image to grayscale else %# It 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 types of images, with the exception of some outliers (for example, alternative color spaces for TIFF images ).

+2
source

Source: https://habr.com/ru/post/1306153/


All Articles