如何编程实现RGB图的灰度化.(50分)

  • 主题发起人 主题发起人 roger_ting
  • 开始时间 开始时间
R

roger_ting

Unregistered / Unconfirmed
GUEST, unregistred user!
编程将RGB图像(如一幅彩色JPG)变成灰度图!
 
将一幅图片转化成灰度图,具体来说应该分为以下几步:
1.提取图片的每一个象素的值,然后建立三个数据表,1->G 2->R 3->B.
2.为每一种颜色值建立一附图.
方法如下:
若源图一点为 (R100,G200,B210),这相应的三附图的点颜色为1_(100,100,100), 2_(200,200,200),3_(210,210,210).



上面是基于图片在屏幕上的方法,如果你的图片是文件就简单多了,在读文件时只分别读RGB,再写屏就可以了.
 
type
TFColor = record
b,g,r:Byte
end;

PFColor =^TFColor;

procedure Gray(srcBmp,DstBmp:TBitMap);
var
x,y: Integer;
Gr: Byte;
incRow,Gap: integer;
DstTmp,SrcTmp: PFColor;
SrcBmInfo,DstBmInfo: TBitmapInfo;
SrcBmHeader,DstBmHeader: TBitmapInfoHeader;
width,height,Size: integer;
SrcBits,DstBits: pointer;
mDC: Integer;
begin
Width:=SrcBmp.Width;
Height:=SrcBmp.Height;
Size:=((Width*3)+(Width mod 4))*Height;
incRow:=((Width*3)+(Width mod 4));
Gap:=Width mod 4;
DstBmp.Assign(SrcBmp);//这句可要可不要,看情况定
getMem(srcBits,size);
getMem(DstBits,size);
with SrcbmHeader do begin
biSize:=SizeOf(SrcbmHeader);
biWidth:=Width;
biHeight:=-Height;
biPlanes:=1;
biBitCount:=24;
biCompression:=BI_RGB;
end;
SrcbmInfo.bmiHeader:=srcbmHeader;

with DstbmHeader do begin
biSize:=SizeOf(DstbmHeader);
biWidth:=Width;
biHeight:=-Height;
biPlanes:=1;
biBitCount:=24;
biCompression:=BI_RGB;
end;
DstbmInfo.bmiHeader:=DstbmHeader;

try
mDC:=GetDC(0);
GetDIBits(mDC,srcBmp.Handle,0,Height,srcBits,srcbmInfo,DIB_RGB_COLORS);

DstTmp:=DstBits;
for y:=0 to Height-1 do begin
for x:=0 to Width-1 do begin
SrcTmp:=pointer(integer(SrcBits)+(y*IncRow+x*3));
Gr := HiByte(SrcTmp^.r * 77 + SrcTmp^.g * 151 + SrcTmp^.b * 28);
DstTmp^.r:=Gr;
DstTmp^.g:=Gr;
DstTmp^.b:=Gr;
Inc(DstTmp);
end;
DstTmp:=Pointer(Integer(DstTmp)+Gap);
end;
SetDIBits(mDC,DstBmp.Handle,0,Height,DstBits,DstbmInfo,DIB_RGB_COLORS);
ReleaseDC(0,mDC);
finally
freemem(SrcBits);
freemem(DstBits);
end;
end;

其中GetDIBBits和SetDIBBits函数可以看API帮助.这个方法与显存有关,
如果你的显存不够大,大图象就处理不,600X600的图象需要
600x600x3=1080000Bytes的显存.
 
delphi 光盘的 /Info/Extras/Jpeg/test/
 
先转成jpg
C:/Program Files/Borland/Delphi6/Help/Examples/Jpeg/JPEGPROJ.DPR
 
RGB
Grayscale
 
谢谢大家.
cwmdelpher的第二种方法是可行的,第一种对于某些图片好像不行.但是如果给R,G,B分量分别加不同的得出的权值会形成不同的灰色分量,这样形成的灰度图就有不同.能够给出相应的理论基础,或者说那种才算是最优的?
稍后给大家分数.
 
接受答案了.
 
后退
顶部