OpenCV检测圆形东西是否存在缺口?

文章目录


前言

想了挺久,一直没解决这个问题。后面勉强解决了。


一、试过的方法

1.想用圆度来解决,后来发现圆度差值很小,完整的圆圆度0.89,然后有缺角的圆圆度0.88。

2.想用面积来解决,但是图片中每个圆大小不是一致的,是有一些差别的,也没办法。

3.多边形拟合、凸包都不合适。

4.想使用角点的数量来确定,发现也是不行。看下图

二、最终使用的方法

1.先极坐标变换

代码如下(示例):

python 复制代码
import cv2
import os

# 设置文件夹路径
folder_path = r"E:\VSCODE_PY\CAPCode\Posong\cap_2"

# 遍历文件夹中的图像文件
for file_name in os.listdir(folder_path):
    if file_name.endswith(".jpg"):
        # 读取图像并转换为灰度图像
        image_path = os.path.join(folder_path, file_name)
        image = cv2.imread(image_path)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 进行极坐标变换
        polar_image = cv2.linearPolar(gray, (gray.shape[1]//2, gray.shape[0]//2), gray.shape[1]//2+10, cv2.WARP_FILL_OUTLIERS)

        # 进行边缘检测
        edges = cv2.Canny(polar_image, 50, 150)

        # 保存处理后的图像
        output_path = os.path.join(folder_path, "polar_" + file_name)
        cv2.imwrite(output_path, polar_image)

极坐标的中心点可以根据实际情况设置一下。

2.计算斜率

代码如下(示例):

python 复制代码
import os
import cv2
import numpy as np

# 设置最小间距阈值
min_distance = 10

# 遍历cap_8文件夹内的所有图片
for filename in os.listdir(r'E:\VSCODE_PY\CAPCode\Posong\cap_8'):
    if filename.endswith('.jpg'):
        # 读取图像并进行灰度化处理
        image = cv2.imread(os.path.join(r'E:\VSCODE_PY\CAPCode\Posong\cap_8', filename))
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 进行边缘检测
        edges = cv2.Canny(gray, 50, 150)

        # 查找轮廓
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # 创建一个空白图像,用于绘制轮廓
        contour_image = np.zeros_like(image)

        # 绘制轮廓
        cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)

        # 查找角点
        corners = cv2.cornerHarris(gray, 2, 3, 0.04)

        # 标记角点
        threshold = 0.45 * corners.max()  # 调整阈值
        corners = cv2.dilate(corners, None)
        image[corners > threshold] = [0, 0, 255]

        # 计算任意两个角点之间的斜率
        corner_points = np.argwhere(corners > threshold)
        slopes = []
        for i in range(len(corner_points)):
            for j in range(i+1, len(corner_points)):
                x1, y1 = corner_points[i]
                x2, y2 = corner_points[j]
                distance = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
                if distance >= min_distance:
                    if x2 - x1 == 0:
                        slope = float('inf')
                    else:
                        slope = (y2 - y1) / (x2 - x1)
                    slopes.append(slope)

        # 处理无穷大和无穷小的情况
        slopes = [slope for slope in slopes if slope != float('inf') and slope != float('-inf')]
        slopes.sort()

        # 输出最大斜率和最小斜率的绝对值
        if len(slopes) >= 2:
            max_slope = max(abs(slopes[-2]), abs(slopes[1]))
            min_slope = min(abs(slopes[-2]), abs(slopes[1]))
        else:
            max_slope = float('-inf')
            min_slope = float('inf')

        print("图片{}的最大斜率的绝对值:".format(filename), max_slope)
        print("图片{}的最小斜率的绝对值:".format(filename), min_slope)

        # 显示结果
        cv2.imshow('Contours with Corners', image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

角点稍微多,要先设置一下任意2个角点的斜率必须大于最小间距。

这样可以求出每一张图片的斜率绝对值最大和最小值,即看下凸起部分是不是影响到了曲线的斜率。


总结

完成。

相关推荐
Chuck.li5 分钟前
AI 长篇创作工具选型:工作流对照与自测清单
人工智能·大模型·ai写作·网文作者·ai网文·豆包写作
aleimu17 分钟前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
SwanArc技术笔记31 分钟前
读技术文档,先用哪个 AI?模型指南筛选与 GPT-6.2 Astra 实操
人工智能
深海鱼在掘金32 分钟前
深入浅出RAG——第21章:回顾与展望
人工智能
羲云网络34 分钟前
GPT Image 2.6 GIF 交付排障:上线后为什么只剩第一帧?
图像处理·人工智能·前端开发·gif
安爹前沿AI41 分钟前
Seedance 有个文档里没写的参数:开了码率涨 3.9 倍,费用一分没多
人工智能
深海鱼在掘金43 分钟前
深入浅出RAG——第20章:端到端实战:企业级知识库问答系统
人工智能
黑十44 分钟前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
樊小肆1 小时前
agent 不报错才最吓人:自研编码工具半年,我踩了 10 个"看着正常"的运行时坑
前端·人工智能·agent
用户986023965611 小时前
Gemini Tool Retrieval:工具越来越多,Agent 如何按需读取参数说明?
人工智能