python - 从曲线创建距离矩阵
问题描述
我正在尝试创建一个矩阵,其元素是到我定义的曲线的距离(下面的代码):
我想对这个图像执行一些操作,它给了我一个矩阵,其中包含该点和螺旋上的任何点之间的所有最小欧几里得距离。
我试过像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())
解决方案
根据关于 的这个 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)
这些努力导致了以下情节:
推荐阅读
- python - 在作为 Windows 服务执行的脚本中执行子进程
- embedded - 中断服务程序以测量相位差
- math - 用和/差公式表示 (cos(x))^3
- javascript - 滚动过去某个点确实
- java - Android Java Spongycastle ECDSA 签名到微妙.crypto Javascript
- javascript - Javascript暂停执行并等待被调用函数返回值
- javascript - 在向 api 发送 post 请求时,请求的资源上不存在“Access-Control-Allow-Origin”标头
- python-sphinx - 在 Sphinx 文档中将 id 添加到 index.rst 的正文中?
- python-3.x - 为什么我得到:无法导入模块“处理程序”:没有名为“paramiko”的模块?
- python - 如何在 django 模型表单中添加自定义字段?