【发布时间】:2016-01-16 17:17:51
【问题描述】:
我想将 numpy 数组的 rgb 值替换为单个整数表示。我的代码可以工作,但是太慢了,我现在正在迭代每个元素。我可以加快速度吗?我是 numpy 的新手。
from skimage import io
# dictionary of color codes for my rgb values
_color_codes = {
(255, 200, 100): 1,
(223, 219, 212): 2,
...
}
# get the corresponding color code for the rgb vector supplied
def replace_rgb_val(rgb_v):
rgb_triple = (rgb_v[0], rgb_v[1], rgb_v[2])
if rgb_triple in _color_codes:
return _color_codes[rgb_triple]
else:
return -1
# function to replace, this is where I iterate
def img_array_to_single_val(arr):
return np.array([[replace_rgb_val(arr[i][j]) for j in range(arr.shape[1])] for i in range(arr.shape[0])])
# my images are square so the shape of the array is (n,n,3)
# I want to change the arrays to (n,n,1)
img_arr = io.imread(filename)
# this takes from ~5-10 seconds, too slow!
result = img_array_to_single_val(img_arr)
【问题讨论】:
标签: python arrays numpy image-processing rgb