image - 在python中绘制灰度图像直方图的问题
问题描述
我绘制了一个直方图
灰度图像的
使用 matplotlib。但是直方图看起来不像我想要的。
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
im=Image.open("lena.pgm")
pxl=list(im.getdata())
print pxl
columnsize,rowsize=im.size
a = np.array(pxl)
plt.hist(a, bins = 255)
plt.title("histogram")
plt.show()
我想要直方图
解决方案
直方图中的间隙是由于 bin 大小选择不当造成的。如果您调用hist(..., bins=255)
,numpy 将创建从数组的最小值到最大值的 256 个 bin。换句话说,垃圾箱将具有非整数宽度(在我的测试中:)[ 24. , 24.86666667, 25.73333333, 26.6 , ....]
。
因为您正在处理具有 255 个级别的图像,所以您应该创建 255 个宽度为 1 的 bin:
plt.hist(a, bins=range(256))
我们必须写256
,因为我们需要包括 bin 的最右边,否则不会包括值为 255 的点。
至于颜色,请按照评论中链接的问题中的示例进行操作
from PIL import Image
im=Image.open("lena.pgm")
a = np.array(im.getdata())
fig, ax = plt.subplots(figsize=(10,4))
n,bins,patches = ax.hist(a, bins=range(256), edgecolor='none')
ax.set_title("histogram")
ax.set_xlim(0,255)
cm = plt.cm.get_cmap('cool')
norm = matplotlib.colors.Normalize(vmin=bins.min(), vmax=bins.max())
for b,p in zip(bins,patches):
p.set_facecolor(cm(norm(b)))
plt.show()
推荐阅读
- javascript - querySelectorAll 请求中的错误“对象引用链太长”
- python - 如何将 yyyymmdd 日期转换为 pandas 中的正确格式?
- linux - 运行“ps -aux |grep bash”后的命令“-bash”是什么
- ios - 如何在 GCD 中的 NSOperationQueue 等操作之间添加依赖关系
- c - 与 C 相比,在 C++ 中使用文件
- c# - Alea GPU 内存分配限制
- python - Python:数据集中行的百分比
- html - 如何拉伸自动完成输入
- python - 如何将 Numpy 4D 数组保存到 CSV?
- python - Python,从包含某个单词的 xml 站点地图中提取 url