0

I've got an image (ndarray with shape (480, 640, 3)) and an associated mask (ndarray with shape (480,640)). What I want to do is this: For each pixel in the image whose corresponding mask value is 255:

  • Calculate the "distance" of that pixel from a reference color = sqrt((R-r)^2+(B-b)^2+(G-g)^2))
  • Return the minimum and maximum values of that distance

I could of course loop over each pixel individually, but it feels like there's a more efficient way using np.array() or something. This question seems to be going in the right direction for me, but it doesn't include the mask.

Is there a clever/efficient way to do this?

Betty Crokker
  • 3,001
  • 6
  • 34
  • 68

1 Answers1

0

How about this?

import numpy as np

# dummy image
dummy = np.random.randint(low=0, high=255, size=(480, 640, 3), dtype=np.uint8)
# dummy mask
dummy_mask = np.zeros((dummy.shape[:-1]), dtype=np.uint8)
dummy_mask[100:200, 100:200] = 255

# only consider pixels where the mask is 255
masked = dummy[dummy_mask == 255]

# arbitrary RGB reference color
reference_color = [100, 100, 100]

# subtract the reference color from each pixel of the masked image, use absolute to avoid negative entries
difference = np.abs(masked - reference_color)
# find distances using the L2 norm
distances = np.linalg.norm(difference, axis=1, ord=2)

# find min & max
max_dist = np.max(distances)
min_dist = np.min(distances)

code-lukas
  • 1,586
  • 9
  • 19