0

I have a code for finding the contours in image with OpenCV. But my code doesn't work when it's based on a messy image.

My image:

my image

My image is a scanned paper, there is a lot of noise and messy areas. So I applied Gaussian Blur, OTSU-Thresholding and Morph close for fix.

My code:

# Apply GaussianBlur + OTSU-Thresholding
grayscale_image = cv.cvtColor(source_image, cv.COLOR_BGR2GRAY)
grayscale_image = cv.GaussianBlur(grayscale_image, (5, 5), 0)
ret, grayscale_image = cv.threshold(grayscale_image, 200, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
cv.imshow("grayscale_image", grayscale_image)

# Apply Morph Close
kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
morph_closed_image = cv.morphologyEx(grayscale_image, cv.MORPH_CLOSE, kernel)
cv.imshow("morph_closed_image", morph_closed_image)

Nevertheless, the contours was created strangely by my code. messy areas of image was recognized as the contours.

My image with contours:

applied contours image

and, this is my contours code:

contours, hierarchy = cv.findContours(morph_closed_image, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
contour_sizes = [(cv.contourArea(contour), contour) for contour in contours]
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]

contour_image = source_image.copy()
cv.drawContours(contour_image, [biggest_contour], 0, (0, 0, 255), 2)
cv.imshow('contour_image', contour_image)

Therefore, I want to fix the noise and the messy in my image. If I fix noise and messy areas from the image, applied contours is work well.

How can I fix messy areas in my image with openCV?

My goal:

my goal

Please give me some advice.

Sujit
  • 1,653
  • 2
  • 9
  • 25

1 Answers1

1

M Z have a good point.

You just need to erode and then dilate it. It actually could be with the same kernel and iterations.

The main purpose for this is:

  1. With the erode, guaraty that little white shape are killed.
  2. With the dilation, recover the white shape eroded in the region of interest (the big shape).

So, you should erode until all the little shapes are killed, then try to return the original size of the big shape with dilation.

Alfredo Maussa
  • 515
  • 2
  • 8