detecting defects in lines with opencv

Viewed 175

I am working on an algorithm to find defects in pictures of printed electronics like this,

enter image description here

I am trying to use findContours but the best result I get is this,

enter image description here

I am using this code:

import cv2
import numpy as np


def damageDetection(img):
   
    imgBW = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    imgThresh = cv2.adaptiveThreshold(imgBW, 255,
                                      cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                      cv2.THRESH_BINARY, 801, 0)

    kernel = np.ones((5,5), np.uint8)
    imgEro = cv2.erode(imgThresh, kernel, iterations=1)
    imgDil = cv2.dilate(imgEro, kernel, iterations=1)

    contours, hierarchy = cv2.findContours(imgDil, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)

    for cnt in contours:
        if cv2.contourArea(cnt) > 500:
            cv2.drawContours(img, cnt, -1, (0, 255, 0), 3)

    return img

I am an undergraduate student and this is for my bachelors thesis. It would be great if somebody has a tip for me! Thanks.

1 Answers

Here's the partial code & output (to detect the lines):

import cv2
import numpy as np
from matplotlib import pyplot as plt
im = cv2.imread("line.png")

imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,101,3)

lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 400, minLineLength=10, maxLineGap=200)
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(im, (x1, y1), (x2, y2), (255, 0, 0), 5)

plt.imshow(im)

Output: enter image description here

After getting the lines detected (hence segmented) you can find the defects easily.

Related