2

How can I most efficiently find the index of pixels within epsilon of the L2 distance from a desired colour?

I could do three nested loops but im told that loops are quite inefficient and that maybe a vectorised solution was available. Is it possible to use something like np.where or np.argwhere to find this?

christina li
  • 83
  • 1
  • 5
  • Consider using an HSL-based approach like this if that fits your scenario... https://stackoverflow.com/a/52183666/2836621 – Mark Setchell Dec 05 '18 at 08:16

1 Answers1

2

You can use numpy to compute the L2 distance from the desired color and then use np.where to get the coordinates of the pixels which have a distance less than epsilon.

img = np.zeros((400, 600, 3), dtype=np.uint8)
color = [255, 5, 31]    # desired color
epsilon = 10

# L2 distance from the desired color
distance_L2 = np.sqrt(np.sum((img.astype(int) - color)**2, 
axis=2))

# coordinates of the pixels that are within epsilon from the 
# desired color
y_coords, x_coords = np.where(distance_L2 < epsilon)
sowlosc
  • 470
  • 3
  • 8
  • 1
    Nice solution - it's around 15% faster on my machine to omit the `np.sqrt()` and then use `np.where(distance_L2 < epsilon*epsilon)` on my machine. – Mark Setchell Dec 05 '18 at 12:28