Created
February 22, 2023 18:28
-
-
Save hipersayanX/f9f5e46fa7f23075df31b8f6b7e2f016 to your computer and use it in GitHub Desktop.
Convert RGB <-> YUV
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
def rgb_y(r, g, b): | |
return ((66 * r + 129 * g + 25 * b + 128) >> 8) + 16 | |
def rgb_u(r, g, b): | |
return ((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128 | |
def rgb_v(r, g, b): | |
return ((112 * r - 94 * g - 18 * b + 128) >> 8) + 128 | |
def yuv_r(y, u, v): | |
r = (298 * (y - 16) + 409 * (v - 128) + 128) >> 8 | |
return min(max(0, r), 255) | |
def yuv_g(y, u, v): | |
g = (298 * (y - 16) - 100 * (u - 128) - 208 * (v - 128) + 128) >> 8 | |
return min(max(0, g), 255) | |
def yuv_b(y, u, v): | |
b = (298 * (y - 16) + 516 * (u - 128) + 128) >> 8 | |
return min(max(0, b), 255) | |
r = 190 | |
g = 0 | |
b = 0 | |
y = rgb_y(r, g, b) | |
u = rgb_u(r, g, b) | |
v = rgb_v(r, g, b) | |
print("RGB({}, {}, {}) -> YUV({}, {}, {})".format(r, g, b, y, u, v)) | |
r = yuv_r(y, u, v) | |
g = yuv_g(y, u, v) | |
b = yuv_b(y, u, v) | |
print("YUV({}, {}, {}) -> RGB({}, {}, {})".format(y, u, v, r, g, b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment