最好的方法如下:
function Histogram(image:TImage;x1,y1,x2,y2:integer):string;
var
his: array [0..255] of real;
ihis: array [0..255,1..3] of integer;
sum: longword;
XStart,XEnd,YStart,YEnd,x,y: integer;
sumreal:real;
bmp:TBitmap;
p: PByteArray;
begin
bmp:=TBitmap.Create;
bmp.Assign(image.Picture.Bitmap );
Bmp.PixelFormat := pf24Bit;
XStart:=min(x1,x2);
XEnd:=max(x1,x2);
YStart:=min(y1,y2);
YEnd:=max(y1,y2);
if XStart=XEnd then
begin
XStart:=0;
XEnd:=bmp.Width-1;
end;
if YStart=YEnd then
begin
YStart:=0;
YEnd:=bmp.Height-1;
end;
if XStart<0 then Xstart:=0;
if XEnd>bmp.Width then XEnd:=bmp.Width-1;
if YStart<0 then YStart:=0;
if YEnd>bmp.Height then YEnd:=bmp.Height-1;
for x:=0 to 255 do
for y:=1 to 3 do
ihis[x,y]:=0;
sum:=0;
for y:=YStart to YEnd do
begin
p:=bmp.ScanLine[y];
for x:=XStart to XEnd do
begin
inc(ihis[p[x*3],1]);
inc(ihis[p[x*3+1],2]);
inc(ihis[p[x*3+2],3]);
inc(sum);
end;
end;
for x:=0 to 255 do
his[x]:=(ihis[x,1]+ihis[x,2]+ihis[x,3])/3.0;
sumreal:=0.0;
for x:=0 to 255 do
sumreal:=sumreal+(x*his[x])/sum;
bmp.Free;
result:=floattostr(sumreal);
end;