Last active
April 23, 2018 05:31
-
-
Save davidnvq/3380514c646d14c77075d6962ca47898 to your computer and use it in GitHub Desktop.
Converting RGB to BGR for image data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
""" | |
In this gist, I demonstrate the simple ways to | |
convert between 2 colorspace representation of images | |
mutually(RGB, BGR). | |
""" | |
CONVERSION_ORDER = [2, 1, 0] | |
def convert_channel(img): | |
""" | |
Convert an image in the first convention to | |
the second convention. | |
We just need to swap the order of the 1st and 3rd channel. | |
- An image is represented by [height, width, channels] | |
For a color image, [height, width, 3] | |
The last dimension is reserved for color channels (R,G,B) or | |
(B,G,R) in cv2 convention. | |
""" | |
# Reverse the order in the last dimension | |
return img[...,::-1] | |
# or | |
return img[...,CONVERSION_ORDER] | |
# or | |
return np.stack([img[..., CONVERSION_ORDER[0], | |
img[..., CONVERSION_ORDER[1], | |
img[..., CONVERSION_ORDER[2]], | |
axis=-1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment