python如何获得图像中一条直线上的平均像素强度并将其绘制在图形上?

2024-04-19 11:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个灰度图像。我想生成一个直方图,对应于x和y轴上每一行的平均像素强度。你知道吗

for example this image should produce two histograms that look like bell curves


Tags: 图像imageforthatexample像素直方图this
3条回答

我会用枕头,小屁股和垫子

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数组,您可以从图像.形状你知道吗

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)]

然后可以使用matplotlibhttps://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

相关问题 更多 >