Home > OS >  Why drawContours Max returns empty in python?
Why drawContours Max returns empty in python?

Time:12-07

I am trying to draw the largest contour of this image. But my code always returns a blank image. So, I am more than grateful of your help to solve this issue.

Original image enter image description here

Here is my code

import cv2
import numpy as np

img_1 = cv2.imread('img.png')
img_gray = cv2.cvtColor(img_1, cv2.COLOR_BGR2GRAY)

# get external contour
cnts = cv2.findContours(img_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

maxcontour = max(cnts, key=cv2.contourArea, default=0)


# draw white filled contour on black background
contour = np.zeros(img_1.shape, dtype=np.uint8)
contour.fill(0)
mask1 = cv2.drawContours(contour, [maxcontour], 0, 255, -1)
cv2.imshow('mask1.png', mask1)

Thanks in advance

CodePudding user response:

Find contours search for a white objects so just invert the image colors:

invert = cv2.bitwise_not(img_gray)
cnts = cv2.findContours(invert, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  • Related