does anyone can help me? I am studying image processing and I am writing a code to do a Histogram equalization, but the output always give me an all black image.
import numpy as np
import scipy.misc, math
from PIL import Image
img = Image.open('/home/thaidy/Desktop/ex.jpg').convert('L')
#converting to ndarray
img1 = np.asarray(img)
#converting to 1D
fl = img1.flatten()
#histogram and the bins are computed
hist, bins = np.histogram(img1,256,[0,255])
#cdf computed
cdf = hist.cumsum()
#places where cdf = 0 is ignored
#rest stored in cdf_m
cdf_m = np.ma.masked_equal(cdf,0)
#histogram eq is performed
num_cdf_m = (cdf_m - cdf_m.min())*255
den_cdf_m = (cdf_m.max()-cdf_m.min())*255
cdf_m = num_cdf_m/den_cdf_m
#the masked places are now 0
cdf = np.ma.filled(cdf_m,0).astype('uint8')
#cdf values assigned in the flattened array
im2 = cdf[fl]
#transformin in 2D
im3 = np.reshape(im2,img1.shape)
im4 = Image.fromarray(im3)
im4.save('/home/thaidy/Desktop/output.jpg')
im4.show()
This is my code
CodePudding user response:
The cdf needs to be normalized before the equalization.
One way to do that is to set the optional parameter density of np.histogram to True
:
hist, bins = np.histogram(img1,256,[0,255],density=True)
Other way is to divide cdf after computation by total pixel count:
cdf = hist.cumsum()
cdf /= cdf[-1]
I would also change the equalization part to simply:
T = (255 * cdf).astype(np.uint8)
im2 = T[fl]
Wikipedia suggests to use this transformation formula instead:
T = (np.ceil(256 * cdf) - 1).astype(np.uint8)