【发布时间】:2016-03-11 13:10:36
【问题描述】:
我有以下代码可以按预期工作,但我很好奇循环是否可以用本机 numpy 函数/方法替换以获得更好的性能。我所拥有的是一个保存 RGB 值的数组,我用作查找表和两个保存灰度值(0-255)的二维数组。这两个数组的每个值对应查找表的一个轴的值。
如前所述,真正好的是摆脱 python 中的(慢)循环并使用更快的 numpy 方法。
#!/usr/bin/env python3
from PIL import Image
import numpy as np
dim = (2000, 2000)
rows, cols = dim
# holding a 256x256 RGB color lookup table
color_map = np.random.random_integers(0, 255, (256,256,3))
# image 1 greyscale values
color_map_idx_row = np.random.randint(0, 255, dim)
# image 2 greyscale values
color_map_idx_col = np.random.randint(0, 255, dim)
# output image data
result_data = np.zeros((rows, cols, 3), dtype=np.uint8)
# is there any built in function in numpy that could
# replace this loop?
# -------------------------------------------------------
for i in range(rows):
for j in range(cols):
row_idx = color_map_idx_row.item(i, j)
col_idx = color_map_idx_col.item(i, j)
rgb_color = color_map[row_idx,col_idx]
result_data[i,j] = rgb_color
img = Image.fromarray(result_data, 'RGB')
img.save('result.png')
【问题讨论】:
-
对不起,我没有找到这个。我检查了一下...谢谢