2

I have a problem while looking for biggest contour. I'm using image after canny edge detection: Canny edge detection

Then I'm using

contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

to find contours:

Contour detection

Next step is to find the biggest contour... I've tried:

contour = max(contours, key = cv2.contourArea)

but this give me something like:

enter image description here

Any ideas how to fix this? Thanks!

Code:

import cv2
image = cv2.imread('TEST_1.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gaussian = cv2.GaussianBlur(gray,(3,3),cv2.BORDER_DEFAULT)
edges = cv2.Canny(gaussian,100,200)

contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contour = max(contours, key = cv2.contourArea)

contourImg = cv2.drawContours(image, contour, -1, (0,255,0), 3)
cv2.imshow("Contours", contourImg)

cv2.waitKey(0)
cv2.destroyAllWindows()

Also, contour area for this dot is 109 and for my biggest contour is 3.5

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
kacpo1
  • 525
  • 5
  • 17
  • `contour = max(contours, key = cv2.contourArea)` seems OK to me. What are you doing after that? Can you please attach the next code snippet as well ? – ZdaR May 27 '20 at 09:11
  • Does this answer your question? [Find and draw the largest contour in opencv on a specific color (Python)](https://stackoverflow.com/questions/44588279/find-and-draw-the-largest-contour-in-opencv-on-a-specific-color-python) – Yunus Temurlenk May 27 '20 at 09:12
  • @YunusTemurlenk As you can see I've already used this code. – kacpo1 May 27 '20 at 09:18
  • 1
    @ZdaR Maybe problem is in that contour is not closed? I used `contourImg = cv2.drawContours(image, [max(contours, key = len)], 0, (0,255,0),2, cv2.LINE_AA, maxLevel=1)` and it's working. – kacpo1 May 27 '20 at 09:44
  • If you wanna go with area then use dilate and closing morphological operation before finding out the contours. – Pygirl May 27 '20 at 10:52

1 Answers1

1

Apparently it seems like some contours are not closed. Using length as criterion rather than area in this case worked for me.

import cv2
image = cv2.imread('TEST_1.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gaussian = cv2.GaussianBlur(gray,(3,3),cv2.BORDER_DEFAULT)
edges = cv2.Canny(gaussian,100,200)

contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contour = max(contours, key = len)

contourImg = cv2.drawContours(image, contour, -1, (0,255,0), 3)
cv2.imshow("Contours", contourImg)

cv2.waitKey(0)
cv2.destroyAllWindows()

I also changed the method in findContours from cv2.CHAIN_APPROX_SIMPLE to cv2.CHAIN_APPROX_NONE. Alternately, you try fixing the problem by changing the limit values in cv2.Canny() and using cv2.RETR_EXTERNAL.