Search code examples
pythonopencvobject-detection

Using opencv to find all contours in an image


Image with the program applied

Image without the program applied

can someone help me identify the problem in my code, I'm trying to find all the contours in my image and then coat it with an ash border but it seems to only coat some of the contours. '''

image_find_goal = "/absolutePathWays.img"
kernel = np.ones((5,5),np.uint8)
#findGoal(image_find_goal)
img1 = cv.imread(image_find_goal,cv.IMREAD_GRAYSCALE)
ret,mask = cv.threshold(img1, 125, 255, cv.THRESH_BINARY_INV)
contours, hierarchy = cv.findContours(mask,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
for cnt in contours:
    approx = cv.approxPolyDP(cnt,0.01*cv.arcLength(cnt,True),True)
    if len(approx) == 4:
        cv.drawContours(mask,cnt,-1,(119,256,51),5)
mask3 = cv.resize(mask,(640,640))
cv.imshow('IMAGE', mask3)
cv.waitKey(0)
cv.destroyWindow(mask3)

'''


Solution

    • I tried printing the values of len(approx), very few values are equal to 4, contours detected might have minor inaccuracies due to which unexpected results might have occured.
    • I tried changing the
    if len(approx) == 4:
    

    to

    if len(approx) >= 4:
    

    Resulting image

    • You can also try removing the condition altogether or edit it as per your requirement.