Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change number of gray levels in a grayscale image in matlab

I am rather new to matlab, but I was hoping someone could help with this question. So I have a color image that I want to convert to grayscale and then reduce the number of gray levels. So I read in the image and I used rgb2gray() to convert the image to grayscale. However, I am not sure how to convert the image to use only 32 gray levels instead of 255 gray levels.

I was trying to use colormap(gray(32)), but this seemed to have no effect on the plotted image itself or the colorbar under the image. So I was not sure where else to look. Any tips out there? Thanks.

like image 441
krishnab Avatar asked Jan 21 '13 08:01

krishnab


1 Answers

While result = (img/8)*8 does convert a grayscale image in the range [0, 255] to a subset of that range but now using only 32 values, it might create undesirable artifacts. A method that possibly produces visually better images is called Improved Grayscale Quantization (abbreviated as IGS). The pseudo-code for performing it can be given as:

mult = 256 / (2^bits)
mask = 2^(8 - bits) - 1
prev_sum = 0
for x = 1 to width
    for y = 1 to height
        value = img[x, y]
        if value >> bits != mask:
            prev_sum = value + (prev_sum & mask)
        else:
            prev_sum = value
        res[x, y] = (prev_sum >> (8 - bits)) * mult

As an example, consider the following figure and the respective quantizations with bits = 5, bits = 4, and bits = 3 using the method above:

enter image description hereenter image description hereenter image description hereenter image description here

Now the same images but quantized by doing (img/(256/(2^bits)))*(256/(2^bits)):

enter image description hereenter image description hereenter image description hereenter image description here

This is not a pathological example.

like image 86
mmgp Avatar answered Sep 28 '22 00:09

mmgp