import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread("../SampleImages/stars.PNG")
plt.imshow(img[:,:,::-1])
#輪廓檢測
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(img_gray, 127, 255, 0)
contours,hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
#顯示輪廓
img_contours = img.copy()
img_contours = cv.drawContours(img_contours, contours, -1, (0,255,0), 2)
plt.imshow(img_contours, cmap=plt.cm.gray)
for contour in contours:
#輪廓最小外接圓
#(x,y),radius = cv.minEnclosingCircle(cnt)
#cnt: 輪廓信息
#(x,y):最小外接圓的圓心
#radius: 最小外接圓的半徑
#參考資料:https://geek-docs.com/opencv/python-opencv/t_how-to-find-the-minimum-enclosing-circle-of-an-object-in-opencv-python.html
(x,y),radius = cv.minEnclosingCircle(contour)
center = (int(x), int(y))
radius = int(radius)
cv.circle(img, center, radius, (0,255,0), 2)
#橢圓擬合
#ellips = cv.fitEllipse(cnt)
#ellipse: 橢圓信息((x,y),(a,b),angle) (x,y)橢圓中心點;(a,b) 橢圓長短軸的直徑(注意:非半徑);angle中心旋轉(zhuǎn)角度
#參考資料:https://blog.csdn.net/Other_stone/article/details/111186254?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-5-111186254-blog-111409635.235%5Ev38%5Epc_relevant_default_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-5-111186254-blog-111409635.235%5Ev38%5Epc_relevant_default_base&utm_relevant_index=10
ellipse = cv.fitEllipse(contour)
cv.ellipse(img, ellipse, (0,0,255), 2)
plt.imshow(img[:,:,::-1])
?
文章來源:http://www.zghlxwxcb.cn/news/detail-705071.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-705071.html
到了這里,關于Python Opencv實踐 - 輪廓特征(最小外接圓,橢圓擬合)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!