You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Histogram equalization(直方图均衡化)运行后输出全黑图像问题求助

直方图均衡化输出全黑图像问题解决

错误原因

代码的问题出在直方图均衡化公式的实现环节,分母多乘了255,导致计算得到的映射后像素值范围被压缩到0~1区间,转换为uint8类型后数值全部取整为0,最终输出全黑图像。

错误代码片段

# 原错误的均衡化计算逻辑
num_cdf_m = (cdf_m - cdf_m.min())*255
den_cdf_m =  (cdf_m.max()-cdf_m.min())*255 # 此行多乘了多余的255
cdf_m = num_cdf_m/den_cdf_m

修正方法

直接移除分母位置多余的*255即可,修正后的计算逻辑如下:

# 修正后的均衡化计算逻辑
num_cdf_m = (cdf_m - cdf_m.min())*255
den_cdf_m =  cdf_m.max() - cdf_m.min()
cdf_m = num_cdf_m / den_cdf_m

修正后完整可运行代码

import numpy as np
from PIL import Image

img = Image.open('/home/thaidy/Desktop/ex.jpg').convert('L')
# 转换为numpy数组
img1 = np.asarray(img)

# 转换为一维数组
fl = img1.flatten()

# 计算直方图和 bins
hist, bins = np.histogram(img1, 256, [0, 255])

# 计算累积分布函数cdf
cdf = hist.cumsum()

# 屏蔽cdf为0的位置
cdf_m = np.ma.masked_equal(cdf, 0)

# 执行直方图均衡化
num_cdf_m = (cdf_m - cdf_m.min()) * 255
den_cdf_m = cdf_m.max() - cdf_m.min()
cdf_m = num_cdf_m / den_cdf_m

# 被屏蔽的位置赋值为0
cdf = np.ma.filled(cdf_m, 0).astype('uint8')
# 用cdf映射原像素值
im2 = cdf[fl]
# 转换回二维数组
im3 = np.reshape(im2, img1.shape)
im4 = Image.fromarray(im3)
im4.save('/home/thaidy/Desktop/output.jpg')
im4.show()

修正后计算得到的映射像素值范围为0~255,转换为uint8后数值正常,即可输出正确的均衡化后图像。

内容的提问来源于stack exchange,提问作者thaidy_04

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:36:00