Skip to content

Instantly share code, notes, and snippets.

@LuoZijun
Last active August 1, 2021 07:12
Show Gist options
  • Save LuoZijun/518608a83dd14a8c786593142b85a8c1 to your computer and use it in GitHub Desktop.
Save LuoZijun/518608a83dd14a8c786593142b85a8c1 to your computer and use it in GitHub Desktop.
RGB to YCbCr
def rgb_to_ycbcr(r, g, b):
assert(255>=r)
assert(255>=g)
assert(255>=b)
y = 0.299*r + 0.587*g + 0.114*b
cb = 128 - 0.168736*r - 0.331364*g + 0.5*b
cr = 128 + 0.5*r - 0.418688*g - 0.081312*b
return int(y), int(cb), int(cr)
fn rgb_to_ycbcr(r: u8, g: u8, b: u8) -> (f64, f64, f64) {
let r = r as f64;
let g = g as f64;
let b = b as f64;
let y : f64 = 0.299*r + 0.587*g + 0.114*b;
let cb: f64 = 128.0 - 0.168736*r - 0.331364*g + 0.5*b;
let cr: f64 = 128.0 + 0.5*r - 0.418688*g - 0.081312*b;
(y, cb, cr)
}
def ycbcr_to_rgb(y, cb, cr):
r = y + 1.402 * (cr-128)
g = y - 0.34414 * (cb-128) - 0.71414 * (cr-128)
b = y + 1.772 * (cb-128)
if b < 255: b += 1
return int(r), int(g), int(b)
fn ycbcr_to_rgb(y: f64, cb: f64, cr: f64) -> (u8, u8, u8) {
let r: f64 = y + 1.402 * (cr-128.0);
let g: f64 = y - 0.34414 * (cb-128.0) - 0.71414 * (cr-128.0);
let mut b: f64 = y + 1.772 * (cb-128.0);
if b < 255.0f64 {
b += 1.0;
}
(r as u8, g as u8, b as u8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment