| 8 | |
| 9 | |
| 10 | def detect_defect(binary, boxes, tpl): |
| 11 | height, width = tpl.shape |
| 12 | index = 1 |
| 13 | defect_rois = [] |
| 14 | # 发现缺失 |
| 15 | for x, y, w, h in boxes: |
| 16 | roi = binary[y:y + h, x:x + w] |
| 17 | roi = cv.resize(roi, (width, height)) |
| 18 | mask = cv.subtract(tpl, roi) |
| 19 | se = cv.getStructuringElement(cv.MORPH_RECT, (5, 5), (-1, -1)) |
| 20 | mask = cv.morphologyEx(mask, cv.MORPH_OPEN, se) |
| 21 | ret, mask = cv.threshold(mask, 0, 255, cv.THRESH_BINARY) |
| 22 | count = 0 |
| 23 | for row in range(height): |
| 24 | for col in range(width): |
| 25 | pv = mask[row, col] |
| 26 | if pv == 255: |
| 27 | count += 1 |
| 28 | if count > 0: |
| 29 | defect_rois.append([x, y, w, h]) |
| 30 | cv.imwrite("mask%d.png"%index, mask) |
| 31 | index += 1 |
| 32 | return defect_rois |
| 33 | |
| 34 | |
| 35 | src = cv.imread("ce_02.jpg") |