使用 Numpy / Opencv / scikit-image 更改 RGB 图像像素值的最快方法是什么

What is the Fastest way to change pixel values of an RGB image using Numpy / Opencv / scikit-image

给定一张二值图像,将图像转换为 RGB 然后修改其像素的最快 Pythonic 方法是什么?

我有这两种方法,但我觉得不太好

def get_mask(rgb_image_path):
    mask = np.array(Image.open(rgb_image_path).convert('L'), dtype = np.float32) # Mask should be Grayscale so each value is either 0 or 255
    mask[mask == 255.0] = 1.0 # whereever there is 255, convert it to 1: (1 == 255 == White)
    return mask


def approach1(mask):
    mask = np.logical_not(mask)
    mask = mask.astype(np.uint8)

    mask = mask*255
    red = mask.copy()
    blue = mask.copy()
    green = mask.copy()

    red[red == 0] = 26
    blue[blue == 0] = 237
    green[green == 0] = 160
    mask = np.stack([red, blue, green], axis = -1)
    plt.imshow(mask)
    
def approach2(mask):
    mask = np.logical_not(mask)
    mask = mask.astype(np.uint8)
    
    mask = np.stack([mask,mask,mask], axis = -1)
    mask = mask*255

    width,height, channels = mask.shape
    for i in range(width):
        for j in range(height):
            if mask[i][j][0] == 0:
                mask[i][j] = (26,237,160)

    plt.imshow(mask)
    

下面是图片

我想最简单的方法是这样的:

def mask_coloring(mask):
    expected_color = (26, 237, 160)
    color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)
    color_mask[mask == 255.0, :] = expected_color
    plt.imshow(color_mask)

顺便说一下,可以找到类似的方法here

最简单的方法是利用您只有并且只想要 2 种颜色这一事实,并使用不需要您遍历所有颜色的快速 space-efficient 调色板图像像素,或者每个像素存储 3 个字节:

from PIL import Image

# Open your image
im = Image.open('oqX2g.gif')

# Create a new palette where the 1st entry is black (0,0,0) and the 2nd is your colour (26,237,160) then pad out to 256 RGB entries
palette = [0,0,0] + [26,237,160] + [0,0,0] * 254

# Put palette into image and save
im.putpalette(palette)
im.save('result.png')

阅读有关调色板图像的更多信息


如果你想让黑色背景变成洋红色,前景变成绿色怎么办?哦,你想要它作为 RGB Numpy 数组吗? 只需更改调色板并转换:

from PIL import Image
import numpy as np

# Open your image, push in new palette
im = Image.open('oqX2g.gif')
palette = [255,0,255] + [0,255,0] + [0,0,0] * 254
im.putpalette(palette)

# Make RGB Numpy array
na = np.array(im.convert('RGB'))