实战赢家:为何传统边缘分割方法比深度学习更有效?附源码+教学+数据

本文主要是介绍实战赢家:为何传统边缘分割方法比深度学习更有效?附源码+教学+数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

传统的边缘分割方法,如Canny边缘检测和Sobel算子,已经在计算机视觉领域中使用了数十年。这些方法依赖于图像梯度和边缘强度来识别边缘,通过一系列精心设计的滤波器和阈值化步骤来实现高效的边缘检测。虽然这些方法较为简单,但它们的计算开销低,效果稳定,并且能够在资源有限的环境中实现快速处理。随着技术的发展,这些传统算法不断优化,并与现代技术结合,展现出在特定应用场景中优于深度学习模型的独特优势。

传统的边缘分割方法在计算机视觉的早期阶段就开始发挥关键作用。这些方法以其简洁而有效的处理流程,在许多应用中奠定了基础。最具代表性的传统边缘检测技术包括Canny边缘检测器、Sobel算子和Prewitt算子等。

Canny边缘检测器由John Canny在1986年提出,被广泛认为是经典的边缘检测方法。它通过多阶段的处理流程来提取边缘:首先应用高斯滤波器来平滑图像,减少噪声的影响;接着计算图像的梯度幅值和方向,以检测边缘;然后通过非极大值抑制技术来精确定位边缘,并利用双阈值处理来进一步确认和连接边缘。这种方法由于其精准度高、结果稳定,至今仍在很多实际应用中使用。

Sobel算子Prewitt算子则是基于图像的梯度来检测边缘的经典技术。Sobel算子使用一个卷积核来计算图像在水平和垂直方向上的梯度,从而检测边缘。这些方法的优点在于计算简单、实时性好,并且能够有效地检测到图像中的主要边缘特征。

虽然深度学习方法近年来在许多视觉任务中取得了显著的成功,但传统的边缘分割方法在某些应用场景中依然展示了其独特的优势。这些传统技术不仅计算开销低,适合资源有限的环境,还在处理特定类型的图像时展现出高效性。例如,在噪声较少、对实时性要求高的应用中,传统方法的简单性和高效性使其成为优选方案。此外,传统方法的可解释性强,使得在调试和优化过程中更具优势。

随着技术的发展,传统边缘分割方法也不断得到改进。算法优化和新技术的引入,使得这些方法在现代应用中仍能发挥重要作用。在某些情况下,它们甚至可以与深度学习模型结合,利用其优越的特性来补充深度学习技术的不足,提供更全面的解决方案。因此,传统边缘分割方法在边缘检测领域依然具有不容忽视的价值和竞争力。

深度学习的Hed等边缘分割算法,我之前做过很久,后续可以给大家提供。

我们以裂缝分割来演示

裂缝分割与斜率检测源码

话不多说,先附带源码和原数据

import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd# 读取目标图像和模板图像
target_img = cv2.imread(r"C:\Users\sunhongzhe\Pictures\images\mmexport1723604959151.png")
template_img = cv2.imread(r"C:\Users\sunhongzhe\Pictures\images\Dingtalk_20240814140529.jpg")# 转换为灰度图像
target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template_img, cv2.COLOR_BGR2GRAY)# 获取模板图像的宽度和高度
w, h = template_gray.shape[::-1]# 使用模板匹配
res = cv2.matchTemplate(target_gray, template_gray, cv2.TM_CCOEFF_NORMED)# 设置阈值
threshold = 0.8
loc = np.where(res >= threshold)x1,y1 = 0,0
# 在目标图像上绘制匹配结果
for pt in zip(*loc[::-1]):cv2.rectangle(target_img, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)x1, y1 = pt[1], pt[0]target_roi = target_gray[y1-25:y1+h+75,x1-50:x1+w+50]
# img_with_shapes = target_roi.copy()
img_with_shapes = np.zeros_like(target_roi) + 255blurred = cv2.GaussianBlur(target_roi, (9, 9), 0)
edges = cv2.Canny(blurred, 50, 150)contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)# 提取 x 和 y
filtered_contours = []
threshold_slope = 0.5  # 自定义斜率阈值
for index, cnt in enumerate(contours):C= cv2.arcLength(cnt,False)if C <= 50:continuesegment_length = cnt.shape[0] // 20for cnt_index in range(0,18):if cnt[cnt_index*segment_length][0][0] ==cnt[(cnt_index+1)*segment_length][0][0]: continueslop = abs((((cnt[cnt_index*segment_length][0][1]) -cnt[(cnt_index+1)*segment_length][0][1]) / ((cnt[cnt_index*segment_length][0][0]) -cnt[(cnt_index+1)*segment_length][0][0]))) if slop > threshold_slope:for j in range(cnt_index*segment_length, (cnt_index+1)*segment_length):filtered_contours.append([cnt[j][0][0], cnt[j][0][1]])filtered_contours = np.array(filtered_contours, dtype=np.int32).reshape(-1, 1, 2)
# filtered_points = []
# for index, cnt in enumerate(filtered_contours):
#     for point in cnt:
#         filtered_points.append([[filtered_contours[0][0], filtered_contours[0][1]]])
# filtered_points = np.array(filtered_points)
filtered_contours = filtered_contours[np.argsort(filtered_contours[:,0, 0])]
x = filtered_contours[:,0, 0]
y = filtered_contours[:,0, 1]# 拟合多项式曲线(这里使用二次多项式)
coefficients = np.polyfit(x, y, 3)
polynomial = np.poly1d(coefficients)# 生成拟合曲线的 x 值
# x_fit = np.linspace(np.min(x), np.max(x), 5000)
y_fit = polynomial(x).clip(y.min())
# y_fit = polynomial(x).clip(y.min())def remove_anomalies(points, threshold=100, threshold_2=10):  # 第一个参数是剔除掉距离拟合曲线上远一些的一群点;# 第二个参数是剔除掉距离前几个sorted_points = points[np.argsort(points[:,0, 0])]x = sorted_points[:,0, 0]y = sorted_points[:,0, 1]# 拟合多项式曲线(这里使用二次多项式)coefficients = np.polyfit(x, y, 3)polynomial = np.poly1d(coefficients)# 生成拟合曲线的 x 值filtered_points = []y_fit = polynomial(x).clip(y.min())last_x = -1for index, x_val in enumerate(sorted_points):# 计算当前 x 值在拟合曲线上的 y 值y_fit_val = int(y_fit[index])# 获取当前 x 值的所有 y 值y_vals = sorted_points[sorted_points[:,0, 0] == x_val[0][0]]if len(y_vals) > 0:# 找到距离拟合 y 值最近的实际 y 值distances = np.abs(y_vals[:,0,0] - y_fit_val)nearest_y = y_vals[np.argmin(distances)][0][1]if (abs(nearest_y - y_fit_val) > threshold): continueif abs(nearest_y - np.mean(y[index-3:index+3])) >= threshold_2: continueif last_x != x_val[0][0]:  filtered_points.append([[int(sorted_points[index][0][0]), nearest_y]])last_x = x_val[0][0]filtered_points = np.array(filtered_points)result_points = []            for index, x_val in enumerate(filtered_points): # 斜率同向计算,点x和x-1的斜率应与x-1和x-2同向 保持单调x = filtered_points[:,0, 0]y = filtered_points[:,0, 1]if index > 2:slope_curr = (y[index] - y[index-1]) / (x[index] - x[index-1])slope_prev = (y[index-1] - y[index-2]) / (x[index-1] - x[index-2])if np.sign(slope_curr) == np.sign(slope_prev):result_points.append([[int(filtered_points[index][0][0]), filtered_points[index][0][1]]])result_points = np.array(result_points)return result_pointsfiltered_points = remove_anomalies(filtered_contours)
result_img = np.ones_like(img_with_shapes) * 255
cv2.drawContours(result_img, filtered_points, -1, 0, 2)data = {'左边缘': [], '右边缘': []}# 计算并显示斜率
def compute_and_display_slopes(img, points, interval=5):result_img_ = np.copy(img)for i in range(0, len(points) - interval, interval):  p1 = points[i][0]p2 = points[i + 2][0]  # 间隔2点取斜率# 计算斜率if p2[0] != p1[0]:slope = -(p2[1] - p1[1]) / (p2[0] - p1[0])else:slope = float('inf')  # 垂直线的斜率# 在图像上标记斜率midpoint = (p2[0], p2[1])midpoint = (int(midpoint[0]), int(midpoint[1]))  # 确保midpoint是整数cv2.putText(result_img_, f"{slope:.2f}", midpoint, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 1, cv2.LINE_AA)cv2.putText(result_img, f"{slope:.2f}", midpoint, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 1, cv2.LINE_AA)flag = Truefor i in range(0, len(points)-2):p1 = points[i][0]p2 = points[i + 2][0]if p2[0] != p1[0]:slope_ = -(p2[1] - p1[1]) / (p2[0] - p1[0])else:slope_ = float('inf')  # 垂直线的斜率# 将斜率按规则添加到对应列if slope_ < 0:data['左边缘'].append(slope_)# data['右边缘'].append(None)  # 填充 None 表示空值else:# data['左边缘'].append(None)  # 填充 None 表示空值data['右边缘'].append(slope_)# if flag and points[i ][0][1] - points[i+1][0][1] > 1: #     flag = False#     continuecv2.line(result_img, tuple(points[i][0]), tuple(points[i + 1][0]), 0, 2)cv2.line(result_img_, tuple(points[i][0]), tuple(points[i + 1][0]), 0, 2)return result_img_# 计算并绘制斜率
result_img_ = compute_and_display_slopes(target_roi, filtered_points)
# 创建 DataFrame
data['右边缘'] = data['右边缘'][::-1]
# 找出每列的最大长度
max_length = max(len(data['左边缘']), len(data['右边缘']))# 填充较短的列
data['左边缘'].extend([None] * (max_length - len(data['左边缘'])))
data['右边缘'].extend([None] * (max_length - len(data['右边缘'])))
df = pd.DataFrame(data)# 保存到 Excel 文件
df.to_excel('slopes.xlsx', index=False)plt.figure(figsize=(18, 8))plt.subplot(1, 3, 1)
plt.title('Original Points')
plt.imshow(target_roi, cmap='gray')# plt.subplot(1, 3, 2)# # 绘制散点图和拟合曲线
# plt.scatter(x, 800-y, color='blue', label='Data points')
# plt.plot(x, 800-y_fit, color='red', label='Fitted curve')
# plt.xlabel('X')
# plt.ylabel('Y')
# plt.title('Scatter Points and Fitted Curve')
# plt.legend()plt.subplot(1, 3,3)
plt.title('Convex Hull')
plt.imshow(result_img, cmap='gray')plt.subplot(1, 3, 2)
plt.title('Convex Hull')
plt.imshow(result_img_, cmap='gray')
plt.savefig("Gradient.png")
plt.show()

数据

下面将两张图放进去,改改前面几行的路径即可,第一张对应第一个路径

使用模板匹配找出预定区域,这个方法比较简单,后续咱们用不需要模板匹配的实现,因为用匹配的比较鲁棒,在几百张图里准确率高不少。

然后我们用多项式拟合与梯度阈值过滤

def remove_anomalies(points, threshold=100, threshold_2=10):  # 第一个参数是剔除掉距离拟合曲线上远一些的一群点;# 第二个参数是剔除掉距离前几个sorted_points = points[np.argsort(points[:,0, 0])]x = sorted_points[:,0, 0]y = sorted_points[:,0, 1]# 拟合多项式曲线(这里使用二次多项式)coefficients = np.polyfit(x, y, 3)polynomial = np.poly1d(coefficients)# 生成拟合曲线的 x 值filtered_points = []y_fit = polynomial(x).clip(y.min())last_x = -1for index, x_val in enumerate(sorted_points):# 计算当前 x 值在拟合曲线上的 y 值y_fit_val = int(y_fit[index])# 获取当前 x 值的所有 y 值y_vals = sorted_points[sorted_points[:,0, 0] == x_val[0][0]]if len(y_vals) > 0:# 找到距离拟合 y 值最近的实际 y 值distances = np.abs(y_vals[:,0,0] - y_fit_val)nearest_y = y_vals[np.argmin(distances)][0][1]if (abs(nearest_y - y_fit_val) > threshold): continueif abs(nearest_y - np.mean(y[index-3:index+3])) >= threshold_2: continueif last_x != x_val[0][0]:  filtered_points.append([[int(sorted_points[index][0][0]), nearest_y]])last_x = x_val[0][0]filtered_points = np.array(filtered_points)result_points = []            for index, x_val in enumerate(filtered_points): # 斜率同向计算,点x和x-1的斜率应与x-1和x-2同向 保持单调x = filtered_points[:,0, 0]y = filtered_points[:,0, 1]if index > 2:slope_curr = (y[index] - y[index-1]) / (x[index] - x[index-1])slope_prev = (y[index-1] - y[index-2]) / (x[index-1] - x[index-2])if np.sign(slope_curr) == np.sign(slope_prev):result_points.append([[int(filtered_points[index][0][0]), filtered_points[index][0][1]]])result_points = np.array(result_points)return result_points

最后我们计算并显示图像

# 计算并显示斜率
def compute_and_display_slopes(img, points, interval=5):result_img_ = np.copy(img)for i in range(0, len(points) - interval, interval):  p1 = points[i][0]p2 = points[i + 2][0]  # 间隔2点取斜率# 计算斜率if p2[0] != p1[0]:slope = -(p2[1] - p1[1]) / (p2[0] - p1[0])else:slope = float('inf')  # 垂直线的斜率# 在图像上标记斜率midpoint = (p2[0], p2[1])midpoint = (int(midpoint[0]), int(midpoint[1]))  # 确保midpoint是整数cv2.putText(result_img_, f"{slope:.2f}", midpoint, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 1, cv2.LINE_AA)cv2.putText(result_img, f"{slope:.2f}", midpoint, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 1, cv2.LINE_AA)flag = Truefor i in range(0, len(points)-2):p1 = points[i][0]p2 = points[i + 2][0]if p2[0] != p1[0]:slope_ = -(p2[1] - p1[1]) / (p2[0] - p1[0])else:slope_ = float('inf')  # 垂直线的斜率# 将斜率按规则添加到对应列if slope_ < 0:data['左边缘'].append(slope_)# data['右边缘'].append(None)  # 填充 None 表示空值else:# data['左边缘'].append(None)  # 填充 None 表示空值data['右边缘'].append(slope_)# if flag and points[i ][0][1] - points[i+1][0][1] > 1: #     flag = False#     continuecv2.line(result_img, tuple(points[i][0]), tuple(points[i + 1][0]), 0, 2)cv2.line(result_img_, tuple(points[i][0]), tuple(points[i + 1][0]), 0, 2)return result_img_

就得到了下图,可以正确地分割出裂缝,又可以得到每个区域的斜率,美哉。

总结

这是裂缝实验的实践,后续给大家带来AI的Hed网络。传统方法不需要训练,简单实现即可,ai需要大规模样本,还是差点意思。小样本里传统方法好使,还不用训练资源,还不用标注数据。

这篇关于实战赢家:为何传统边缘分割方法比深度学习更有效?附源码+教学+数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1137245

相关文章

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

从原理到实战深入理解Java 断言assert

《从原理到实战深入理解Java断言assert》本文深入解析Java断言机制,涵盖语法、工作原理、启用方式及与异常的区别,推荐用于开发阶段的条件检查与状态验证,并强调生产环境应使用参数验证工具类替代... 目录深入理解 Java 断言(assert):从原理到实战引言:为什么需要断言?一、断言基础1.1 语

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1