使用python加速从文件填充3d数组

问题描述 投票:-2回答:1

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

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

我现在:

  1. 初始化3d数组与零。
  2. 逐行读取文件。
  3. 对于每一行只占前三个元素(x,y,z)。
  4. 从x和y计算数组位置[i,j]
  5. 如果array [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
python gpu numba point-clouds numba-pro
1个回答
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是字节数

© www.soinside.com 2019 - 2024. All rights reserved.