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

相关推荐
xiaohouzi1122333 小时前
OpenCV的cv2.VideoCapture如何加GStreamer后端
人工智能·opencv·计算机视觉
用户8356290780513 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下3 小时前
最终的信号类
开发语言·c++·算法
小关会打代码3 小时前
计算机视觉案例分享之答题卡识别
人工智能·计算机视觉
c8i3 小时前
python中类的基本结构、特殊属性于MRO理解
python
天天进步20154 小时前
用Python打造专业级老照片修复工具:让时光倒流的数字魔法
人工智能·计算机视觉
echoarts4 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05064 小时前
【ESP32-CAM】HELLO WORLD
python
荼蘼4 小时前
答题卡识别改分项目
人工智能·opencv·计算机视觉
Aomnitrix4 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式