How to fill closed contour region with white

Solution for How to fill closed contour region with white
is Given Below:

I’m trying to do a mask in cell image just with the ROI, so I applied the contours with OpenCV around the ROI but I’ve been struggling to get the region inside the contours. I want to have this region inside white and then discard the contours and the rest outside.

cell = cv.imread(original, 0) # original cell image after matching template
imgray = cv.cvtColor(cell,cv.COLOR_BGR2GRAY) 
ret,thresh_binary = cv.threshold(imgray,127,255,cv.THRESH_BINARY)

the resulting image is:

image 1

And the original is:

image 2

from another image after match template and the already marked cell contours, the image that is read in the code:

image 3

So basically what I need is to have white in that closed contour region and discard all the rest (i.e. black).
Could someone give me some help or hint about how do I do this?

Here’s an approach:

  • Convert image to grayscale
  • Find contours and fill in the contour
  • Perform morphological transformations to remove unwanted sections

We find contours then fill in the contour with cv2.drawContours() using -1 for the thickness parameter

To remove the line section, we can use morphological transformations

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
    cv2.drawContours(gray,[c], 0, (255,255,255), -1)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20,20))
opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel, iterations=2)

cv2.imshow('gray', gray)
cv2.imshow('opening', opening)
cv2.imwrite('opening.png', opening)