NumPy: Concatenate three images (RGB) into one

Writing simple codes isn’t simple. Sometimes writing a very simple function costs you more time than a complex one because you think the code should be very concise considering its simple functionality, which is not always true. In my case this code was that sort of thing.

If you have three images representing three different channels (R, G, and B), you may want to concatenate those three 2D arrays into one 3D array to display or write to an image file. In NumPy, there is a simple way to do this as follows:

# Concatenate three (height, width)s into one (height, width, 3).
def concat_channels(r, g, b):
    assert r.ndim == 2 and g.ndim == 2 and b.ndim == 2
    rgb = (r[..., np.newaxis], g[..., np.newaxis], b[..., np.newaxis])
    return np.concatenate(rgb, axis=-1)
Advertisements
NumPy: Concatenate three images (RGB) into one

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s