首页 > 解决方案 > 从曲线创建距离矩阵

问题描述

我正在尝试创建一个矩阵,其元素是到我定义的曲线的距离(下面的代码):

矩阵中的螺旋曲线

我想对这个图像执行一些操作,它给了我一个矩阵,其中包含该点和螺旋上的任何点之间的所有最小欧几里得距离。

我试过像scipy这样使用ndimage.distance_transform_edt

import scipy.ndimage as ndi
transformed = ndi.distance_transform_edt(spiral())

但是输出并没有给我我想要的东西!

有谁知道如何生成这个矩阵?

下面的螺旋生成代码:

import numpy as np
import matplotlib.pyplot as plt

def pol2cart(rho, phi):
    # https://stackoverflow.com/questions/20924085/python-conversion-between-coordinates
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(y, x)

def spiral():

    C = 0.15
    phi = np.linspace(6, 540, 1000)
    rho =  (1 - C * np.log(phi - 5))

    # Now convert back to x, y coordinates
    y, x = pol2cart(rho, np.deg2rad(phi))

    # Center the spiral so we can see it better.
    x -= x.min()
    y -= y.min()
    x += 1
    y += 1.5

    m = np.zeros((100, 100))

    for i in range(len(x)):
        try:

            # Include some scaling factor to increase the size of the curve
            m[int(x[i]*30), int(y[i]*30)] = 1
        except IndexError:
            continue

    return m

plt.imshow(spiral())

标签: pythonimagenumpyscipy

解决方案


根据关于 的这个 stackoverflow 讨论scipy.ndi.distance_transform_edt()该函数将计算非零矩阵的元素到零元素的最近欧几里得距离。

问题是您的spiral()函数返回一个矩阵,该矩阵在曲线存在的地方非零(完全等于 1),而在其他任何地方都为 0。要解决这个问题:

import scipy.ndimage as ndi
# The original spiral curve, with 1's where the curve is defined, else 0
s = spiral()
# Transformed data: 0's representing the curve, with 1's everywhere else
TS= 1-s
transformed = ndi.distance_transform_edt(TS)

这些努力导致了以下情节:

l2 到螺旋的距离


推荐阅读