
视觉/图像重磅干货,第一时间送达
导 读
本文主要介绍基于OpenCV实现钢材表面划痕检测,并给详细步骤和代码。
背景介绍
实例图片来源于网络,目标是提取图中的划痕。

本文实现效果如下:

实现步骤
【1】灰度转换 +自适应二值化
# load image
img = cv2.imread('src.jpg')
# convert to grayscale
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)