关于二值化的问题(有关位深度)
我写的程序如下,该程序产生的是一个24位的黑白灰度图,怎样将其处理为位深为1的二值图呢?
procedure TForm1.Button1Click(Sender: TObject);
var
pBit, pBit1:PByteArray;
x, y, Gray:integer;
bit1Map:TBitMap;
begin
jpegImage := TJpegImage.Create();
jpegImage.LoadFromFile( 'h:\nakedboard.jpg ');
bitMap := TBitMap.Create();
bitMap.Assign(jpegImage);
bitMap.PixelFormat := pf24Bit;
bit1Map := TBitMap.Create();
bit1Map.Width := bitMap.Width;
bit1Map.Height := bitMap.Height;
//bit1Map.Assign(jpegImage);
bit1Map.PixelFormat := pf1Bit;
ZeroMemory(
for y := 0 to bitMap.Height - 1 do
begin
pBit := bitMap.ScanLine[y];
pBit1 := bitMap.ScanLine[y];
for x := 0 to bitMap.Width - 1 do
begin
Gray := Round(pBit[x * 3 + 2] * 0.3 + pBit[x * 3 + 1] * 0.59 + pBit[x * 3] *
0.11);
if Gray > 128 then
begin
pBit[x * 3] := 255;
pBit[x * 3 + 1] := 255;
pBit[x * 3 + 2] := 255;
end
else
begin
pBit[x * 3] := 0;
pBit[x * 3 + 1] := 0;
pBit[x * 3 + 2] := 0;
end
end;
end;
bitMap.SaveToFile( 'h:\n1.bmp ');
bitMap.Free;
bitMap := nil;
bit1Map.Free;
bit1Map := nil;
end;
请给出源码,或在我的基础上改,给本人分少不好意思,请大家多多指点
[解决办法]
那个代码是在VB总用模拟指针和DIBSECTION写的,贴出来你不会明白的。
你的过程就是想把24位的转换成2位的,我只描述下8位灰度是如何转换为2位的
For i = 0 To Height - 1
k = 0
TempByte = 0
For j = 0 To Width - 1 '一行一行的处理
If OldBytes(oldCurPtr) > Threshold Then TempByte = TempByte + BitAndMask(k)
'如果原始灰度值大于指定的阀值,则为1
If k = 7 Then
Bytes(CurPtr) = TempByte '已经累加了8个位
TempByte = 0
CurPtr = CurPtr + 1
k = 0
Else
k = k + 1
End If
oldCurPtr = oldCurPtr + 1
Next
If k <> 0 Then Bytes(CurPtr) = TempByte '这一句是为了保证一行字节对齐的
'下面还有一些位对齐的代码
Next
哎呀,表述不清楚,你还是自己看下二位图像的格式吧!