【问题标题】:Replace corresponding white pixels from one image with RGB pixels from another image用另一幅图像中的 RGB 像素替换一幅图像中对应的白色像素
【发布时间】:2021-10-29 17:49:45
【问题描述】:

我有 2 张图像 - 其中一张是二值化的,即每个像素是黑色或白色,另一张是标准 RGB 图像。两张图片大小相同。对于第一张图像中的所有白色像素,我想获取 RGB 图像中的相应像素并将它们附加到白色像素的位置。如何在 Python 中做到这一点?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用二值化图像作为像素坐标的二值索引:

    import numpy as np
    
    my_source_image = np.random.randint(0, 255, (480,640,3), np.uint8) # defined somewhere, assumed to have shape [H,W,3]
    my_binarized_image = np.random.randint(0, 2, (480,640), np.uint8) # defined somewhere, assumed to have shape [H,W]
    pixel_idx = my_binarized_image.astype(bool)
    my_dest_image = np.zeros_like(my_source_image)
    my_dest_image[pixel_idx,:] = my_source_image[pixel_idx]
    

    请注意,我将目标图像定义为全零(如果您想要不同的背景颜色,只需初始化为颜色值),然后填充相关像素,而不是像您看到的那样重复使用 my_binarized_image你的问题,因为目标图像需要三个通道,而二值化图像只有一个。

    或者,只要“背景”颜色为黑色,您就可以避免预分配第二张图像,而只需将第一张图像中的像素清零:

    my_dest_image = my_source_image * pixel_idx[...,None]
    

    [...,None]pixel_idx 的末尾添加了一个额外的维度,以使逐像素乘法成为可能)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-19
      • 2019-02-27
      • 2018-03-28
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2018-09-28
      • 2020-03-30
      相关资源
      最近更新 更多