image - 最小成本路径/最小成本路径
问题描述
我目前正在使用来自 skimage.graph 的库和函数 route_through_array 来获取成本图中从一个点到另一个点的最低成本路径。问题是我有多个起点和多个终点,这会导致数千次迭代。我目前正在用两个 for 循环修复这个问题。以下代码只是一个说明:
img=np.random.rand(400,400)
img=img.astype(dtype=int)
indices=[]
costs=[]
start=[[1,1],[2,2],[3,3],[4,5],[6,17]]
end=[[301,201],[300,300],[305,305],[304,328],[336,317]]
for i in range(len(start)):
for j in range(len(end)):
index, weight = route_through_array(img, start[i],end[j])
indices.append(index)
costs.append(weight)
根据我从文档中了解到的情况,该函数接受许多端点,但我不知道如何在函数中传递它们。有任何想法吗?
解决方案
skimage.graph.MCP
通过直接与Cython 类进行交互,这应该可以更有效地实现。便利包装器route_through_array
不够通用。假设我正确理解了您的问题,那么您要寻找的基本上就是MCP.find_costs()
方法。
您的代码将看起来像(忽略导入)
img = np.random.rand(400,400)
img = img.astype(dtype=int)
starts = [[1,1], [2,2], [3,3], [4,5], [6,17]]
ends = [[301,201], [300,300], [305,305], [304,328], [336,317]]
# Pass full set of start and end points to `MCP.find_costs`
from skimage.graph import MCP
m = MCP(img)
cost_array, tracebacks_array = m.find_costs(starts, ends)
# Transpose `ends` so can be used to index in NumPy
ends_idx = tuple(np.asarray(ends).T.tolist())
costs = cost_array[ends_idx]
# Compute exact minimum cost path to each endpoint
tracebacks = [m.traceback(end) for end in ends]
请注意,原始输出cost_array
实际上是一个完全密集的数组,其形状与 相同img
,它仅在您要求端点的地方具有有限值。这种方法唯一可能出现的问题是,如果从多个起点开始的最小路径会收敛到同一个终点。您将只能通过上面的代码获得这些收敛路径中较低路径的完整回溯。
回溯步骤仍然有一个循环。这很可能通过使用tracebacks_array
和与 `m.offsets 交互来消除,这也将消除上面提到的歧义。但是,如果您只想要最小成本和最佳路径,则可以省略此循环 - 只需使用 argmin 找到最小成本,并跟踪该单个端点(或几个端点,如果多个端点绑定为最低) 背部。
推荐阅读
- angular - Ng-select 下拉菜单部分隐藏在 mat-expansion-panel 内?
- c++ - VS2019 中的 C++20 范围反向视图问题(最新)
- esxi - 如何使用只有一个 IP 地址的 3 个 VM 配置 Cisco 服务器 ESXi?
- mysql - 恢复 Mysql 8 only ibd
- sql - 如果一列的值在结果中多次出现,如何只选择一行?
- c# - Blazor 服务器组件在状态更改后不刷新
- spring-boot - 使用什么过滤器从远程 sftp 中挑选最旧的文件
- simple-injector - SimpleInjector Rider 2021 nuget 安装失败“与 DotNetCompilerPlatform 不兼容
- javascript - 域名正则表达式
- javascript - 在 React 中开发期间和部署后的不同图像行为