I’m using OpenCV 4 – python 3 – to find an specific area in a black & white image.
This area is not a 100% filled shape. It may hame some gaps between the white lines.
This is the base image from where I start processing:
This is the rectangle I expect – made with photoshop -:
Results I got with hough transform lines – not accurate –
So basically, I start from the first image and I expect to find what you see in the second one.
Any idea of how to get the rectangle of the second image?
3
Answers
In Python/OpenCV, you can use morphology to connect all the white parts of your image and then get the outer contour. Note I have modified your image to remove the parts at the top and bottom from your screen snap.
Input:
Image after morphology:
Result:
I’d like to present an approach which might be computationally less expensive than the solution in fmw42’s answer only using NumPy’s
nonzero
function. Basically, all non-zero indices for both axes are found, and then the minima and maxima are obtained. Since we have binary images here, this approach works pretty well.Let’s have a look at the following code:
I borrowed the cropped image from fmw42’s answer as input, and my output should be the same (or most similar):
Hope that (also) helps!
Here’s a slight modification to @fmw42’s answer. The idea is connect the desired regions into a single contour is very similar however you can find the bounding rectangle directly since there’s only one object. Using the same cropped input image, here’s the result.
We can optionally extract the ROI too