来自 128x512 阵列列表中的图像列表可提高效率



我有一个 128x512 数组的列表,如下所示:

[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32),
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
..., 
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32),
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
..., 

我正在将此数组列表转换为RGB图像列表,到目前为止,我的代码是:

#makes an array of all the images 
image_out = [[] for i in range(len(blue_Rad_list))]
for i in range(len(blue_Rad_list)):
startTime = time.time()
image_arr = [np.int_(np.float_(x/np.amax(blue_Rad_list))*256) for x in blue_Rad_list[i]]
image_out[i] = Image.new('RGB', (width, height))
image_out[i].putdata(np.asarray(image_arr).ravel())

del image_arr[:]
stopTime = time.time()
print(stopTime - startTime)

运行我的代码后,我得到这样的内容:

<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCE90>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCED0>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCF10>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCF50>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCF90>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CDCFD0>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9050>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9090>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE90D0>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9110>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9150>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9190>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE91D0>,
<PIL.Image.Image image mode=RGB size=128x512 at 0x7F47D4CE9210>]

在上面的代码中,blue_Rad_list是 128x512 数组的列表。这段代码有效,但是当有大约 180 个元素时,需要花费大量时间才能为我提供整个图像列表。有没有更有效的方法可以做到这一点。感谢您的任何帮助。

一旦我们进入循环,特别是那些计算繁重的工作,就会执行更少的工作,这里有一种方法使用多暗数组而不是数组列表作为输入。在这个过程中,我们将利用 NumPy 支持的矢量化操作来覆盖所有元素 -

# Convert to 3D array. If you already have the multi-dim array that was used to
# create the list of arrays. Use that instead of imgs
imgs = np.array(blue_Rad_list)
# Perfomr the image conversion operation formerly done within loop
imgs1 = np.int_(np.float_(imgs/np.amax(imgs))*256).reshape(imgs.shape[0],-1)
# Loop through and create list of PIL images
image_out = [[] for i in range(len(blue_Rad_list))]
for i in range(len(imgs)):
image_out[i] = Image.new('RGB', (width, height))
image_out[i].putdata(imgs1[i])

似乎我们可以通过在进入循环之前初始化数据存储来进一步优化,就像这样 -

image_out = [Image.new('RGB', (width, height))]*len(imgs)
for i in range(len(imgs)):
image_out[i].putdata(imgs1[i])

最新更新