1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // RGBToYCbCr converts an RGB triple to a Y'CbCr triple.
8 func RGBToYCbCr(r
, g
, b
uint8) (uint8, uint8, uint8) {
9 // The JFIF specification says:
10 // Y' = 0.2990*R + 0.5870*G + 0.1140*B
11 // Cb = -0.1687*R - 0.3313*G + 0.5000*B + 128
12 // Cr = 0.5000*R - 0.4187*G - 0.0813*B + 128
13 // http://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.
17 yy
:= (19595*r1
+ 38470*g1
+ 7471*b1
+ 1<<15) >> 16
18 cb
:= (-11056*r1
- 21712*g1
+ 32768*b1
+ 257<<15) >> 16
19 cr
:= (32768*r1
- 27440*g1
- 5328*b1
+ 257<<15) >> 16
35 return uint8(yy
), uint8(cb
), uint8(cr
)
38 // YCbCrToRGB converts a Y'CbCr triple to an RGB triple.
39 func YCbCrToRGB(y
, cb
, cr
uint8) (uint8, uint8, uint8) {
40 // The JFIF specification says:
41 // R = Y' + 1.40200*(Cr-128)
42 // G = Y' - 0.34414*(Cb-128) - 0.71414*(Cr-128)
43 // B = Y' + 1.77200*(Cb-128)
44 // http://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.
45 yy1
:= int(y
)<<16 + 1<<15
48 r
:= (yy1
+ 91881*cr1
) >> 16
49 g
:= (yy1
- 22554*cb1
- 46802*cr1
) >> 16
50 b
:= (yy1
+ 116130*cb1
) >> 16
66 return uint8(r
), uint8(g
), uint8(b
)
69 // YCbCr represents a fully opaque 24-bit Y'CbCr color, having 8 bits each for
70 // one luma and two chroma components.
72 // JPEG, VP8, the MPEG family and other codecs use this color model. Such
73 // codecs often use the terms YUV and Y'CbCr interchangeably, but strictly
74 // speaking, the term YUV applies only to analog video signals, and Y' (luma)
75 // is Y (luminance) after applying gamma correction.
77 // Conversion between RGB and Y'CbCr is lossy and there are multiple, slightly
78 // different formulae for converting between the two. This package follows
79 // the JFIF specification at http://www.w3.org/Graphics/JPEG/jfif3.pdf.
84 func (c YCbCr
) RGBA() (uint32, uint32, uint32, uint32) {
85 r
, g
, b
:= YCbCrToRGB(c
.Y
, c
.Cb
, c
.Cr
)
86 return uint32(r
) * 0x101, uint32(g
) * 0x101, uint32(b
) * 0x101, 0xffff
89 // YCbCrModel is the Model for Y'CbCr colors.
90 var YCbCrModel Model
= ModelFunc(yCbCrModel
)
92 func yCbCrModel(c Color
) Color
{
93 if _
, ok
:= c
.(YCbCr
); ok
{
96 r
, g
, b
, _
:= c
.RGBA()
97 y
, u
, v
:= RGBToYCbCr(uint8(r
>>8), uint8(g
>>8), uint8(b
>>8))