How to extract R, G, B values ​​with numpy into separate arrays

Suppose I have an image with some dimension (1920, 1080, 3), I want to extract the values ​​of R, G, B into separate arrays R , G, B. I tried to do it like

for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            B = np.append(B, image[i, j][0])
            G = np.append(G, image[i, j][1])
            R = np.append(R, image[i, j][2])

But, as expected, it is very slow. How can I do this using numpy in an inline function?

+6
source share
3 answers

If you want to use it in OpenCV, then you can use cv2.split(), bearing in mind the channels of your image:

b, g, r    = cv2.split(image) # For BGR image
b, g, r, a = cv2.split(image) # for BGRA image

Or, if you might like the direct numpy format, you can use directly [which seems more efficient according to @igaurav comments]

b, g, r    = image[:, :, 0], image[:, :, 1], image[:, :, 2] # For RGB image
b, g, r, a = image[:, :, 0], image[:, :, 1], image[:, :, 2], image[:, :, 3] # for BGRA image

np.shape[2] .

+12

dsplit it.

import numpy as np

def channelSplit(image):
    return np.dsplit(image,image.shape[-1])

[B,G,R]=channelSplit(image)

RGB RGBA.

+6

:

def split_channels(im: np.ndarray):
    assert len(im.shape) == 3 and im.shape[-1] == 3
    return np.squeeze(np.split(im, im.shape[-1], -1), axis=-1)

Note that the TG41 itself is not enough and you will get an image (M, N, 1). But if you want to have (M, N), then it squeezeworks.

You can delete assertif you have other cases.

0
source

Source: https://habr.com/ru/post/1665960/


All Articles