使用列表或numpy过滤3D python列表

2024-09-30 01:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python3d列表。更清楚的是,一个列表列表,其中每个列表是一个框的四个角坐标。我必须过滤所有小于给定尺寸的盒子。你知道吗

让我们假设这是python列表。你知道吗

box = [[[4, 4], [4, 8], [8, 8], [8, 4]],
      [[8, 8], [8, 16], [16, 16], [16, 8]],
      [[20,16],[20,20],[24,20],[24,16]]
      ...
      ]

我必须过滤所有长度和宽度小于或等于5的盒子。你知道吗

filtered_box = [[[4, 4], [4, 8], [8, 8], [8, 4]],
                [[20,16],[20,20],[24,20],[24,16]]
               ...
               ]

这是我现在的密码

filtered_box = []
for c in box:
    min_x, min_y = c[0]
    max_x, max_y = c[2]
    if max_x - min_x <= 5 & min_y - max_y <= 5:
        filtered_box.append(c)

这是工作良好,但我需要一个更优化的解决方案。它可以使用numpy并转换回python列表,或者使用列表上的本机python操作。我正在使用python3。你知道吗


Tags: inbox密码列表forif宽度尺寸
2条回答

具有numpy的解决方案可能如下所示:

filtered_array = array[
    (np.abs(array[:, 0, 0] - array[:, 3, 0]) < 5) &
    (np.abs(array[:, 0, 1] - array[:, 3, 1]) < 5), :, :]

其中array = np.array(box)。你知道吗

如果您已经准备好了数据(numpy数组),我猜这个解决方案将比普通python快得多。将数据从python列表转换为numpy数组将抵消任何时间增益。你知道吗

此列表替换for循环结构:

import numpy as np

box = [
      [[4, 4], [4, 8], [8, 8], [8, 4]],
      [[8, 8], [8, 16], [16, 16], [16, 8]],
      [[20,16],[20,20],[24,20],[24,16]]
      ]

box = np.array(box) # convert to numpy array

# one-liner
filtered = [i for i in box if np.ptp(i[:,0]) <= 5 and np.ptp(i[:,1]) <= 5]

filtered = np.array(filtered) # if you want to convert to a numpy array

相关问题 更多 >

    热门问题