我使用下面的代码来使用2种方法生成彩色图像的直方图:
方法1 :-
使用cv2.calalHist()函数计算frequency
的线条图
方法2 :-
观察:两种直方图大致相似。第一个直方图(使用plt.plot)看起来相当平滑。然而,第二直方图(使用plt.hist)有额外的尖峰和下降。
问题:,因为图像中只有int值,所以不应该有不一致的绑定。在直方图2中出现这些额外的尖峰和下降的原因是什么?
blue_bricks = cv2.imread('Computer-Vision-with-Python/DATA/bricks.jpg')
fig = plt.figure(figsize=(17,10))
color = ['b','g','r']
# Histogram Type-1
fig.add_subplot(2,2,1)
for i,c in enumerate(color):
hist = cv2.calcHist([blue_bricks], mask=None, channels=[i], histSize=[256], ranges=[0,256])
plt.plot(hist,color=c)
plt.title('Histogram-1')
# Histogram Type-2
fig.add_subplot(2,2,2)
for i,c in enumerate(color):
plt.hist(blue_bricks[:,:,i].flatten(),color=c, alpha=0.5, bins=250)
plt.title('Histogram-2')

发布于 2021-06-06 08:05:49
bins=250在最低值和最高值之间创建251个等距的桶边。这些不符合离散值。当最高和最低之间的差额大于250时,一些垃圾箱将是空的。当差小于250时,一些回收箱将得到两个相邻数字的值,从而产生一个尖峰。此外,当叠加直方图时,所有直方图都使用完全相同的bin边是很方便的。
您需要在整数值之间精确地设置回收箱,设置bins=np.arange(-0.5, 256, 1)就可以做到这一点。或者,您可以使用海运的histplot(...., discrete=True)。
下面是一些数字较小的代码来说明正在发生的事情。
import matplotlib.pyplot as plt
import numpy as np
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(12, 3))
for ax in (ax1, ax2, ax3, ax4):
if ax in [ax1, ax3]:
x = np.arange(1, 10)
else:
x = np.arange(1, 12)
if ax in [ax1, ax2]:
bins = 10
else:
bins = np.arange(0.5, x.max() + 1, 1)
_, bin_edges, _ = ax.hist(x, bins=bins, ec='white', lw=2)
ax.vlines(bin_edges, 0, 2.5, color='crimson', ls='--')
ax.scatter(x, [2.2] * len(x), color='lime', s=50)
ax.set_title((f"{bins} bins" if type(bins) == int else "discrete bins") + f', {len(x)} values')
ax.set_xticks(x)
ax.set_yticks([0, 1, 2])
plt.tight_layout()
plt.show()

https://stackoverflow.com/questions/67855101
复制相似问题