2像素之间的距离 [英] Distance between 2 pixels

查看:771
本文介绍了2像素之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自软件开发,我是图像处理的新手。
我试图获得图像中两个像素之间的距离,该图像是一个numpy形状的数组(100,100,3)。

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).

例如我想要为了找到图像中蓝色像素(0,0,255)和像素红色(255,0,0)之间的距离,我尝试使用for循环或np.where()......但没有成功。
距离可能是图像中两个索引之间的某种差异(这些颜色的像素可能更多,因此图像中至少有第一个像素)

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)

知道怎么做吗?

编辑:
我正在捕捉我的部分屏幕:

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

推荐答案

让我们从测试图像开始。它是400x300像素的灰色(192),其中:

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


  • 红色3x3方格20,10,

  • 蓝色3x3方块,300,200

现在这样做:

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))

这给出:

(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))

这给出:

(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)

这篇关于2像素之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆