【问题标题】:Image processing: vectorize numpy array elements substitution图像处理:向量化 numpy 数组元素替换
【发布时间】:2018-10-30 00:38:42
【问题描述】:

代码运行良好,但速度很慢。如何矢量化颜色替换以避免使用 Python for 循环?

processed_image = np.empty(initial_image.shape)
for i, j in np.ndindex(initial_image.shape[:2]):
    l_, a, b = initial_image[i, j, :]
    idx = mapping[a + 128, b + 128]
    a, b = new_colors[tuple(idx)]
    processed_image[i, j] = l_, a, b

我在 CIELAB 空间中有一个图像 initial_image 作为形状 (一些高度,一些宽度,3)的 numpy 数组。我需要通过使用mapping 更改图像的 ab 颜色分量来生成校正图像。 mapping 是一个形状为 (255, 255, 2) 的 numpy 数组。它为我提供了索引,可用于从new_colors 获取更正的 ab 颜色。 new_colors 的形状为 (table height, table width, 2)

使用 scikit-image 的解决方案也会有所帮助。

【问题讨论】:

    标签: python performance numpy image-processing scikit-image


    【解决方案1】:

    您可以使用高级索引:

    # chain the two maps
    chained = new_colors[(*np.moveaxis(mapping, 2, 0),)]
    # split color channels
    c1, *c23 = np.moveaxis(initial_image, 2, 0)
    # add 128
    c23 = *map(np.add, c23, (128, 128)),
    # apply chained map
    processed_image_2 = np.concatenate([c1[..., None], chained[c23]], axis=2)
    

    【讨论】:

    • 对我来说工作速度至少快 100 倍!
    • 这里的None 是指np.newaxis 吗?
    • @SashaTsukanov 是的,它们的意思是一样的。事实上,我认为np.newaxis 只是None 的别名。
    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多