【问题标题】:Distance between 2 pixels2个像素之间的距离
【发布时间】:2018-12-07 15:36:55
【问题描述】:

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

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

知道怎么做吗?

编辑: 我正在像这样捕获部分屏幕:

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

现在我想在图像中找到蓝色的像素和红色的像素以及它们之间的距离

【问题讨论】:

  • 尝试将您的ndarray 重塑为(10000, 3),然后从scipy 包中应用pdist (docs.scipy.org/doc/scipy-0.16.1/reference/generated/…)。
  • 颜色无所谓,使用位置。
  • 您是先找到(或寻找)一个蓝色像素和一个红色像素,然后再找到这些像素之间的距离,然后找不到蓝色和红色像素吗?
  • 距离是指测量一张纸上两点之间的距离?看看欧几里得向量空间中的二维距离:sqrt((a.x-b.x)^2 + (a.y-b.y)^2)
  • 请向我们展示不起作用的代码...也许它有助于理解您要完成的工作。你需要什么样的距离?我们是在谈论空间距离还是颜色距离?

标签: python numpy opencv image-processing computer-vision


【解决方案1】:

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

  • 20,10 处的红色 3x3 正方形,
  • 300,200 处的蓝色 3x3 正方形

现在这样做:

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

现在让我们做蓝色像素:

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

所以现在我们需要从第一个红色像素到第一个蓝色像素的距离

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)

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多