简体   繁体   中英

How to mark the center and calculate the diameter of an image using opencv - python?

I am working on the recognition of the center and the image rendering. I'm using cv2.findContours to delimit the edges of the image of interest. And using cv.minEnclosingCircle (cnt) to circumnavigate my region of interest. The code below I can identify the center of each ROI, but I am not able to mark in the output of the image the circle corresponding to the image that I want to calculate and also I want to mark with a pqno point the exact location where the algorithm identified the center.

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()

I used the Opencv documentation to demarcate the contours and get the regions, but the green circle mark does not appear.

Exit:

在此处输入图片说明

Exit expected: 在此处输入图片说明

updating the question I was able to add the information, it's only necessary to add the circle and check if the diameter is correct.

You are using a single channel image, but trying to show 3-channel color. Add the following:

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

Also, be extra careful when mixing the OpenCV and PyPlot drawing routines. OpenCV uses BGR by default, while PyPlot uses RGB . Also, cv2 drawing routines don't add extra channels, while the plt does. Just need to keep that in mind

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM