matlabquantizationlab-color-space

Lab color space quantization in Matlab


In Matlab, I've converted an RGB image to CIE Lab color space.

Lab = applycform(rgbImage, makecform('srgb2lab'));
L = Lab(:, :, 1);
a = Lab(:, :, 2);
b = Lab(:, :, 3);

How to quantize and combine those 3 channels?

...

For the comparison, this is what I did with RGB:

In the main program

R = rgbImage(:, :, 1);
G = rgbImage(:, :, 2);
B = rgbImage(:, :, 3);

binsR = 4;
binsG = 4;
binsB = 4;

quantR = Quantize(binsR, R, 255);
quantG = Quantize(binsG, G, 255);
quantB = Quantize(binsB, B, 255);

quantColors = (binsB*binsG*quantR) + (binsB+quantG) + quantB;

Quantize.m

function quant = Quantize(bins, data, maxdata)

quant = data * (bins/maxdata);
quant = floor(quant);
quant(quant >= (bins - 1)) = (bins - 1);

end

Solution

  • It turns out that I've found the solution :D

    And the good thing is:

    The code is relatively simpler!

    In the main program

    labImage = applycform(rgbImage, makecform('srgb2lab'))
    labImage = lab2double(labImage)
    L = labImage(:, :, 1)
    a = labImage(:, :, 2)
    b = labImage(:, :, 3)
    
    bins_L = 10
    bins_a = 10
    bins_b = 10
    
    quant_L = QuantizeMT(bins_L, L)
    quant_a = QuantizeMT(bins_a, a)
    quant_b = QuantizeMT(bins_b, b)
    
    quantColors = sqrt(quant_L.^2 + quant_a.^2 + quant_b.^2)
    

    QuantizeMT.m

    function quant = QuantizeMT(bins, data)
    
    % Number of divider is number of segments (bins) minus 1
    thresh = multithresh(data, bins-1)
    % Quantize image (or channel) based on segments
    quant = imquantize(data, thresh)
    
    end
    

    Notes:

    1. We can continue without converting Lab to Double, but an error may occur for some images. It is because the values in Lab are encoded by default. So some slightly different values won't be detected by the multithresh function, resulting some identical thresh values. Based on imquantize documentation: "Values of the discrete quantization levels must be in monotonically increasing order." Therefore it is better to use lab2double function.
    2. multithresh and imquantize functions should be compatible with any color spaces. Despite there is exception for some RGB images, error at multithresh step, usually in the B (blue) channel. I don't know why. But I get no problem when I use imquantize to the whole image, not channel by channel.
    3. The formula to combine the 3 channels is called Euclidean Distance. Fully compatible with any color spaces and produce better result than other formula when used in texture detection.

    PS: I use Matlab R2012b.