首页 > 解决方案 > 如何使用opencv-python标记中心并计算图像的直径?

问题描述

我正在研究中心的识别和图像渲染。我cv2.findContours用来划定感兴趣图像的边缘。并cv.minEnclosingCircle (cnt)用于环绕我感兴趣的区域。下面的代码我可以识别每个 ROI 的中心,但我无法在图像的输出中标记与我要计算的图像相对应的圆圈,并且我想用 pqno 点标记确切位置该算法确定了中心。

import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText


thresh = cv2.imread('IMD044.png',0)
_, contours,hierarchy = cv2.findContours(thresh,2,1)
print (len(contours))
cnt = contours

for i in range (len(cnt)):
    (x,y),radius = cv2.minEnclosingCircle(cnt[i])
    center = (int(x),int(y))
    radius = int(radius)
    cv2.circle(thresh,center,radius,(0,255,0),2)
    print ('Circle: ' + str(i) + ' - Center: ' + str(center) + ' -     Radius: ' + str(radius))
plt.text(x-15, y+10, '+', fontsize=25, color = 'red')
plt.text(10, -10, 'Centro: '+str(center), fontsize=11, color = 'red')
plt.text(340, -10, 'Diametro: '+str((radius*2)/100)+'mm', fontsize=11, color = 'red')
plt.Circle(x, y, color='red', fill=False)
plt.imshow(thresh, cmap='gray')
plt.show()

我使用Opencv文档来划定轮廓并获取区域,但没有出现绿色圆圈标记。

出口:

在此处输入图像描述

预期退出: 在此处输入图像描述

更新我能够添加信息的问题,只需要添加圆圈并检查直径是否正确。

标签: pythonimageopencvimage-processing

解决方案


您正在使用单通道图像,但尝试显示 3 通道颜色。添加以下内容:

...
thresh = cv2.imread('IMD016.png',0)
_, contours,hierarchy = cv2.findContours(thresh,2,1)
thresh = cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB)
print (len(contours))
...

OpenCV此外,在混合和PyPlot绘图例程时要格外小心。OpenCV默认使用BGR,而PyPlot使用RGB. 此外,cv2绘图例程不会添加额外的通道,而plt会添加。只需要记住这一点


推荐阅读