Search code examples
pythonopencvmatplotlibcomputer-visionedge-detection

Flawed contour detection in an image python opencv


I would like to detect the contour of the giant black blob in the following image:

enter image description here

So I used Canny edge detection to find the edges using the following code:

edged = cv2.Canny(image, 30, 200)

enter image description here

Then, when I try to find the contour, it gives me only half on the blob.

enter image description here

This is the code I used to find the contour:

# find contours in the edged image, keep only the largest
# ones, and initialize our screen contour
(cnts, _) = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:10]

# Scan the contours for largest item
array_sizes = []

for numpoints in cnts:
    array_sizes.append(len(numpoints))

largest = max(array_sizes)
second = second_largest(array_sizes)
index_of_object = array_sizes.index(largest)

# Largest detected contour
screenCnt = cnts[index_of_object] 

Is there any alteration I can make in the original image to get a full and more accurate detection of the large black blob? All help is appreciated.


Solution

  • The problem is in your workflow.

    Remove the Canny operator from your processing. It will give you an edge image from your blobs. Once you process the Canny image with contourFinder it will treat the edge segments as objects. Your largest contour will be of the longest edge segment. If you zoom into your Canny image you'll see that there are gaps where your current result ends.

    To get the contour of the blob skip Canny. Maybe you have to invert the image if findContours treats white as foreground.

    Please get some knowledge and understanding of those methods so you won't run into such traps again.