绘制红、绿、蓝三个通道的直方图,用python语言写出来
时间: 2024-03-24 10:41:33 浏览: 27
好的,以下是用Python语言绘制红、绿、蓝三个通道的直方图的代码示例:
``` python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读入彩色图像
img = cv2.imread('test.jpg')
# 分离通道
b, g, r = cv2.split(img)
# 绘制直方图
plt.hist(b.ravel(), 256, [0, 256], color='blue')
plt.hist(g.ravel(), 256, [0, 256], color='green')
plt.hist(r.ravel(), 256, [0, 256], color='red')
# 显示直方图
plt.show()
```
其中,`cv2.imread()`函数用于读入彩色图像,`cv2.split()`函数用于将彩色图像分离为红、绿、蓝三个通道的图像,`plt.hist()`函数用于绘制直方图。最后,调用`plt.show()`函数来显示直方图。
相关问题
python分别绘制出图片红、绿、蓝色直方图
可以使用Python中的Matplotlib库来绘制图片的红、绿、蓝色直方图。以下是代码示例:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图片
img = cv2.imread('image.png')
# 将图片转换成RGB模式
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 计算红、绿、蓝三个通道的直方图
r_hist = cv2.calcHist([img], [0], None, [256], [0,256])
g_hist = cv2.calcHist([img], [1], None, [256], [0,256])
b_hist = cv2.calcHist([img], [2], None, [256], [0,256])
# 绘制三个通道的直方图
plt.figure()
plt.title('Red Histogram')
plt.xlabel('Bins')
plt.ylabel('# of Pixels')
plt.plot(r_hist, color='red')
plt.xlim([0, 256])
plt.figure()
plt.title('Green Histogram')
plt.xlabel('Bins')
plt.ylabel('# of Pixels')
plt.plot(g_hist, color='green')
plt.xlim([0, 256])
plt.figure()
plt.title('Blue Histogram')
plt.xlabel('Bins')
plt.ylabel('# of Pixels')
plt.plot(b_hist, color='blue')
plt.xlim([0, 256])
plt.show()
```
这段代码中,首先使用OpenCV库读取并将图片转换成RGB模式,然后使用`cv2.calcHist()`函数计算出红、绿、蓝三个通道的直方图。最后使用Matplotlib库绘制出三个通道的直方图。
python多个属性绘制直方图
可以使用 Python 的 Matplotlib 库来绘制直方图。下面是一个示例代码,可以绘制多个属性的直方图:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
data = np.random.randn(1000, 3)
# 绘制直方图
fig, axs = plt.subplots(1, 3, figsize=(10, 5), sharey=True)
axs[0].hist(data[:, 0], bins=30)
axs[0].set_title('Attribute 1')
axs[1].hist(data[:, 1], bins=30)
axs[1].set_title('Attribute 2')
axs[2].hist(data[:, 2], bins=30)
axs[2].set_title('Attribute 3')
plt.show()
```
这段代码中,首先使用 numpy 库生成了一个 1000 行 3 列的随机数矩阵,表示了三个属性的数据。然后,使用 plt.subplots() 函数创建了一个大小为 1x3 的子图,即三个子图排列在一行中。接着,对每个子图使用 hist() 函数绘制了对应属性的直方图,并设置了标题。最后,调用 plt.show() 函数显示绘制的图形。
你可以根据自己的需求修改代码中的数据和参数,以便绘制符合自己需求的直方图。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)