使用標準亮度加權公式 (ITU-R BT.601) 將彩色圖像轉換為灰度圖像的 ColorMatrix 實現。
ColorMatrix1: TColorMatrix = ( (1.0, 0.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 0.0, 1.0) );
ColorMatrix2: TColorMatrix = (
(0.30, 0.30, 0.30, 0.0, 0.0), { R' = 0.30R + 0.30G + 0.30B }
(0.59, 0.59, 0.59, 0.0, 0.0), { G' = 0.59R + 0.59G + 0.59B }
(0.11, 0.11, 0.11, 0.0, 0.0), { B' = 0.11R + 0.11G + 0.11B }
(0.0, 0.0, 0.0, 1.0, 0.0), { A' = A }
(0.0, 0.0, 0.0, 0.0, 1.0)
);
| 標準 | 紅色 | 綠色 | 藍色 | 備註 |
|---|---|---|---|---|
| ITU-R BT.601 (SDTV) | 0.299 | 0.587 | 0.114 | 傳統電視、JPEG、MPEG |
| ITU-R BT.709 (HDTV) | 0.2126 | 0.7152 | 0.0722 | 現代高清標準 |
| 本例近似值 | 0.30 | 0.59 | 0.11 | 簡化整數近似,視覺差異極小 |
const ColorMatrix1, ColorMatrix2: TColorMatrix = ( ... );
procedure TForm1.FormPaint(Sender: TObject);
var g: TGPGraphics; img: TGPImage; ImageAttributes: TGPImageAttributes;
begin
g := TGPGraphics.Create(Canvas.Handle);
img := TGPImage.Create('c:\temp\test.png');
ImageAttributes := TGPImageAttributes.Create;
if CheckBox1.Checked then
ImageAttributes.SetColorMatrix(ColorMatrix2)
else
ImageAttributes.SetColorMatrix(ColorMatrix1);
g.DrawImage(img, MakeRect(4, 4, img.GetWidth, img.GetHeight), 0, 0, img.GetWidth, img.GetHeight, UnitPixel, ImageAttributes);
ImageAttributes.Free; img.Free; g.Free;
end;
procedure TForm1.CheckBox1Click(Sender: TObject); begin Repaint; end;

[0,0,0,1,0])此灰度矩陣是色彩空間轉換的經典案例,理解其權重來源有助於掌握更複雜的色彩科學應用。