Skip to main content

Finding multiple non-zero value in an image

Image 1 (Image)

I have this kind of image, and I want to draw rectangle on each of non zero value of them.

I am trying to use this code from other thread

import cv2
import numpy as np

img = cv2.imread('blob_in_the_middle.png', cv2.IMREAD_GRAYSCALE)
positions = np.nonzero(img)

top = positions[0].min()
bottom = positions[0].max()
left = positions[1].min()
right = positions[1].max()

output = cv2.rectangle(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    , (left, top), (right, bottom), (0,255,0), 1)

cv2.imwrite('blob_with_bounds.png', output)

But what I get is this:

Image 2 (Wrong Rectangle)

What I expect to get is something like this:

Image 3 (Expected Rectangle)



source https://stackoverflow.com/questions/72366224/finding-multiple-non-zero-value-in-an-image

Comments