Mengubah Citra Warna ke Greyscale
Proses awal yang banyak dilakukan dalam image processing adalah mengubah citra berwarna menjadi citra grey-scale. Untuk membuat citra berwarna menjadi citra dengan greyscale (abu-abu) maka nilai warna ditiap piksel citra kita manipulasi menggunakan rumus berikut:
atau
atau bisa gunakan yang ini
Jika dituliskan dalam bentuk potongan kode pada delphi akan tampak seperti ini
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
procedure TForm1.BitBtn1Click(Sender: TObject); brs, kol : Integer; color : Longint; r,g,b,clr : Byte; rgb1 : array [0..2] of integer; begin Image2.Picture.Bitmap := Image1.Picture.Bitmap; for kol := 0 to Image2.Picture.Bitmap.Height-1 do begin Application.ProcessMessages; for brs := 0 to Image2.Picture.Bitmap.Width-1 do begin color := ColorToRGB(Image2.Picture.Bitmap.Canvas.Pixels[brs,kol]); //---mengambil warna per piksel r := GetRValue(color); g := GetgValue(color); b := GetbValue(color); clr := ((r+g+b)div 3); //****Rumus 1 //clr := round((0.2989*r)+(0.5870*g)+(0.1140*b)); //****Rumus 2 rgb1[0]:= r; rgb1[1]:= g; rgb1[2]:= b; //clr := MaxIntValue(rgb1); //****Rumus 3<br> Image2.Picture.Bitmap.Canvas.Pixels[brs,kol] := RGB(clr,clr,clr); end; end; end; |
Baris 18 dan 22 menunjukkan pemakaian ketiga rumus diatas, untuk sementara dinon-aktifkan, jika ingin mengaktifkannya tinggal menghapus tanda comment “//”.
Atau jika menggunakan metode Scanline kodenya nampak seperti berikut.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
procedure TForm1.Button4Click(Sender: TObject); var brs, kol, r : Integer; clr : longint; temp : PByteArray; rgb1 : array [0..2] of Integer; begin Image2.Picture.Bitmap := Image1.Picture.Bitmap; Image2.Picture.Bitmap.PixelFormat := pf24bit; for brs := 0 to Image7.Picture.Bitmap.Height-1 do begin temp := Image2.Picture.Bitmap.ScanLine[brs]; Application.ProcessMessages; kol := 0; repeat clr :=((temp[kol])+(temp[kol+1])+(temp[kol+2]))div 3; //clr :=round((0.1140*temp[kol])+(0.5870*temp[kol+1])+(0.2989*temp[kol+2])); Rgb1[0] := temp[kol]; Rgb1[1] := temp[kol+1]; Rgb1[2] := temp[kol+2]; //clr := MaxIntValue(rgb1); for r:=0 to 2 do temp[kol+r] := clr; inc(kol,3); until kol >= 3*Image2.Picture.Bitmap.Width-1; //---format piksel 24bit(3x8bit)'R=8bit,G=8bit,B=8 bit end; Image2.Invalidate; end; |
Download (source code):
Image Processing – Greyscale.rar
Referensi :
[1] Wikipedia
[2] http://imageprocessingindelphi.blogspot.com/