Select coordinates from image, based on certain criteria

Issue

Let’s say I have an OpenCV image in form of a numpy array. I want to collect all (x, y) point coordinates of points that have greater than zero blue color component. The naive way would be something like this:

n_rows, n_cols, _ = image.shape
points = []
for row in range(n_rows):
    for col in range(n_cols):
        if image[row, col, 0] > 0:
            points.append((row, col))

Is there a smarter and more efficient way to do the same, using numpy or OpenCV capabilities?

Solution

This will help:

np.argwhere(image[:,:,0] > 0)

For a given image having three color channels (in this BGR), the 0 in image[:,:,0] denotes the first channel (blue)

The statement itself returns an array of coordinates where the pixel values of blue channel is greater than 0

Answered By – Jeru Luke

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.