【问题标题】:How to calculate the Euclidean distance in a canny image如何计算精巧图像中的欧几里得距离
【发布时间】:2021-03-16 10:33:26
【问题描述】:

我有一条黑线和一条紫线。我想以最有效和最快的方式计算canny图像中每个紫色像素点与最近的黑线之间的距离。我该怎么做?有opencv-python函数吗?

【问题讨论】:

  • 你的意思是你想知道,对于每个单独的紫色像素,到最近的黑色像素的距离?
  • 是的,你没看错。我将在精明的图像上执行此操作。

标签: python opencv image-processing euclidean-distance canny-operator


【解决方案1】:

考虑对其中一种线型的图片进行“距离变换”。然后,对于其他线型的任何点,立即查看距离。

或者将你的线变成多边形/折线。这极大地减少了数据,并将您的问题变成了几何问题。

【讨论】:

  • 是的,我是这么认为的,但是抱歉,我是图像处理方面的新手,所以我需要额外的信息或示例。
  • 请寻找“opencv 距离变换”。你会在官方文档中找到一个小教程。
【解决方案2】:

我认为这很接近但还没有检查太多:

#!/usr/bin/env python3

import cv2
import numpy as np

# Load input image
im = cv2.imread('PBv6H.png')

# DEBUG Get list of all unique colours in image
# np.unique(im.reshape((-1,3)),axis=0)

# Find purple pixels
purplepixels = np.where(np.all(im==[164,73,163],axis=-1))

# Make black and white image with only the black pixels from original
bw = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
_, bw = cv2.threshold(bw,1,255,cv2.THRESH_BINARY)
# DEBUG cv2.imwrite('bw.png', bw)

# Now calculate the distance from every pixel to the nearest black one
# Every pixel in "dst" image has a brightness equal to its distance to nearest black pixel 
dst = cv2.distanceTransform(bw, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)

# Print out the distance to the nearest black pixel for each purple pixel
for y,x in zip(purplepixels[0], purplepixels[1]):
   print(f'[{y},{x}]: {dst[y,x]}')

这是距离变换图像 - 像素越亮,距离黑色像素越远:

这是经过阈值处理的黑白图像:

关键词:OpenCV、图像处理、距离变换、distancetransform、cv2.distancetransform、Python。

【讨论】:

  • 非常感谢。你让我很开心。我很感激。我想知道我们是否可以找出最近的黑色像素的坐标?
  • 你应该可以把cv2.distanceTransform()改成dst, labels = cv2.distanceTransformWithLabels(bw, cv2.DIST_L2, cv2.DIST_MASK_PRECISE, labelType=cv2.DIST_LABEL_PIXEL)
  • 实际上,这就是我要求您在 cmets 中澄清您只想要距离(而不是最近像素的坐标)的原因。如果你真的想要最近像素的坐标,你最好使用 SciPy 函数scipy.ndimage.morphology.distance_transform_edt()
  • 我写了这个函数,我解决了。非常感谢。edt, inds = ndimage.distance_transform_edt(bw, return_indices=True)
猜你喜欢
  • 2018-08-26
  • 1970-01-01
  • 2020-11-29
  • 2018-02-14
  • 2010-11-26
  • 2013-04-07
  • 2021-01-31
  • 2015-09-23
相关资源
最近更新 更多