首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

再學 GDI+ [91]:TGPImage 灰度轉換 - ColorMatrix 亮度加權公式

     編輯:Delphi

使用標準亮度加權公式 (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.2990.5870.114傳統電視、JPEG、MPEG
ITU-R BT.709 (HDTV)0.21260.71520.0722現代高清標準
本例近似值0.300.590.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.59),紅色次之 (~0.30),藍色最低 (~0.11)
  • 三通道輸出相同值 (R'=G'=B') 即形成灰度
  • Alpha 通道保持不變 (第 4 行 [0,0,0,1,0])
  • 矩陣乘法在 GPU 管線中極速並行執行

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved