'How to calculate the Euclidean distance in a canny image

I have a black line and purple lines. I want to calculate the distance between each purple pixel points in the canny image and the closest black line in the most efficient and fastest way. How can I do it? Is there any opencv-python function?

Actual image

Canny Image



Solution 1:[1]

I think this is close but haven't checked it too much yet:

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

This is the distance transform image - the brighter a pixel is, the further it is from a black pixel:

enter image description here

Here is the thresholded black and white image:

enter image description here

Keywords: OpenCV, image processing, distance transform, distancetransform, cv2.distancetransform, Python.

Solution 2:[2]

Consider a "distance transform" on a picture of one of the line types. Then, for any point of the other line type, look up the distance instantly.

Or turn your lines into polygons/polylines. That's an enormous reduction in data and turns your problem into a geometry problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Christoph Rackwitz