Search code examples
pythonimage-processinghistogramhistogram-equalization

Histogram equalization for python


I have this routine to do histogram equalization of a photo:

def histeq(im,nbr_bins=256):

   #get image histogram
   imhist,bins = histogram(im.flatten(),nbr_bins,normed=True)
   cdf = imhist.cumsum() #cumulative distribution function
   cdf = 255 * cdf / cdf[-1] #normalize

   #use linear interpolation of cdf to find new pixel values
   im2 = interp(im.flatten(),bins[:-1],cdf)

   return im2.reshape(im.shape), cdf

#im = array(Image.open('AquaTermi_lowcontrast.jpg').convert('L'))
im = array(Image.open('Unequalized.jpg').convert('L'))
#Image.open('plant4.jpg').convert('L').save('inverted.jpg')

im2,cdf = histeq(im)

plt.imshow(im2)
plt.savefig("outputhisto.jpg")

When I run this with the picture from the wiki page for histogram equalization it results in this: enter image description here

Instead of properly adjusting the contrast of image to something along the lines of this. What am I doing wrong?


Solution

  • Are you sure you're just not rendering with the wrong colormap? Try

    plt.imshow(im2, cmap=plt.cm.gray)
    

    Or

    plt.imshow(im2, cmap=plt.get_cmap('gray'))