![](/img/trans.png)
[英]How to calculate the diameter of irregular shape from jpg input image in Python?
[英]How to mark the center and calculate the diameter of an image using 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文檔來划定輪廓並獲取區域,但是沒有出現綠色圓圈標記。
出口:
更新了我可以添加信息的問題,只需添加圓並檢查直徑是否正確。
您使用的是單通道圖像,但是試圖顯示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
會添加額外的通道。 只需要記住這一點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.