smo*_*mop 5 python matlab voronoi scipy
我使用voronoinMATLAB来判断单元格之间的连接,我想把这个函数转换成Python。
当我使用scipy.spatial.VoronoiPython 时,输出有点不同。例如,我对 MATLAB 和 Python 使用了相同的输入,您可以在下一个代码中看到。
MATLAB:
seed = [ 17.746 -0.37283 -0.75523;
6.1704 1.3404 7.0341;
-7.7211 5.4282 4.5016;
5.8014 2.1252 -6.2491;
-16.047 -2.8472 -0.024795;
-2.2967 -6.7334 0.60707]
[vvern_mat, vceln_mat] = voronoin(seed);
Run Code Online (Sandbox Code Playgroud)
Python:
import numpy as np
from scipy.spatial import Voronoi
seed = np.array([[ 17.746 , -0.37283 , -0.75523 ],
[ 6.1704 , 1.3404 , 7.0341 ],
[ -7.7211 , 5.4282 , 4.5016 ],
[ 5.8014 , 2.1252 , -6.2491 ],
[-16.047 , -2.8472 , -0.024795],
[ -2.2967 , -6.7334 , 0.60707 ]])
vor = Voronoi(seed)
vvern_py = vor.vertices
vceln_py = vor.regions
Run Code Online (Sandbox Code Playgroud)
输出如下:
MATLAB:
vvern_mat =
Inf Inf Inf
-6.9386 1.7980 -7.7861
-15.9902 -20.8031 50.1840
29.5016 106.3690 5.9214
8.6816 -6.5899 -0.1741
-0.2027 2.1210 0.5874
vceln_mat =
1 4 5
1 3 4 5 6
1 2 3 4 6
1 2 4 5 6
1 2 3
1 2 3 5 6
Run Code Online (Sandbox Code Playgroud)
Python:
vvern_py = array([[ -6.93864391, 1.79801934, -7.78610533],
[-15.9902125 , -20.80310202, 50.1840397 ],
[ 29.501584 , 106.36899584, 5.92137852],
[ 8.68156407, -6.58985621, -0.17410448],
[ -0.20266123, 2.12100225, 0.58735065]])
vceln_py = [[],
[-1, 0, 2, 3, 4],
[-1, 2, 3],
[-1, 0, 1],
[-1, 0, 1, 2, 4],
[-1, 1, 2, 3, 4],
[-1, 0, 1, 3, 4]]
Run Code Online (Sandbox Code Playgroud)
当您专注于 时vceln,您会注意到 MATLAB 和 Python 之间的值是相同的,因为您可以vceln_mat通过将两个添加到vceln_py. 但是,行顺序不同,我很难转换vceln_py为vceln_mat.
我以为我可以通过将QhullMATLAB 的选项应用于 Python来解决这个问题,但我无法获得相同的输出。(关于 voronoin 的选项:https ://jp.mathworks.com/help/matlab/ref/voronoin.html ? lang = en#bqurvsm-1 )如果有人能解决这个问题,我将不胜感激。
中列表的顺序vor.regions可以是任意的。但是,您可以通过属性获取哪个区域与哪个入口点关联的信息vor.point_region。scipy.spatial.Voronoi文档说
Run Code Online (Sandbox Code Playgroud)point_region: (list of ints, shape (npoints)) Index of the Voronoi region for each input point.
所以你必须vor.regions根据该信息来订购vor.point_region
# Find point coordinate for each region
sorting = [np.where(vor.point_region==x)[0][0] for x in range(1, len(vor.regions))]
# sort regions along coordinate list `sorting` (exclude first, empty list [])
sorted_regions = [x for _, x in sorted(zip(sorting, vor.regions[1:]))]
sorted_regions = [[-1, 2, 3],
[-1, 1, 2, 3, 4],
[-1, 0, 1, 2, 4],
[-1, 0, 2, 3, 4],
[-1, 0, 1],
[-1, 0, 1, 3, 4]]
Run Code Online (Sandbox Code Playgroud)
像这样,您可以获得 MATLAB 函数的排序voronoin,显然该函数本质上已经进行了排序。
为了获得相同的数值,您可以计算(正如您已经提到的那样)
# PseudoCode
vceln_py = vceln_mat - 2
Run Code Online (Sandbox Code Playgroud)
然而,其原因似乎没有记录在scipy.spatial.Voronoi、voronoin和qhull文档中。