Andrew
Andrew

Reputation: 549

finding and drawing bounding boxes

I currently have a 2D array of values. I am currently trying to find areas of it with values that are significantly different and draw bounding boxes around them.

Currently, I have used to scikit-image to threshold my values, by doing

from skimage import filters
val = filters.threshold_otsu(zo)
mask = zo < val

This mask gives me an array of Trues and Falses, like:

[[F, T, T, F],
 [F, T, F, F],
 [F, F, F, F],
 [F, F, F, T]
]

Now, using this, I would like to draw a rectangle around each of the two groups of the Trues. However, I am finding it difficult to perform this. OpenCV seems to be able to perform actions like this simply (see: Drawing bounding rectangles around multiple objects in binary image in python) using the function cv2.boundingRect(). However, since my original object is not an image I am not using it.

Is there a simple function in Python to calculate the areas of bounding boxes (kinda like cv2.boundingRect()), or a way to pass a 2d matrix like the one above to OpenCV to be able to use it directly?

Upvotes: 0

Views: 2021

Answers (1)

Juan
Juan

Reputation: 5738

There is an example drawing bounding boxes about regions in the scikit-image gallery here:

https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html

You need two things:

(1) label your regions so that they are two distinct regions. ie your image above would become:

[[0, 1, 1, 0],
 [0, 1, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 2]]

(2) Use regionprops and props.bbox to find the bounding box of each region, which you can then use to draw in matplotlib or your software of choice.

So, in the example, search for "label" and "bbox" to see usage examples.

Upvotes: 1

Related Questions