使用 Python 加快从文件填充 3D 数组的速度



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

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

现在我:

  1. 初始化带零的 3D 数组。

  2. 逐行读取文件。

  3. 对于每行,仅取前 3 个元素 (x,y,z(。

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

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

  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

也许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 是根据文档的字节计数

最新更新