I'm trying to detect a polygonal shape in a binary image. If the shape is white then the background is black and vice versa. For example if the shape is white it has some black spots in it and the background is black and has some white spots in it. If i'm using OpenCV's tools for object detection (canny, contours, lines, etc...) it works badly and detects things that are not the shape, or rare occasions it does detect the shape but does so badly.
Example of an image with a shape
I tried using canny edge detection and contours and many things with lines but none of the methods worked. I did not provide the results because i didn't save them and i tried many things and they were not even in the direction of detecting it correctly.
Getting a perfect solution is challenging.
We may find an approximated solution using the following stages:
Start by closing and opening morphological operations.
Apply closing with 5x5 kernel, followed by opening with 3x3 kernel - connecting neighbors without too much dilating:
Result:

Removing small contours:
Result:

Apply opening in the vertical direction and then in the horizontal direction:
Result:

Find largest "black" contour, and approximate it to a rectangle using simplify_contour:
Result:

For finding the best inner rectangle we my use one of the solutions from the following post.
Code sample: