前言:本文适合急用边缘检测的读者,不需要学习原理直接用代码。详细原理参见下面的文章,我只讲使用过程中需要注意的地方。
一、流程
首先,无脑导入model.yml文件,链接如下:https://pan.baidu.com/s/1jffq9oXNXmsKGtFJu2VzYw
提取码:z2t4
接着,复制以下代码,只修改文件路径,然后就能运行
img = cv2.imread(file)
print("正在处理边界")
edgeDetector = cv2.ximgproc.createStructuredEdgeDetection("model.yml")
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
edges = edgeDetector.detectEdges(np.float32(src) / 255.0)
cv2.imshow("edges", edges)
cv2.imwrite(file, edges * 255)
cv2.waitKey(0)
# cv2.ximgproc.structuredDection.edgesNms()
其中,file更换成你的图片路径。
二、注意点
1.我的原图是灰度图,如果你也是,注意!!!第四行代码src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)这一块,一定不要修改,否则就报错:
Traceback (most recent call last):
File "F:\pythonProjects\Ice_Motion_Forecast\codes\opticalFlow\edgeDetection.py", line 28, in <module>
edges = edgeDetector.detectEdges(np.float32(src) / 255.0)
cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv_contrib\modules\ximgproc\src\structured_edge_detection.cpp:537: error: (-215:Assertion failed) _src.type() == CV_32FC3 in function 'cv::ximgproc::StructuredEdgeDetectionImpl::detectEdges'
这是因为第五行代码detectEdges函数,必须输入RGB格式图像,第四行代码就是将灰度图先转成RGB。
2.如果是下面这玩意报错
cv2.ximgproc.createStructuredEdgeDetection,就是你需要添加一个新的库叫:opencv-contrib-python,直接pip install opencv-contrib-python,或者PyCharm中setting添加这个库。
三、最终结果
四、好人做到底
如果你要批量提取图像边缘,循环我都给你写好了,如果对你有帮助,请在评论区扣666
import cv2
import numpy as np
import os
def edgeDetection(file, savepath):
img = cv2.imread(file)
print("正在处理" + file[-17:-4] + "的边界") # file[-17:-4]是提取我文件名的,你改成自己的
edgeDetector = cv2.ximgproc.createStructuredEdgeDetection("model.yml")
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
edges = edgeDetector.detectEdges(np.float32(src) / 255.0)
# cv2.namedWindow("edges", 0)
# cv2.imshow("edges", edges)
cv2.imwrite(savepath + file[-17:-4] + '.png', edges * 255)
# cv2.waitKey(0)
# cv2.ximgproc.structuredDection.edgesNms()
if __name__ == '__main__':
path = '自己改'
savePath = '自己改'
for root, dirs, files in os.walk(path):
for file in files:
print(file)
edgeDetection(path+file, savePath)