Last active
June 2, 2023 14:33
-
-
Save awoimbee/83c0a409e8aeb1700d999505a5ee9bf7 to your computer and use it in GitHub Desktop.
OpenCV's RGB2YUV & YUV2RGB conversions for Numpy, for values between [0, 1] or [0, 255]
This file contains 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
# The coefficients were taken from OpenCV https://github.com/opencv/opencv | |
# I'm not sure if the values should be clipped, in my (limited) testing it looks alright | |
# but don't hesitate to add rgb.clip(0, 1, rgb) & yuv.clip(0, 1, yuv) | |
# | |
# Input for these functions is a numpy array with shape (height, width, 3) | |
# Change '+= 0.5' to '+= 127.5' & '-= 0.5' to '-= 127.5' for values in range [0, 255] | |
def rgb2yuv(rgb): | |
m = np.array([ | |
[0.29900, -0.147108, 0.614777], | |
[0.58700, -0.288804, -0.514799], | |
[0.11400, 0.435912, -0.099978] | |
]) | |
yuv = np.dot(rgb, m) | |
yuv[:,:,1:] += 0.5 | |
return yuv | |
def yuv2rgb(yuv): | |
m = np.array([ | |
[1.000, 1.000, 1.000], | |
[0.000, -0.394, 2.032], | |
[1.140, -0.581, 0.000], | |
]) | |
yuv[:, :, 1:] -= 0.5 | |
rgb = np.dot(yuv, m) | |
return rgb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment