[FIXED] Specifying a rectangle around a binary object to define a spatially-constrained area?

Issue

I am programming in python. I have the coordinate of the center of the object in a binary image. How can I define a bounding box area around the object in python, which starts from left-top most nonzero point and ends in right-bottom most point?

I want to consider a rectangle area around the object to spatially and virtually constrain the working area for an algorithm. For this purpose, how to check whether a point is falling in that region or not?

Your help is appreciated


Solution

You can use the boundingRect function as described in this Contour Features tutorial:

The img.png is the following:

enter image description here

import cv2
import numpy as np

img = cv2.imread('img.png')
active_px = np.argwhere(img!=0)
active_px = active_px[:,[1,0]]
x,y,w,h = cv2.boundingRect(active_px)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),1)
cv2.imwrite('result.png',img)

result.png is the following:

enter image description here



Answered By - Alessandro Jacopson
Answer Checked By - David Marino (sql.easybugfix Volunteer)

Related Posts

Post a Comment