Last active
November 9, 2024 20:58
-
-
Save Quasimondo/c3590226c924a06b276d606f4f189639 to your computer and use it in GitHub Desktop.
RGB to YUV and YUV to RGB conversion for Numpy
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
import numpy as np | |
#input is a RGB numpy array with shape (height,width,3), can be uint,int, float or double, values expected in the range 0..255 | |
#output is a double YUV numpy array with shape (height,width,3), values in the range 0..255 | |
def RGB2YUV( rgb ): | |
m = np.array([[ 0.29900, -0.16874, 0.50000], | |
[0.58700, -0.33126, -0.41869], | |
[ 0.11400, 0.50000, -0.08131]]) | |
yuv = np.dot(rgb,m) | |
yuv[:,:,1:]+=128.0 | |
return yuv | |
#input is an YUV numpy array with shape (height,width,3) can be uint,int, float or double, values expected in the range 0..255 | |
#output is a double RGB numpy array with shape (height,width,3), values in the range 0..255 | |
def YUV2RGB( yuv ): | |
m = np.array([[ 1.0, 1.0, 1.0], | |
[-0.000007154783816076815, -0.3441331386566162, 1.7720025777816772], | |
[ 1.4019975662231445, -0.7141380310058594 , 0.00001542569043522235] ]) | |
rgb = np.dot(yuv,m) | |
rgb[:,:,0]-=179.45477266423404 | |
rgb[:,:,1]+=135.45870971679688 | |
rgb[:,:,2]-=226.8183044444304 | |
return rgb |
🥳
i get results for YUV2RGB out of 0,255
def YUV2RGB( yuv ):
m = np.array([[ 1.0, 1.0, 1.0],
[-0.000007154783816076815, -0.3441331386566162, 1.7720025777816772],
[ 1.4019975662231445, -0.7141380310058594 , 0.00001542569043522235] ])
rgb = np.dot(yuv,m)
rgb[:,:,0]-=179.45477266423404
rgb[:,:,1]+=135.45870971679688
rgb[:,:,2]-=226.8183044444304
rgb = rgb.clip(0,255)
return rgb
This did not work for me, I had to make my own version: https://gist.github.com/awoimbee/83c0a409e8aeb1700d999505a5ee9bf7
I calculated the matrix's components from OpenCV's constants.
Wonderful! Please mark it as BT.601 colorspace.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Its public domain.