检测思路

① 原图均值滤波

② 滤波图像与原图进行差分

③ 二值化

④ 查找轮廓(根据轮廓长度进行筛选)

代码

import cv2
import numpy as np

print(cv2.__version__)
minThres = 6

# 读取图像1
img1 = cv2.imread('C:\\Users\\PC\\Desktop\\surface_scratch.png')
img2 = cv2.imread('C:\\Users\\PC\\Desktop\\surface_scratch.png')

# 中值滤波
img1 = cv2.medianBlur(img1, 15)

# 图像差分
diff = cv2.absdiff(img1, img2)
cv2.imshow('diff', diff)  # 结果图

gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
# 二值化
_, thres = cv2.threshold(gray, minThres, 255, cv2.THRESH_BINARY)
cv2.imshow('thres', thres)

# 查找轮廓
contours, hierarchy = cv2.findContours(thres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 输出轮廓个数
print(len(contours))

for i in range(0, len(contours)):
    length = cv2.arcLength(contours[i], True)
    # 通过轮廓长度筛选
    if length > 30:
        cv2.drawContours(img2, contours[i], -1, (0, 0, 255), 2)

cv2.imshow('result', img2)  # 结果图
cv2.waitKey(0)
cv2.destroyAllWindows()

效果

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐