我写了下面的代码,得到的是下面的输出。我想做的是写一个直方图均衡化函数(没有内置的方法),我没有得到任何错误,但输出不是它应该是什么。我没有注意到我的代码中有任何逻辑错误。虽然,在编写用于计算cdf和/或映射的循环时,我无法准确地跟踪其背后发生的情况,但问题可能存在,但我不确定
def my_float2int(img):
img = np.round(img * 255, 0)
img = np.minimum(img, 255)
img = np.maximum(img, 0)
img = img.astype('uint8')
return img
def equalizeHistogram(img):
img_height = img.shape[0]
img_width = img.shape[1]
histogram = np.zeros([256], np.int32)
# calculate histogram
for i in range(0, img_height):
for j in range(0, img_width):
histogram[img[i, j]] +=1
# calculate pdf of the image
pdf_img = histogram / histogram.sum()
### calculate cdf
# cdf initialize .
cdf = np.zeros([256], np.int32)
# For loop for cdf
for i in range(0, 256):
for j in range(0, i+1):
cdf[i] += pdf_img[j]
cdf_eq = np.round(cdf * 255, 0) # mapping, transformation function T(x)
imgEqualized = np.zeros((img_height, img_width))
# for mapping input image to s.
for i in range(0, img_height):
for j in range(0, img_width):
r = img[i, j] # feeding intensity levels of pixels into r.
s = cdf_eq[r] # finding value of s by finding r'th position in the cdf_eq list.
imgEqualized[i, j] = s # mapping s thus creating new output image.
# calculate histogram equalized image here
# imgEqualized = s # change this
return imgEqualized
# end of function
# 2.2 obtain the histogram equalized images using the above function
img_eq_low = equalizeHistogram(img_low)
img_eq_high = equalizeHistogram(img_high)
img_eq_low = my_float2int(img_eq_low)
img_eq_high = my_float2int(img_eq_high)
# 2.3 calculate the pdf's of the histogram equalized images
hist_img_eq_low = calcHistogram(img_eq_low)
hist_img_eq_high = calcHistogram(img_eq_high)
pdf_eq_low = hist_img_eq_low / hist_img_eq_low.sum()
pdf_eq_high = hist_img_eq_high / hist_img_eq_high.sum()
# 2.4 display the histogram equalized images and their pdf's
plt.figure(figsize=(14,8))
plt.subplot(121), plt.imshow(img_eq_low, cmap = 'gray', vmin=0, vmax=255)
plt.title('Hist. Equalized Low Exposure Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img_eq_high, cmap = 'gray', vmin=0, vmax=255)
plt.title('Hist. Equalized High Exposure Image'), plt.xticks([]), plt.yticks([])
plt.show()
plt.close()
预期输出:使用内置方法
我发现了两个小错误和一个效率问题:
cdf = np.zeros([256], np.int32)
替换为cdf = np.zeros([256], float)
在循环中,您将
float
元素放在cdf
中,因此类型应该是float
而不是int32
李>img = np.round(img * 255, 0)
替换为img = np.round(img, 0)
(在my_float2int
中)。您将
img
缩放255倍(第一次是在cdf_eq = np.round(cdf * 255, 0)
)李>您可以更有效地计算
cdf
。您的实施:
建议实施(计算“累计金额”的更有效方法):
这不是一个bug,而是一种学术问题(关于复杂性)
下面是更正代码的示例(仅使用
img_low
):结果:
相关问题 更多 >
编程相关推荐