OpenCV实现钢材表面划痕检测

项目来源:https://mp.weixin.qq.com/s/AUZIBjqzFJhU1WfZf2_LMw

主要学习点:去燥 + 霍夫直线检测

 

项目目标: 提取下图中的划痕,并对划痕作标记:

需要实现效果如下:

 【1】灰度转换 +自适应二值化

img = cv2.imread('src.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 自适应阈值 adaptive threshold 
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, -35)
cv2.imwrite('thres.jpg',thresh)

【2】形态学闭运算 + 开运算,去除噪点干扰(注意核大小)

# apply morphology
kernel = np.ones((3,30),np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((3,35),np.uint8)
morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)

【3】霍夫直线检测 + 绘制结果

# get hough line segments
threshold = 25
minLineLength = 10
maxLineGap = 20
lines = cv2.HoughLinesP(morph, 1, 30*np.pi/360, threshold, minLineLength, maxLineGap)

# draw lines
linear1 = np.zeros_like(thresh)
linear2 = img.copy()
for [line] in lines:
    x1 = line[0]
    y1 = line[1]
    x2 = line[2]
    y2 = line[3]
    cv2.line(linear1, (x1,y1), (x2,y2), 255, 1)
    cv2.line(linear2, (x1,y1), (x2,y2), (0,0,255), 1)

 

posted @ 2024-05-08 11:28  南极山  阅读(101)  评论(0)    收藏  举报