python opencv之提取轮廓并拟合圆

图片存储地址为:C:\Users\Pictures\test.png,该图像图片背景是黑色的,目标区域是亮的,目标区域是两段圆弧和两段曲线构成的封闭区域,其中两段圆弧属于同一个圆,但在目标区域的相对位置,也就是不是相邻的,现在用python+opencv提取轮廓并拟合圆弧的圆心和半径。

1、拟合所有圆弧

python 复制代码
import cv2
import numpy as np
​
# 读取图像
image_path = r'C:\Users\Pictures\test.png'
image = cv2.imread(image_path)
​
# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
​
# 对图像进行二值化处理
_, threshold_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
​
# 查找图像轮廓
contours, _ = cv2.findContours(threshold_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
​
# 迭代所有轮廓
for contour in contours:
    # 拟合轮廓为圆弧(仅拟合最小外接圆)
    (x, y), radius = cv2.minEnclosingCircle(contour)
​
    # 绘制圆弧
    cv2.circle(image, (int(x), int(y)), int(radius), (0, 255, 0), 2)
​
# 显示结果图像
cv2.imshow('Detected Arcs', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

2、拟合最大圆弧

python 复制代码
import cv2
import numpy as np
​
# 读取图像
image_path = r'C:\Users\Pictures\test.png'
image = cv2.imread(image_path)
​
# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
​
# 对图像进行二值化处理
_, threshold_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
​
# 查找图像轮廓
contours, _ = cv2.findContours(threshold_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
​
max_radius = 0
max_circle_center = None
​
# 迭代所有轮廓
for contour in contours:
    # 拟合轮廓为圆弧(仅拟合最小外接圆)
    (x, y), radius = cv2.minEnclosingCircle(contour)
​
    if radius > max_radius:
        max_radius = radius
        max_circle_center = (int(x), int(y))
​
# 绘制最大半径的圆
cv2.circle(image, max_circle_center, int(max_radius), (0, 255, 0), 2)
​
# 在图像上标注圆心和直径
cv2.putText(image, f"Center: {max_circle_center}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.putText(image, f"Diameter: {2 * max_radius}", (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
​
# 显示结果图像
cv2.imshow('Detected Arcs', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
相关推荐
newxtc1 分钟前
【JJ斗地主-注册安全分析报告】
开发语言·javascript·人工智能·安全
程序猿小D11 分钟前
第22节 Node.js JXcore 打包
开发语言·人工智能·vscode·node.js·c#
花果山总钻风15 分钟前
SQLAlchemy 中的 func 函数使用指南
python
小猫咪怎么会有坏心思呢18 分钟前
华为OD机试-最短木板长度-二分法(A卷,100分)
java·开发语言·华为od
wo32586614524 分钟前
浪潮交换机配置track检测实现高速公路收费网络主备切换NQA
开发语言·网络·php
知识中的海王28 分钟前
Python html 库用法详解
开发语言·python
面朝大海,春不暖,花不开1 小时前
使用 Python 正则表达式实现文本替换与电话号码规范化
python·mysql·正则表达式
淘小白_TXB21961 小时前
Python网页自动化Selenium中文文档
python·selenium·自动化·网页自动化
獨枭1 小时前
配置 macOS 上的 Ruby 开发环境
开发语言·macos·ruby
飞由于度1 小时前
C#中清空DataGridView的方法
开发语言·c#