【问题标题】:speed up 3d array fill from file using python使用 python 从文件中加速 3d 数组填充
【发布时间】:2019-04-19 12:27:27
【问题描述】:

我正在使用 python 填充一个 3d 数组,每个数组元素代表一个像素。

我需要插入到数组中的值存储在一个非常大的 .txt 文件中 (5600 万行,格式如下 - x,y,z,r,g,b)

现在我:

  1. 用零初始化 3d 数组。

  2. 逐行读取文件。

  3. 每行只取前 3 个元素 (x,y,z)。

  4. 根据 x 和 y 计算数组 location[i,j]

  5. 如果 array[i,j] 等于 0 --> 插入从文件中读取的行

  6. 否则跳到下一个文件

对于 5600 万行,我大约需要 160 秒

如何使用 python 加快速度? (gpu 可用)

array = np.zeros((height, width), dtype=np.float32)

with open(point_cloud_file) as pc_file:
    while True:
        line = pc_file.readline()
        if not line:
            break
        nof_read_lines += 1

        new_line = line.strip()
        try:
            x, y, z, _, _, _ = new_line.split(',')
        except:
            nof_skipped_lines += 1
            continue

        # insert to array
        pixel_x = some calculation
        pixel_y = some calculation
        if 0 < pixel_x < width and 0 < pixel_y < height:
            if array[int(pixel_y), int(pixel_x), 0] == 0:
                array[int(pixel_y), int(pixel_x), :] = x, y, z
            else:
                nof_skipped_lines += 1  # pixel already filled with values

【问题讨论】:

    标签: python gpu numba point-clouds numba-pro


    【解决方案1】:

    也许 readlines() 在这种情况下会有所帮助 此示例一次读取所有行并将整个文件加载到内存中:

    with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass
    

    但您正在处理大型文本文件,因此您可以限制每个循环中的缓冲区使用率

    with open('foo') as f:
        while True:
            lines = f.readlines(8192)
            if not lines:
                break
            for line in lines:
                pass
    

    file.readlines([sizehint]) sizehint 是根据文档的字节数

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2017-07-10
      • 2012-09-06
      相关资源
      最近更新 更多