直方图均衡化给我全黑图像
Histogram equalization gives me 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()
cdf在均衡之前需要归一化。
一种方法是将 np.histogram 的可选参数 density 设置为 True
:
hist, bins = np.histogram(img1,256,[0,255],density=True)
另一种方法是计算后的cdf除以总像素数:
cdf = hist.cumsum()
cdf /= cdf[-1]
我还将均衡部分简单地更改为:
T = (255 * cdf).astype(np.uint8)
im2 = T[fl]
Wikipedia 建议改用这个转换公式:
T = (np.ceil(256 * cdf) - 1).astype(np.uint8)
我正在学习图像处理,我正在编写代码来进行直方图均衡,但输出总是给我一个全黑的图像。
这是我的代码:
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()
cdf在均衡之前需要归一化。
一种方法是将 np.histogram 的可选参数 density 设置为 True
:
hist, bins = np.histogram(img1,256,[0,255],density=True)
另一种方法是计算后的cdf除以总像素数:
cdf = hist.cumsum()
cdf /= cdf[-1]
我还将均衡部分简单地更改为:
T = (255 * cdf).astype(np.uint8)
im2 = T[fl]
Wikipedia 建议改用这个转换公式:
T = (np.ceil(256 * cdf) - 1).astype(np.uint8)