基于OPENCV的任意多边形最大内切圆和最小外接圆

提取关键点cv2.findContours(),其次+闭运算+高斯模糊平滑就完美解决了个搞了好久,网络上的大佬们的代码我真的基本都试试完了,但是还是会有各种各样的情况,最终我选择的是干货 | OpenCV获取不规则区域的最大内切圆(附Python / C++ 源码)-腾讯云开发者社区-腾讯云这位大佬的代码基础上改进的,因为不知道为啥他老人家代码看着非常合理,但是在我电脑运行起来就会乱七八糟,但是还是给我极大帮助,下一篇就专门写文章给考虑这个大佬代码的兄弟们一点我遇到的问题以及解决方案。废话不多说看我的代码吧,这里是在他的基础上改好的

本代码解读:(python)

1.最小外接圆是直接通过cv2.minEnclosingCircle() 函数实现

这个函数可以计算给定轮廓的最小外接圆的圆心坐标和半径。具体而言,它接受一个轮廓作为输入,并返回一个元组,其中包含最小外接圆的圆心坐标 (x, y) 和半径 radius

下面是对 cv2.minEnclosingCircle() 函数的调用示例:

(x, y), min_enclosing_radius = cv2.minEnclosingCircle(contour)

其中 contour 是输入的轮廓。调用后,(x, y) 表示最小外接圆的圆心坐标,min_enclosing_radius 表示最小外接圆的半径。

2.最大内切圆理论上也有这样的代码例如https://www.cnblogs.com/01black-white/p/16289830.html

这个up主写的,但是我没能成功复现,感兴趣的可以自己试试。

所以最终我使用的方法是这样的提取关键点cv2.findContours(),其次+闭运算+高斯模糊平滑+二值化 + 轮廓提取 + 填充绘制+距离变换(获取距离变换结果最大值及其坐标)就完美解决了

最终效果图还算不错是这样的(蓝色线是我用来输出轮廓的,这次的代码没有,我放下次文章里面)

通过上述我说的方法最终我们可以得到一个可以绘制出任意多边形的内切圆外接圆。

完整代码如下

需要注意的是src = cv2.imread('D:/WORK/PY/edge_processing(2)/train/screenshot2.jpg')这个是你需要检测的图片位置,其他文件都是自动生成的。

import os
import cv2
import numpy as np

# 读取图像并缩小尺寸
src = cv2.imread('D:/WORK/PY/edge_processing(2)/train/screenshot2.jpg')
src_resized = cv2.resize(src, (800, 600))  # 将图像缩小到800x600

# 显示原始图像
cv2.imshow('src', src_resized)

# 将图像转换为灰度图像并进行阈值处理
gray = cv2.cvtColor(src_resized, cv2.COLOR_BGR2GRAY)
gray[gray > 127] = 255
cv2.imshow('thres', gray)

# 使用 Canny 边缘检测获取更多的边缘信息
edges = cv2.Canny(gray, 50, 150)
cv2.imshow('edges', edges)

# 闭运算
kernel = np.ones((5, 5), np.uint8)
closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closed', closed)

# 使用高斯模糊平滑 mask
smoothed = cv2.GaussianBlur(closed, (5, 5), 0)

# 寻找轮廓并创建掩膜
contours, _ = cv2.findContours(smoothed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 轮廓近似
epsilon = 0.02 * cv2.arcLength(contours[0], True)  # 调整 epsilon 的值
approx = cv2.approxPolyDP(contours[0], epsilon, True)

mask = np.zeros(gray.shape, np.uint8)
cv2.drawContours(mask, [approx], 0, (255, 255, 255), -1)
cv2.imshow('mask', mask)

# 计算距离变换并将结果转换为灰度图像
dt = cv2.distanceTransform(mask, cv2.DIST_L2, 5, cv2.DIST_LABEL_PIXEL)
transImg = cv2.convertScaleAbs(dt)
cv2.normalize(transImg, transImg, 0, 255, cv2.NORM_MINMAX)
cv2.imshow("distanceTransform", transImg)

# 寻找最大内接圆
_, max_val, _, max_loc = cv2.minMaxLoc(dt)
radius = int(max_val)

# 调整半径以确保不超出图像边界
max_radius = min(radius, min(src_resized.shape[0], src_resized.shape[1]) // 2)

# 在原始图像上画出最大内接圆
max_loc = (int(max_loc[0]), int(max_loc[1]))  # 将 max_loc 中的浮点数值转换为整数值
cv2.circle(src_resized, max_loc, max_radius, (0, 0, 255), 2)

# 绘制最小外接圆并保存相关数据
(x, y), min_enclosing_radius = cv2.minEnclosingCircle(approx)
min_enclosing_center = (int(x), int(y))
min_enclosing_radius = int(min_enclosing_radius)
cv2.circle(src_resized, min_enclosing_center, min_enclosing_radius, (0, 255, 0), 2)

# 保存带轮廓的图像
result_dir = 'result'
if not os.path.exists(result_dir):
    os.makedirs(result_dir)
photo_dir = os.path.join(result_dir, 'photo')
if not os.path.exists(photo_dir):
    os.makedirs(photo_dir)
index = len(os.listdir(photo_dir)) + 1
cv2.imwrite(os.path.join(photo_dir, 'screenshot{}.jpg'.format(index)), src_resized)

# 保存数据至文件
file_dir = os.path.join(result_dir, 'file')
if not os.path.exists(file_dir):
    os.makedirs(file_dir)
data_file_path = os.path.join(file_dir, 'data{}.txt'.format(index))
with open(data_file_path, 'w') as file:
    file.write("Min Enclosing Circle Center(最小外接圆圆心): {}\n".format(min_enclosing_center))
    file.write("Min Enclosing Circle Radius(最小外接圆半径): {}\n".format(min_enclosing_radius))
    file.write("Max Inscribed Circle Center(最大内接圆圆心): {}\n".format(max_loc))
    file.write("Max Inscribed Circle Radius(最大内接圆半径): {}\n".format(max_radius))

cv2.imshow('result', src_resized)

cv2.waitKey(0)
cv2.destroyAllWindows()

有问题可以给我留言我会看的。

  • 16
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值