找到最近的白色像素到给定的像素位置openCV

tpu*_*GIS 5 python opencv

我有一个二进制图像,我需要选择最近的白色像素到给定的像素坐标集.

例如,如果我单击一个像素,我需要Python搜索值大于0的最近像素,然后返回该像素的坐标.

有什么想法吗?

我想我应该添加到目前为止我所做的事情.

import cv2
import numpy as np

img = cv.imread('depth.png', 0) # reads image as grayscale
edges = cv2.Canny(img, 10, 50)

white_coords = np.argwhere(edges == 255) # finds all of the white pixel coordinates in the image and places them in a list.

# this is where I'm stuck
Run Code Online (Sandbox Code Playgroud)

Dan*_*šek 8

  • 首先用于cv2.findNonZero获得所有白色像素的numpy坐标数组.

  • 接下来,计算点击目标点的距离(毕达哥拉斯定理)

  • 使用numpy.argmin找出最低距离的位置.

  • 返回相应非零像素的坐标.

示例脚本:

import cv2
import numpy as np

# Create a test image
img = np.zeros((1024,1024), np.uint8)

# Fill it with some white pixels
img[10,10] = 255
img[20,1000] = 255
img[:,800:] = 255


TARGET = (255,255)


def find_nearest_white(img, target):
    nonzero = cv2.findNonZero(img)
    distances = np.sqrt((nonzero[:,:,0] - TARGET[0]) ** 2 + (nonzero[:,:,1] - TARGET[1]) ** 2)
    nearest_index = np.argmin(distances)
    return nonzero[nearest_index]


print find_nearest_white(img, TARGET)
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

[[10 10]]
Run Code Online (Sandbox Code Playgroud)

因为它利用了优化cv2numpy功能,所以需要大约4ms才能完成.


或者,你可以选择一个纯粹的numpy解决方案,正如你已经尝试过的那样,使用numpy.argwhere而不是cv2.findNonZero:

def find_nearest_white(img, target):
    nonzero = np.argwhere(img == 255)
    distances = np.sqrt((nonzero[:,0] - TARGET[0]) ** 2 + (nonzero[:,1] - TARGET[1]) ** 2)
    nearest_index = np.argmin(distances)
    return nonzero[nearest_index]
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

[10 10]
Run Code Online (Sandbox Code Playgroud)

但是,对我来说这稍微慢一点,每次运行大约9毫秒.