用opencv与python写一个绘制图像直方图的程序
时间: 2023-05-21 20:07:01 浏览: 125
好的,可以使用以下代码:
```python
import cv2
from matplotlib import pyplot as plt
# Read image
img = cv2.imread('image.jpg')
# Convert image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Calculate histogram
hist = cv2.calcHist([gray_img], [0], None, [256], [0, 256])
# Plot histogram
plt.plot(hist)
plt.xlim([0, 256])
plt.show()
```
也可以使用numpy和matplotlib库来生成图像直方图:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Read image
img = cv2.imread('image.jpg')
# Convert image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Calculate histogram
hist, bins = np.histogram(gray_img.ravel(), 256, [0, 256])
# Plot histogram
plt.hist(gray_img.ravel(), 256, [0, 256])
plt.show()
```
以上两个程序的功能是一样的,可以根据自己的喜好来选择哪一个来使用。
阅读全文