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

相关推荐
以卿a7 分钟前
C++ 模板初阶
开发语言·c++
s:10311 分钟前
【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
java·开发语言
道不尽世间的沧桑1 小时前
第17篇:网络请求与Axios集成
开发语言·前端·javascript
久绊A1 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J5 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
软件黑马王子5 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
莫忘初心丶5 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
闲猫5 小时前
go orm GORM
开发语言·后端·golang
李白同学6 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?7 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash