将 PIL 对象转换为 numpy 时发生了什么?
What is happening when converting PIL objects to numpy?
我正在用 [n_images, width, height, 3] 创建一个大的 numpy 数组。
为此,我创建了一个空列表并附加了通过裁剪 RGB 图像并将它们转换为 numpy 数组创建的 numpy 数组。
我在尝试优化我的代码时遇到了一些非常奇怪的事情:
import time
from PIL import Image
im1=Image.open("random_png_image.png")
im2=Image.open("random_png_image.png").convert('RGB')
t1=time.time()
a1=np.asarray(im1)
t2=time.time()
a2=np.asarray(im2)
t3=time.time()
print("Converting to numpy without converting to RGB mode first took: %0,3f ms"%((t2-t1)*1000.0))
print("Converting to numpy after the image was converted to RGB first took: %0,3f ms"%((t3-t2)*1000.0))
我得到了巨大的不同:
- 第一个操作大约 80 毫秒
- 第二次大约 8 毫秒
这是为什么? PIL 在将其转换为 numpy 数组时是否隐含地执行此操作 convert_to_rgb ?如果检查,两个 PIL 对象都具有 RGB 模式,所以很奇怪。有没有办法加快这个过程?我应该怎么做才能优化这个过程?不使用 PIL ?之后将它们转换为数组 ?
来自official documentation for Image.open
:
Opens and identifies the given image file. This is a lazy operation;
the function reads the file header, but the actual image data is not
read from the file until you try to process the data
通过第一个操作,您正在计时从磁盘读取数据的过程。
我正在用 [n_images, width, height, 3] 创建一个大的 numpy 数组。 为此,我创建了一个空列表并附加了通过裁剪 RGB 图像并将它们转换为 numpy 数组创建的 numpy 数组。
我在尝试优化我的代码时遇到了一些非常奇怪的事情:
import time
from PIL import Image
im1=Image.open("random_png_image.png")
im2=Image.open("random_png_image.png").convert('RGB')
t1=time.time()
a1=np.asarray(im1)
t2=time.time()
a2=np.asarray(im2)
t3=time.time()
print("Converting to numpy without converting to RGB mode first took: %0,3f ms"%((t2-t1)*1000.0))
print("Converting to numpy after the image was converted to RGB first took: %0,3f ms"%((t3-t2)*1000.0))
我得到了巨大的不同:
- 第一个操作大约 80 毫秒
- 第二次大约 8 毫秒
这是为什么? PIL 在将其转换为 numpy 数组时是否隐含地执行此操作 convert_to_rgb ?如果检查,两个 PIL 对象都具有 RGB 模式,所以很奇怪。有没有办法加快这个过程?我应该怎么做才能优化这个过程?不使用 PIL ?之后将它们转换为数组 ?
来自official documentation for Image.open
:
Opens and identifies the given image file. This is a lazy operation; the function reads the file header, but the actual image data is not read from the file until you try to process the data
通过第一个操作,您正在计时从磁盘读取数据的过程。