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

Time:03-17

Given a binary image, what is the fastest and Pythonic way to convert the image to RGB and then modify it's pixels?

I have these two ways but they don't feel good to me

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)
    

Below is the Image

enter image description here

CodePudding user response:

I suppose the most simple way is this:

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)

By the way, similar approach can be found enter image description here

Read more about palette images here.

  • Related