4

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?

Zhubei Federer
  • 1,274
  • 2
  • 10
  • 27
  • 1
    Could you add your original image and expected output image? You can use morphological operations to smooth out the outlier sections then find the resulting contour. Then you can use `cv2.drawContours()` and fill in the closed contour region with white – nathancy Aug 16 '19 at 00:52
  • See CV_FILLED or -1 for thickness argument in cv2.drawContours() at https://docs.opencv.org/3.1.0/d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc – fmw42 Aug 16 '19 at 01:10
  • Already edited -nathancy – Bruno Miguel Gonçalves Aug 16 '19 at 01:30

1 Answers1

9

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)
cv2.waitKey(0)
nathancy
  • 42,661
  • 14
  • 115
  • 137