Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between 2 pixels

Coming from software development, i'm new to image processing. I try to get the distance between two pixels in an image that is a numpy array of shape (100, 100, 3).

For example i want to find the distance between a pixel blue (0, 0, 255) and a pixel red (255, 0, 0) in the image, I tried with a for loop or np.where() ... but no success. The distance could be the some kind of difference between the two indexes in the image (possibility that there is more pixels of these colors so at least the first met in the image)

Any idea how to do that ?

EDIT: I'm capturing part of my screen like that:

screen = np.array(pyautogui.screenshot(region=(80,120,100,100)))

Now i want to find the pixel(s) of color blue and the pixel(s) of color red and the distance between them in the image

like image 499
Louis Beaumont Avatar asked Mar 20 '26 16:03

Louis Beaumont


1 Answers

Let's start with a test image. It is 400x300 pixels of gray(192), with:

  • a red 3x3 square at 20,10,
  • a blue 3x3 square at 300,200

enter image description here

Now do this:

import numpy as np
import PIL
import math

# Load image and ensure RGB - just in case palettised
im=Image.open("a.png").convert("RGB")

# Make numpy array from image
npimage=np.array(im)

# Describe what a single red pixel looks like
red=np.array([255,0,0],dtype=np.uint8)

# Find [x,y] coordinates of all red pixels
reds=np.where(np.all((npimage==red),axis=-1))

This gives:

(array([10, 10, 10, 11, 11, 11, 12, 12, 12]),
 array([20, 21, 22, 20, 21, 22, 20, 21, 22]))

Now let's do the blue pixels:

# Describe what a single blue pixel looks like
blue=np.array([0,0,255],dtype=np.uint8)

# Find [x,y] coordinates of all blue pixels
blues=np.where(np.all((npimage==blue),axis=-1))

This gives:

(array([200, 200, 200, 201, 201, 201, 202, 202, 202]),
 array([300, 301, 302, 300, 301, 302, 300, 301, 302]))

So now we need the distance from the first red to the first blue pixel

dx2 = (blues[0][0]-reds[0][0])**2          # (200-10)^2
dy2 = (blues[1][0]-reds[1][0])**2          # (300-20)^2
distance = math.sqrt(dx2 + dy2)
like image 70
Mark Setchell Avatar answered Mar 23 '26 05:03

Mark Setchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!