【发布时间】:2019-12-12 04:37:41
【问题描述】:
我有一张灰度图像。我想生成一个直方图,对应于沿 x 和 y 轴的每条线的平均像素强度。
for example this image should produce two histograms that look like bell curves
【问题讨论】:
标签: python
我有一张灰度图像。我想生成一个直方图,对应于沿 x 和 y 轴的每条线的平均像素强度。
for example this image should produce two histograms that look like bell curves
【问题讨论】:
标签: python
我会使用 PIL/pillow、numpy 和 matplotlib
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# load Image as Grayscale
i = Image.open("QWiTL.png").convert("L")
# convert to numpy array
n = np.array(i)
# average columns and rows
# left to right
cols = n.mean(axis=0)
# bottom to top
rows = n.mean(axis=1)
# plot histograms
f, ax = plt.subplots(2, 1)
ax[0].plot(cols)
ax[1].plot(rows)
f.show()
【讨论】:
假设你的图片是一个numpy数组,你可以从image.shape中获取宽度和高度
pixel_sums_x = [sum(row) for row in image]
pixel_avgs_x = [s / image_height for s in pixel_sums_x]
pixel_sums_y = [sum(col) for col in zip(*image)]
pixel_avgs_y = [s / image_width for s in pixel_sums_y]
使用统计库:
pixel_avgs_x = [statistics.mean(row) for row in image]
pixel_avgs_y = [statistics.mean(col) for col in zip(*image)]
然后您可以使用 matplotlib https://matplotlib.org/3.1.1/gallery/statistics/hist.html 绘制直方图
【讨论】:
我会参考之前问过的question,它讨论了如何找到整个图像的平均像素强度。您可以编辑此代码,而不是循环遍历每个像素,只需逐行循环,然后您将获得一个强度值数组。然后,使用以下代码绘制数据图表:
import matplotlib.pyplot as plt
#number of bins in the histogram. You can decide
n_bins = 20
fig, axs = plt.subplots(1, 1, tight_layout=True)
axs[0].hist(x, bins=n_bins)
#x is your array of values
注意:需要下载matplotlib
【讨论】: