我正在尝试创建一个矩阵,其元素是与我定义的曲线的距离(代码如下):
我想对这张图像进行一些操作,给出一个矩阵,它包含该点与螺旋上任意点之间的所有最小欧几里德距离。
我试过像这样使用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())
发布于 2019-02-19 22:06:14
根据this stackoverflow discussion on 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)
这些努力的结果如下:
https://stackoverflow.com/questions/54778026
复制相似问题