First time here? Check out the FAQ!

Ask Your Question
0

Defect Detection using OpenCV

asked Apr 26 '18

Dear Members,

I am trying to detect defect in image by comparing defected image with original one. I have achieved it so far using canny algorithm.

Now i have to fill color to defected area after applying canny algorithm to it.

Kindly let me know for the same.

Thanks in advance.

Preview: (hide)

Comments

2

please show us, what you tried, code, images ...

berak gravatar imageberak (Apr 26 '18)edit

Hi Berak,

 Thanks for reply,

I am attaching code:

im = cv2.imread("C:/Original_Image.jpg", 0)
im1 = cv2.imread("C:/Defect_Image.jpg", 0)

diff = cv2.absdiff(im, im1)
#cv2.imwrite("C:\this.jpg", diff)
ret, thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
contours, hierarchy, we = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
mask = cv2.cvtColor(im1, cv2.COLOR_GRAY2BGR)

try:
    hierarchy = hierarchy[0]
except:
    hierarchy = []

for contour, hier in zip(contours, hierarchy):
    (x, y, w, h) = cv2.boundingRect(contour)
    cv2.rectangle(mask, (x, y), (x+w, y+h), (255, 0, 0), 3)

cv2.imwrite("C:\mask.jpg", mask)
cv2.imwrite("C:\thresh.jpg", thresh)
Ranganath gravatar imageRanganath (Apr 26 '18)edit

im: original image without defect im1: with defect (A scratch on image)

Ranganath gravatar imageRanganath (Apr 26 '18)edit

problem what i am facing is i am not able to get rectangle shape on defected areas.

Ranganath gravatar imageRanganath (Apr 26 '18)edit

Images ... my guess is your contours are not closed hence incorrect bounding rects

StevenPuttemans gravatar imageStevenPuttemans (Apr 27 '18)edit

Hi Steven,

  How to work on that?
Ranganath gravatar imageRanganath (Apr 30 '18)edit

1 answer

Sort by » oldest newest most voted
0

answered May 15 '19

updated May 18 '19

supra56 gravatar image

Hi Ranganath try the following code:

import cv2
im = cv2.imread("image.jpg", 0)
im1 = cv2.imread("image1.jpg", 0)

diff = cv2.absdiff(im, im1)
ret, thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
mask = cv2.cvtColor(im1, cv2.COLOR_GRAY2BGR)

try:
    hierarchy = hierarchy[0]
except:
    hierarchy = []

for contour in contours[:-1]:
    (x, y, w, h) = cv2.boundingRect(contour)
    area = cv2.contourArea(contour)
    if area>100:
        cv2.rectangle(im1, (x, y), (x+w, y+h), (255, 0, 0), 3)

cv2.imshow("mask", im1)
cv2.imshow("thresh", thresh)
cv2.waitKey(0)
Preview: (hide)

Question Tools

1 follower

Stats

Asked: Apr 26 '18

Seen: 4,677 times

Last updated: May 17 '19