├── detaction.py └── detaction.rar /detaction.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import cv2 3 | import numpy as np 4 | 5 | img = cv2.imread("E://eraser.jpg",1) 6 | 7 | kernel0 = np.ones((2,1),np.uint8) 8 | kernel = np.ones((1,4),np.uint8) 9 | 10 | img1 = cv2.GaussianBlur(img,(5,5),0) 11 | 12 | opening_img = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)#待处理边缘 13 | 14 | #cv2.imshow("img",img1) 15 | canny_img = cv2.Canny(opening_img,50,150) 16 | 17 | lines=cv2.HoughLinesP(canny_img, 1, np.pi/180,15,0,0) 18 | #for i in range(len(lines)-1): 19 | # for x1,y1,x2,y2 in lines[i]: 20 | # cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2) 21 | 22 | #缺陷检测 23 | ret, thresh = cv2.threshold(canny_img, 127, 255,0) 24 | contours,hierarchy = cv2.findContours(thresh,2,1) 25 | cnt = contours[0] 26 | hull = cv2.convexHull(cnt,returnPoints = False) 27 | defects = cv2.convexityDefects(cnt,hull) 28 | for i in range(defects.shape[0]-1): 29 | 30 | s,e,f,d = defects[i,0] 31 | start = tuple(cnt[s][0]) 32 | end = tuple(cnt[e][0]) 33 | x1,y1 = cnt[s][0] 34 | x2,y2 = cnt[e][0] 35 | x3,y3 = cnt[s-1][0] 36 | x4,y4 = cnt[e-1][0] 37 | 38 | if (abs(x1-x3) <= 20 or abs(x2 - x4) <= 20): 39 | s = s + 1 40 | e = e + 1 41 | cv2.rectangle(img,((int)(x1+20),(int)(y1+20)),((int)(x2-20),(int)(y2-20)),(0,255,0),2) 42 | 43 | img_crop = img [(int)(y2-20) : (int)(y1+20),(int)(x2-20):(int)(x1+20)]#缺陷处放大 44 | img_bigger = cv2.resize(img_crop, (0, 0), fx=3, fy=3, 45 | interpolation=cv2.INTER_NEAREST) 46 | 47 | 48 | cv2.imshow("img_output",img) 49 | #cv2.imshow('crop_img.jpg', img_crop) 50 | cv2.imshow("img_bigger",img_bigger) 51 | 52 | cv2.waitKey() 53 | cv2.destroyAllWindows() 54 | -------------------------------------------------------------------------------- /detaction.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HANLIN-zeng/defect_detection/6f2e2a04235a0a1210e5bcab5f066d6a809023be/detaction.rar --------------------------------------------------------------------------------