TCanvas::Pixels[x][y] 存取單像素極慢 (每次函數呼叫、顏色轉換)。高效能做法:
ScanLine[y] 取得行指標。BYTE* 陣列 (BGR 順序,24-bit 為 3 bytes/pixel)。Assign 回顯示控件。struct RGB { BYTE r, g, b; };
RGB** rgb; // [width][height] 或扁平化一維陣列
Graphics::TBitmap* bmpWork; // 暫存結果位圖
void __fastcall TForm1::LoadImageToArray()
{
int w = Image1->Picture->Width;
int h = Image1->Picture->Height;
rgb = new RGB*[w];
for (int i=0;iPicture->Bitmap->ScanLine[y];
for (int x=0; xWidth = w; bmpWork->Height = h;
bmpWork->PixelFormat = pf24bit;
}
大多數空域濾鏡可表示為 3x3 核矩陣 K[3][3],輸出像素 = Σ鄰域像素 × 核權重 / 除數 (歸一化),再鉗制至 [0,255]。
| 效果 | 核矩陣 (K) | 除數 |
|---|---|---|
| 柔化 | 全 1 (中心可加大) | 9 (或 10, 16) |
| 銳化 | [[0,-1,0],[-1,5,-1],[0,-1,0]] | 1 |
| 浮雕 | [[-2,-1,0],[-1,1,1],[0,1,2]] | 1 + 128 偏移 |
| 邊緣偵測 | [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]] | 1 |
void ApplyFilter(int kernel[3][3], int divisor, int offset = 0)
{
int w = bmpWork->Width, h = bmpWork->Height;
for (int y=1; yScanLine[y];
for (int x=1; xPicture->Bitmap->Assign(bmpWork);
}
void __fastcall TForm1::btnBlurClick(TObject *Sender) {
int k[3][3] = {{1,1,1},{1,2,1},{1,1,1}}; // 高斯近似
ApplyFilter(k, 10);
}
void __fastcall TForm1::btnSharpenClick(TObject *Sender) {
int k[3][3] = {{0,-1,0},{-1,5,-1},{0,-1,0}};
ApplyFilter(k, 1);
}
void __fastcall TForm1::btnEmbossClick(TObject *Sender) {
int k[3][3] = {{-2,-1,0},{-1,1,1},{0,1,2}};
ApplyFilter(k, 1, 128); // 偏移 128 產生灰底浮雕感
}
__fastcall TForm1::~TForm1() {
for (int i=0;i