使用OpenCV绘制图像直方图及其边缘轮廓

本文将介绍如何使用OpenCV和Python绘制图像的直方图,并将其边缘轮廓绘制在图像本身上。

步骤:

  1. 读取图像并计算直方图: 使用cv2.imread()读取图像,使用cv2.cvtColor()转换为灰度图像,最后使用cv2.calcHist()计算直方图。
  2. 获取直方图边缘轮廓: 使用cv2.findContours()函数获取直方图的边缘轮廓点。
  3. 绘制直方图和轮廓: 可以使用Matplotlib库将直方图和其轮廓绘制出来,方便观察。
  4. 在图像上绘制边缘轮廓: 使用cv2.circle()函数绘制一个圆形作为基准,然后使用cv2.polylines()函数连接圆形上的点,绘制出直方图轮廓。

代码示例:

import cv2
from matplotlib import pyplot as plt
import numpy as np

# 读取图像
img = cv2.imread('c.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 计算直方图
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])

# 获取直方图边缘轮廓
contours, _ = cv2.findContours(hist.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_img = np.zeros_like(hist)
cv2.drawContours(contour_img, contours, -1, 255, thickness=1)

# 绘制直方图和轮廓
plt.subplot(221), plt.imshow(img, 'gray'), plt.title('Image')
plt.subplot(222), plt.hist(img.ravel(), 256, [0, 256]), plt.title('Histogram'), plt.xlim([0, 256])
plt.subplot(223), plt.imshow(hist, 'gray'), plt.title('Histogram')
plt.subplot(224), plt.imshow(contour_img, 'gray'), plt.title('Contour')

# 在图像上绘制边缘轮廓
h, w = contour_img.shape[:2]
center = (w // 2, h // 2)
radius = min(center) - 10
cv2.circle(img, center, radius, (0, 255, 0), thickness=2)
points = cv2.circle(np.zeros_like(img), center, radius, (255, 255, 255), thickness=2)
points = np.transpose(np.nonzero(points))
cv2.polylines(img, [points], True, (0, 255, 0), thickness=2)

# 显示结果
plt.figure()
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # matplotlib使用RGB颜色空间
plt.title('Image with Histogram Contour')
plt.show()

注意:

  • 代码中使用了Matplotlib库绘制直方图和轮廓,方便观察结果。
  • cv2.circle()函数用于在图像上绘制圆形。
  • cv2.polylines()函数用于在图像上绘制多边形,这里用于连接圆形上的点绘制轮廓。
  • 最终结果将显示带有直方图边缘轮廓的图像。

希望本文能够帮助您理解如何使用OpenCV绘制图像直方图及其边缘轮廓。

使用OpenCV绘制图像直方图及其边缘轮廓

原文地址: https://www.cveoy.top/t/topic/jtga 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录