Skip to content

Instantly share code, notes, and snippets.

@Cynosphere
Created November 10, 2019 23:47
Show Gist options
  • Save Cynosphere/1f25b0307d50a9360d216a09c3f2d7c5 to your computer and use it in GitHub Desktop.
Save Cynosphere/1f25b0307d50a9360d216a09c3f2d7c5 to your computer and use it in GitHub Desktop.
GLua/Lua RGB <--> YCbCr Color Space Conversions
local function RGBToYCbCr(r, g, b)
local Y = 0.299 * r + 0.587 * g + 0.114 * b
local Cb = -0.169 * r - 0.331 * g + 0.500 * b + 128
local Cr = 0.500 * r - 0.419 * g - 0.081 * b + 128
return Y, Cb, Cr
end
local function YCbCrToRGB(Y, Cb, Cr)
local r = 1 * Y + 0 * (Cb - 128) + 1.4 * (Cr - 128)
local g = 1 * Y - 0.343 * (Cb - 128) - 0.711 * (Cr - 128)
local b = 1 * Y + 1.765 * (Cb - 128) + 0 * (Cr - 128)
return r, g, b
end
@Cynosphere
Copy link
Author

Use case:

local function RGBToYCbCr(r, g, b)
    local Y  =  0.299 * r + 0.587 * g + 0.114 * b
    local Cb = -0.169 * r - 0.331 * g + 0.500 * b + 128
    local Cr =  0.500 * r - 0.419 * g - 0.081 * b + 128

    return Y, Cb, Cr
end
local function YCbCrToRGB(Y, Cb, Cr)
    local r = 1 * Y + 0 * (Cb - 128) + 1.4 * (Cr - 128)
    local g = 1 * Y - 0.343 * (Cb - 128) - 0.711 * (Cr - 128)
    local b = 1 * Y + 1.765 * (Cb - 128) + 0 * (Cr - 128)

    return r, g, b
end

local function Intersect(a, b, value)
    return a + (b - a) * value
end

function IntersectColor(a, b, value)
    local Y1, Cb1, Cr1 = RGBToYCbCr(a.r,a.g,a.b)
    local Y2, Cb2, Cr2 = RGBToYCbCr(b.r,b.g,b.b)

    local r_, g_, b_ = Intersect(Y1, Y2, value), Intersect(Cb1, Cb2, value), Intersect(Cr1, Cr2, value)

    local R, G, B = YCbCrToRGB(r_, g_, b_)
    return Color(R, G, B)
end

Demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment