Python Opencv实践 - 轮廓特征(最小外接圆,椭圆拟合)

复制代码
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中心旋转角度
    #参考资料: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])

相关推荐
Heartoxx几秒前
c语言-指针与一维数组
c语言·开发语言·算法
hqxstudying2 分钟前
Java创建型模式---原型模式
java·开发语言·设计模式·代码规范
charlie11451419118 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
孤狼warrior20 分钟前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹25 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金1 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
zdw2 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python