如何使用opencv-python标记中心并计算图像的直径?

时间:2018-11-13 18:32:31

标签: python image opencv image-processing

我正在研究中心的识别和图像渲染。我正在使用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文档对轮廓进行了划分并获得了区域,但是没有出现绿色的圆圈标记。

退出:

enter image description here

预期出口: enter image description here

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

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题