Skip to content

Instantly share code, notes, and snippets.

@Quasimondo
Last active November 9, 2024 20:58
Show Gist options
  • Save Quasimondo/c3590226c924a06b276d606f4f189639 to your computer and use it in GitHub Desktop.
Save Quasimondo/c3590226c924a06b276d606f4f189639 to your computer and use it in GitHub Desktop.
RGB to YUV and YUV to RGB conversion for Numpy
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
@emilwallner
Copy link

This is excellent! Is it possible to add a license to this snippet?

@Quasimondo
Copy link
Author

Its public domain.

@emilwallner
Copy link

🥳

@eyaler
Copy link

eyaler commented Nov 11, 2019

i get results for YUV2RGB out of 0,255

@thiesmoeller
Copy link

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

@awoimbee
Copy link

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.

@faymek
Copy link

faymek commented Jul 5, 2024

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