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 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:
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:
Please give me some advice.