阅读 72

delphi图像处理之灰度处理

---------------开发环境D7

--------------------------

 左边的彩色的是原图,右边的是效果图(点击按钮3)

 

 

-----Unit开始

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, math;

type
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Image2: TImage;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);//RGB三个分量的平均值,把平局值赋值给RGB的三个分量
var
vP:PByteArray;
x,y:Integer;
vBmp:TBitmap;
gray:Integer;
begin
vBmp:=TBitmap.Create;
vBmp.Assign(Image1.Picture.Bitmap);
vBmp.PixelFormat:=pf24bit;//如果Image1.Picture.Bitmap不是24位的真彩BMP图片,请设置这个
for y:=0 to vBmp.Height -1 do
begin
vp:=vbmp.ScanLine[y];
for x:=0 to vBmp.Width-1 do
begin
gray:=(vp[3*x+2]+vp[3*x+1] +vp[3*x]) div 3; //RGB的平均值
vp[3*x+2]:=Byte(gray);
vp[3*x+1]:=Byte(gray);
vp[3*x]:=Byte(gray);
end;
end;
Image2.Picture.Bitmap:=vBmp;
vBmp.Free;
// for
end;

procedure TForm1.Button2Click(Sender: TObject); //RGB三个分量最大值代替原来的的RGB三个分量
var
vP:PByteArray;
x,y:Integer;
vBmp:TBitmap;
gray:Integer;
begin
vBmp:=TBitmap.Create;
vBmp.Assign(Image1.Picture.Bitmap);
vBmp.PixelFormat:=pf24bit;//如果Image1.Picture.Bitmap不是24位的真彩BMP图片,请设置这个
for y:=0 to vBmp.Height -1 do
begin
vp:=vbmp.ScanLine[y];
for x:=0 to vBmp.Width-1 do
begin
gray:=Max(vp[3*x+2],vp[3*x+1]);
gray:=Max(gray,vp[3*x]);

vp[3*x+2]:=Byte(gray);
vp[3*x+1]:=Byte(gray);
vp[3*x]:=Byte(gray);
end;
end;
Image2.Picture.Bitmap:=vBmp;
vBmp.Free;
// for
end;

procedure TForm1.Button3Click(Sender: TObject);
var
vP:PByteArray;
x,y:Integer;
vBmp:TBitmap;
gray:Integer;
begin
vBmp:=TBitmap.Create;
vBmp.Assign(Image1.Picture.Bitmap);
vBmp.PixelFormat:=pf24bit;//如果Image1.Picture.Bitmap不是24位的真彩BMP图片,请设置这个
for y:=0 to vBmp.Height -1 do
begin
vp:=vbmp.ScanLine[y]; //获取每行的像素
for x:=0 to vBmp.Width-1 do
begin
//利用YUV的颜色空间,求出Y的分量 ,公式:y=0.299R+0.587G+0.114B
//按这里把公式处理一下y=0.3R+0.59G+0.11B,再处理y=3/10 R+59/100 G+11/100 B
//Gray:=Round(vp[3*x+2]*0.3+vp[3*x+1]*0.59 +vp[3*x]*0.11);

//也许有人要说我多此一举,我只想说,浮点类型的计算其实比较复杂,这样处理一下,可能更快
//Gray:=Round((vp[3*x+2]*3)/ 10+(vp[3*x+1]*59) / 100 +(vp[3*x]*11) / 100);
//Gray:=(vp[3*x+2]*3) div 10+(vp[3*x+1]*59) div 100 +(vp[3*x]*11) div 100;
Gray:=(77 * vp[3*x+2] + 149 * vp[3*x+1] + 29 * vp[3*x]) shr 8 ;//这个感觉更好
{
解释一下这个shr 8,相当于除以256
77/256约等于0.3
149/256约等于0.58
29/256约等于0.11
}
//24位的真彩,一个像素占三个字节
vp[3*x+2]:=Byte(gray);//R
vp[3*x+1]:=Byte(gray);//G
vp[3*x]:=Byte(gray);//B
end;
end;
Image2.Picture.Bitmap:=vBmp;
vBmp.Free;
// for
end;

end.

 

------Unit结束--

 

原文:https://www.cnblogs.com/dmqhjp/p/15136969.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐