問題描述
來自軟件開發,我是圖像處理的新手.我嘗試獲取形狀為 (100, 100, 3) 的 numpy 數組的圖像中兩個像素之間的距離.
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:
- 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]))
現在讓我們做藍色像素:
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個像素之間的距離的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!