opencv 如何计算Canny图像中的欧氏距离

sc4hvdpw  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(183)

我有一条黑线和一条紫线,我想用最高效最快的方法计算canny图像中每个紫色像素点到最近黑线的距离,怎么做呢?有opencv-python函数吗?

mrzz3bfm

mrzz3bfm1#

我认为这是接近,但还没有检查它太多:

#!/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]}')

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

下面是阈值化的白色图像:

4smxwvx5

4smxwvx52#

考虑对一种线型的图片进行“距离变换”,然后,对另一种线型的任意点,立即查找距离。
或者把你的线变成多边形/折线,这是一个巨大的数据减少,把你的问题变成一个几何问题。

相关问题