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

相关推荐
m0_662577974 分钟前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
Elnaij5 分钟前
从C++开始的编程生活(20)——AVL树
开发语言·c++
似水明俊德8 分钟前
12-C#
开发语言·数据库·oracle·c#
hanbr8 分钟前
【C++ STL核心】vector:最常用的动态数组容器(第九天核心)
开发语言·c++
菜鸟‍1 小时前
【后端项目】苍穹外卖day01-开发环境搭建
java·开发语言·spring boot
青槿吖1 小时前
【保姆级教程】Spring事务控制通关指南:XML+注解双版本,避坑指南全奉上
xml·java·开发语言·数据库·sql·spring·mybatis
Yungoal1 小时前
B/S和C/S架构在服务端接收请求
c语言·开发语言·架构
niceffking2 小时前
C++内部类的ISO约定和语法细节
开发语言·c++
2501_921649492 小时前
美股历史 K线数据 API接口综合评测与接入指南
后端·python·websocket·金融·restful