Python 将 PIL 图像转换为 numpy 数组非常慢

Pra*_*oya 6 python opencv numpy computer-vision tensorflow

我正在评估开放 cv 视频帧上的 Tensorflow 模型。我需要将传入的 PIL 图像重塑为重塑的 numpy 数组,以便我可以对其进行推理。但是我看到在我的笔记本电脑上将 PIL 图像转换为 numpy 数组大约需要 900 多毫秒,内存为 16 GiB 和 2.6 GHz Intel Core i7 处理器。我需要将其缩短到几毫秒,以便我可以在我的相机上每秒处理多个帧。

谁能建议如何使以下方法运行得更快?

def load_image_into_numpy_array(pil_image):
    (im_width, im_height) = pil_image.size
    data = pil_image.getdata()

    data_array = np.array(data)

    return data_array.reshape((im_height, im_width, 3)).astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)

在进一步的检测中,我意识到这np.array(data)占用了大部分时间......接近 900+ 毫秒。所以将图像数据转换为 numpy 数组才是真正的罪魁祸首。

unl*_*lut 8

您可以让 numpy 处理转换而不是重塑自己。

def pil_image_to_numpy_array(pil_image):
    return np.asarray(pil_image)  
Run Code Online (Sandbox Code Playgroud)

您正在将图像转换为(高度、宽度、通道)格式。这是对 PIL 图像执行的默认转换 numpy.asarray 函数,因此不需要显式整形。

  • PIL 使用(宽度,高度)顺序 https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#attributes,而 numpy 使用这里提到的(高度,宽度)https://stackoverflow.com /questions/43272848/what-is-dimension-order-of-numpy-shape-for-image-data。 (2认同)