user3696412
user3696412

Reputation: 1419

Bounding box of blob in image

I have a grayscale image with black background, and some non-black objects on it like this:

enter image description here

Now I want to find the minimal (rectangle) bounding box for each object. I can provide a starting point inside each object if this helps.

Since there are no fancy thresholds or anything, I would like to avoid something like Canny to find the contures. If a pixel is not 0, it's in the blob.

Upvotes: 2

Views: 1934

Answers (2)

Carlos Melus
Carlos Melus

Reputation: 1552

In order to plot rectangles around anything that is not completely black in your image you can do the following:

imagefile = '/path/to/your/image'
img = cv2.imread(imagefile)

# Convert you image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Threshold the image to extract only objects that are not black
# You need to use a one channel image, that's why the slice to get the first layer
tv, thresh = cv2.threshold(gray[:,:,0], 1, 255, cv2.THRESH_BINARY)

# Get the contours from your thresholded image
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

# Create a copy of the original image to display the output rectangles
output = img.copy()

# Loop through your contours calculating the bounding rectangles and plotting them
for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(output, (x,y), (x+w, y+h), (0, 0, 255), 2)
# Display the output image
plt.imshow(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))

output image with rectangles around non-zero objects

Upvotes: 4

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34150

Well no matter what you use, you will still need to loop through all pixels. although Bitmap.GetPixel(x,y) is mostly used but it is very slow. but if you lock bits in the memory and loop over the byte array it will be hundreds of time faster.

please have a look at this document for locking bits of an image in memory.

Upvotes: 0

Related Questions