如何在 python 中的同一张图中绘制所有 3 个通道(红色、绿色、蓝色)的颜色直方图?
How can I plot a color histogram with all 3 channels (red, green, blue) in the same figure in python?
我使用下面的代码读取图像,然后在 python 中为其生成颜色直方图。
path = r"G:Y_individualProject\farm_colormap1.jpg"
colormap1 = cv2.imread(path)
colormap1=cv2.cvtColor(colormap1, cv2.COLOR_BGR2RGB)
plt.imshow(colormap1)
chans=cv2.split(colormap1)
colors=("b", "g", "r")
plt.figure()
plt.title("Color histogram")
plt.xlabel("Bins")
plt.ylabel("Number of pixels")
for (chan, c) in zip(chans, colors):
hist=cv2.calcHist([chan], [0], None, [256], [0,256])
plt.plot(hist, color=c)
plt.xlim([0,256])
plt.show()
但是,它将 3 个颜色通道(红色、绿色、蓝色)绘制成 3 个不同的图形,如下所示
那么我怎样才能将它们绘制在同一个图中呢?谢谢!
您调用 plt.show()
两次。因此,在执行循环的一部分后,它会显示,然后再次执行循环并显示第二部分。
固定版本如下:
path = r"G:Y_individualProject\farm_colormap1.jpg"
colormap1 = cv2.imread(path)
colormap1=cv2.cvtColor(colormap1, cv2.COLOR_BGR2RGB)
plt.imshow(colormap1)
chans=cv2.split(colormap1)
colors=("b", "g", "r")
plt.figure()
plt.title("Color histogram")
plt.xlabel("Bins")
plt.ylabel("Number of pixels")
for (chan, c) in zip(chans, colors):
hist=cv2.calcHist([chan], [0], None, [256], [0,256])
plt.plot(hist, color=c)
plt.xlim([0,256])
plt.show()
我使用下面的代码读取图像,然后在 python 中为其生成颜色直方图。
path = r"G:Y_individualProject\farm_colormap1.jpg"
colormap1 = cv2.imread(path)
colormap1=cv2.cvtColor(colormap1, cv2.COLOR_BGR2RGB)
plt.imshow(colormap1)
chans=cv2.split(colormap1)
colors=("b", "g", "r")
plt.figure()
plt.title("Color histogram")
plt.xlabel("Bins")
plt.ylabel("Number of pixels")
for (chan, c) in zip(chans, colors):
hist=cv2.calcHist([chan], [0], None, [256], [0,256])
plt.plot(hist, color=c)
plt.xlim([0,256])
plt.show()
但是,它将 3 个颜色通道(红色、绿色、蓝色)绘制成 3 个不同的图形,如下所示
您调用 plt.show()
两次。因此,在执行循环的一部分后,它会显示,然后再次执行循环并显示第二部分。
固定版本如下:
path = r"G:Y_individualProject\farm_colormap1.jpg"
colormap1 = cv2.imread(path)
colormap1=cv2.cvtColor(colormap1, cv2.COLOR_BGR2RGB)
plt.imshow(colormap1)
chans=cv2.split(colormap1)
colors=("b", "g", "r")
plt.figure()
plt.title("Color histogram")
plt.xlabel("Bins")
plt.ylabel("Number of pixels")
for (chan, c) in zip(chans, colors):
hist=cv2.calcHist([chan], [0], None, [256], [0,256])
plt.plot(hist, color=c)
plt.xlim([0,256])
plt.show()