gpt4 book ai didi

python - 在标签图中的段周围获取边界框的最快方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:20 25 4
gpt4 key购买 nike

3D 标签图是矩阵,其中每个像素(体素)都有一个整数标签。这些值应该是连续的,这意味着带有标签 k 的段不会被分段。

给定这样的标签图(分段),在 Python 中获取每个分段周围的最小边界框坐标的最快方法是什么?

我尝试了以下方法:

  • 使用多索引迭代器(来自 numpy.nditer)遍历矩阵并构造一个反向索引字典。这意味着对于每个标签,您都会获得标签所在的每个体素的 3 个坐标。
  • 对于每个标签,获取每个坐标的最大值和最小值。

好处是您可以在一次 O(N) 次传递中获得所有位置信息。不好的是我不需要这些详细信息。我只需要四肢,所以可能有更快的方法来执行此操作,使用一些比许多列表追加更快的 numpy 函数。有什么建议吗?

一次通过矩阵在我的机器上大约需要 8 秒,所以摆脱它会很棒。为了解数据,标签图中有数百个标签。标签图的大小可以是 700x300x30 或 300x300x200 或类似的大小。

编辑:现在仅存储每个标签每个坐标的更新最大值和最小值。这消除了维护和存储所有这些大列表(追加)的需要。

最佳答案

如果我对你的问题的理解正确,你有体素组,并且你希望在每个轴上都有一个组的极值。

让我们定义:

  • arr:整数标签的 3D 数组

  • labels:标签列表(整数 0..labmax)

代码:

import numpy as np

# number of highest label:
labmax = np.max(labels)

# maximum and minimum positions along each axis (initialized to very low and high values)
b_first = np.iinfo('int32').min * np.ones((3, labmax + 1), dtype='int32')
b_last = np.iinfo('int32').max * np.ones((3, labmax + 1), dtype='int32')

# run through all of the dimensions making 2D slices and marking all existing labels to b
for dim in range(3):
# create a generic slice object to make the slices
sl = [slice(None), slice(None), slice(None)]

bf = b_first[dim]
bl = b_last[dim]

# go through all slices in this dimension
for k in range(arr.shape[dim]):
# create the slice object
sl[dim] = k
# update the last "seen" vector
bl[arr[sl].flatten()] = k

# if we have smaller values in "last" than in "first", update
bf[:] = np.clip(bf, None, bl)

在这个操作之后,我们有六个向量给出了每个轴的最小和最大索引。例如,标签 13 沿第二轴的边界值为 b_first[1][13]b_last[1][13]。如果缺少某个标签,则所有对应的 b_firstb_last 将是最大的 int32 值。

我用我的电脑试过了,对于一个 (300,300,200) 数组,大约需要 1 秒才能找到值。

关于python - 在标签图中的段周围获取边界框的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com