How are the indices computed in gray2ind(...)?

1 view (last 30 days)
In the below code, I would like to know the mathematics that was involved behind generating an index for a pixel. Does it consider the distribution of intensity values of all the pixels in the image? Or, does it just consider pixel by pixel independently, and generate an index?
camera = imread("cameraman.tif");
size(camera)
ans = 1×2
256 256
class(camera)
ans = 'uint8'
[x, map] = gray2ind(camera, 32);
class(x)
ans = 'uint8'
camera(110:115, 110:115)
ans = 6×6
11 11 11 11 12 12 12 12 13 13 13 14 13 12 12 12 12 13 13 12 12 12 13 15 12 11 12 13 16 15 12 12 13 14 16 15
x(110:115, 110:115)
ans = 6×6
1 1 1 1 1 1 1 1 2 2 2 2 2 1 1 1 1 2 2 1 1 1 2 2 1 1 1 2 2 2 1 1 2 2 2 2

Accepted Answer

DGM
DGM on 16 Oct 2021
Here's an example for a uint8 image:
A = imread('cameraman.tif');
maplength = 32;
[B bmap] = gray2ind(A,maplength);
% assuming uint8 input
C = uint8((maplength-1)/255 * double(A));
cmap = gray(maplength);
immse(B,C) % images are the same
ans = 0
immse(bmap,cmap) % maps are the same
ans = 0
You can also just look at how it's done by opening gray2ind.m.
So it appears that it pays no attention to the actual image content either locally or globally. It merely does a crude uniform quantization based on the standard data range defined by the numeric class.
This is in contrast to rgb2ind() which is both more complicated in its available palette reduction methods, but also wrapped up in mex, so figuring out how it works isn't as easy.
  3 Comments
DGM
DGM on 17 Oct 2021
I'm not sure what would be best or easiest, though I imagine one approach may simply be to expand the image on dim3 to create a grayscale RGB image, and then feed it to rgb2ind(), using the common syntax
idxpict = rgb2ind(repmat(graypict,[1 1 3]),N);
which would do minimum variance quantization (as opposed to gray2ind()'s uniform quantization). You might try doing it with kmeans, but the last time I tinkered with the idea, I found it to be relatively slow. Maybe I could've been more clever about it, but that's what I found in my case.
If you're using Octave, I don't know how similar the corresponding functions behave.
Harsha Yogeshappa
Harsha Yogeshappa on 18 Oct 2021
Edited: Harsha Yogeshappa on 18 Oct 2021
Yes, kmeans clustering is very very slow for me. I have an image stack that amounts to 55M pixels in total. And, clustering them to 256 different clusters was time consuming.
However, I was able to get what I wanted as output but, surely, kmeans seems not to be the way to do it. I will try understanding what rgb2ind(...) does, and see if it fits my need.
Thanks,

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!