import cv2import cv2from matplotlib import pyplot as pltimport numpy as npimg = cv2imreadcjpggray = cv2cvtColorimgcv2COLOR_BGR2GRAYhist = cv2calcHistgray0None2560256pltsubplot221 pltimshowimg gray plt
要将直方图绘制成边缘的一圈轮廓,可以使用OpenCV的绘图函数cv2.circle()和cv2.polylines()。具体步骤如下:
-
首先绘制直方图,获取直方图的边缘轮廓。可以使用cv2.findContours()函数获取轮廓,并使用cv2.drawContours()函数将轮廓绘制在一张黑色图像上。
-
创建一张新的图像,大小与原图相同,将直方图绘制在该图像的中心位置。
-
使用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('Image1') 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(img) plt.title('Histogram with contour') plt.show()
原文地址: https://www.cveoy.top/t/topic/bLN0 著作权归作者所有。请勿转载和采集!