gpt4 book ai didi

python - 找到距离给定像素位置最近的白色像素 openCV

转载 作者:太空狗 更新时间:2023-10-30 02:08:07 25 4
gpt4 key购买 nike

我有一个二值图像,我需要在其中选择最接近给定像素坐标集的白色像素。

例如,如果我点击一个像素,我需要让 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

最佳答案

  • 首次使用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)

打印:

[[10 10]]

大约需要 4 毫秒才能完成,因为它利用了优化的 cv2numpy 函数。


或者,您可以寻求纯 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]

打印:

[10 10]

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

关于python - 找到距离给定像素位置最近的白色像素 openCV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com