繁体   English   中英

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

[英]Find nearest white pixel to a given pixel location 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
  • 首先使用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]]

并且需要大约4ms才能完成,因为它利用了优化的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毫秒。

想,是的! 从给定像素开始循环,在第一次迭代检查给定像素周围的所有像素,如果找不到白色像素,则将距离增加1并检查给定像素的外接周长中的任何像素是否为白色,继续循环,直到找到白色像素或超出界限。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM