【发布时间】:2020-07-24 09:52:32
【问题描述】:
我有一个图像保存为形状为[Height, Width, 3] 的numpy 数组,我想根据像素的颜色将每个像素替换为另一个值,因此最终数组的形状为[Height, Weight]。
我的 for 循环解决方案有效,但速度很慢。如何使用 Numpy 矢量化来提高效率?
image = cv2.imread("myimage.png")
result = np.zeros(shape=(image.shape[0], image.shape[1],))
for h in range(0, result.shape[0]):
for w in range(0, result.shape[1]):
result[h, w] = get_new_value(image[h, w])
这里是get_new_value函数:
def get_new_value(array: np.ndarray) -> int:
mapping = {
(0, 0, 0): 0,
(0, 0, 255): 5,
(0, 100, 200): 8,
# ...
}
return mapping[tuple(array)]
【问题讨论】:
-
你能告诉我们你的
get_new_value函数吗? -
映射是否包含 256^3 个值(对于所有像素)?您可以访问和编辑 get_new_value 函数吗?
-
是的,我可以编辑这个函数。该映射包含每个可能的像素值的值。
标签: python numpy vectorization