Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active September 24, 2025 06:32
Show Gist options
  • Save yohhoy/dafa5a47dade85d8b40625261af3776a to your computer and use it in GitHub Desktop.
Save yohhoy/dafa5a47dade85d8b40625261af3776a to your computer and use it in GitHub Desktop.
RGB <=> YCbCr(YPbPr) color space conversion
@Vanilagy
Copy link

Color spaces are the most niche, rabbit holey thing ever, I swear

@danigc98
Copy link

They really are. I feel I will never gain my time back from learning this stuff.

@zhanwang-sky
Copy link

e for BT.2020 should be 1.4746, it can be calculated by the following formula:
e = (1 - a) / 0.5,
d = (1 - c) / 0.5

@yohhoy
Copy link
Author

yohhoy commented Jun 8, 2023

e for BT.2020 should be 1.4746,

Fixed. thanks!

@molesmoke
Copy link

Looks like Cb/Cr should be centred around 0.5?

Y  = a * R + b * G + c * B
Cb = (B - Y) / d  + 0.5
Cr = (R - Y) / e + 0.5

@yohhoy
Copy link
Author

yohhoy commented Jan 17, 2024

Chrominance(Chroma) Cb/Cr are defined in the range [-0.5, 0.5].

@molesmoke
Copy link

Oh yup, my bad, I was thinking about it for use in a shader.

@EliCDavis
Copy link

Golang code for those interested

type BT struct {
	A float64
	B float64
	C float64
	D float64
	E float64
}

var (
	BT601  = BT{A: 0.299, B: 0.587, C: 0.114, D: 1.772, E: 1.402}
	BT709  = BT{A: 0.2126, B: 0.7152, C: 0.0722, D: 1.8556, E: 1.5748}
	BT2020 = BT{A: 0.2627, B: 0.6780, C: 0.0593, D: 1.8814, E: 1.4746}
)

func RgbToYCbCr(r, g, b float64, space BT) (y, cb, cr float64) {
	y = space.A*r + space.B*g + space.C*b
	cb = (b - y) / space.D
	cr = (r - y) / space.E
	return
}

func YCbCrToRgb(y, cb, cr float64, space BT) (r, g, b float64) {
	r = y + space.E*cr
	g = y - (space.A*space.E/space.B)*cr - (space.C*space.D/space.B)*cb
	b = y + space.D*cb
	return
}

@Noob-101-8988
Copy link

where the hellyante skibidi sigma is the srgb to ycbcr

@Vanilagy
Copy link

ong ts is actually goated, only took me around 6, 7 tries to get right

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