pythonimage-processingcomputer-vision

Min Max Image Histogram Stretching


I have a problem with fitting the histogram of an image to a specific range to get a better contrast.

First of all the data that I use starting from input image+histogram over to my output image+histogram to the output that I want+histogram:

My input image

Histogram of input image

My output image

The histogram from my output image

I want it to look like this (looks a lot smoother)

Histogram of the output image that I want

The description of the method in the program that I used just says "Maps black to the minimal intensity and white to the maximal intensity".

Here is the code to do the mapping:

for y in range(0, h):
    for x in range(0, w):
        image[y,x] = (((image[y,x] - smallest) / diff)  * 65535)

In this code is smallest the minimal intensity in the original image and diff the difference between max and min intensity.

What do I need to do, to get a smoother histogram in the end?

Thanks for helping!


Solution

  • If image is of an integer type, then (image[y,x] - smallest) / diff) is a smaller integer -- this operation rounds down the result, effectively quantifying the input gray levels.

    To prevent this from happening, pre-compute the multiplier as this:

    scale = 65535 / diff
    image[y,x] = (image[y,x] - smallest) * scale
    

    Alternatively, cast the pixel value to a floating-point number before computing the mapping, then cast back to integer to store it back in the image array.