我聽說tesseract對於灰度TIFF很好。
所以請儘量爲您的TIFF圖像的轉換下面的代碼爲灰度的:
using (Tiff tif = Tiff.Open(@"input.tif", "r"))
{
FieldValue[] value = tif.GetField(TiffTag.IMAGEWIDTH);
int width = value[0].ToInt();
value = tif.GetField(TiffTag.IMAGELENGTH);
int height = value[0].ToInt();
int xresolution = -1;
value = tif.GetField(TiffTag.XRESOLUTION);
if (value != null)
xresolution = value[0].ToInt();
int yresolution = -1;
value = tif.GetField(TiffTag.YRESOLUTION);
if (value != null)
yresolution = value[0].ToInt();
int[] raster = new int[height * width];
if (!tif.ReadRGBAImageOriented(width, height, raster, Orientation.TOPLEFT))
{
System.Windows.Forms.MessageBox.Show("Could not read image");
return;
}
string fileName = "grayscale.tif";
using (Tiff output = Tiff.Open(fileName, "w"))
{
output.SetField(TiffTag.IMAGEWIDTH, width);
output.SetField(TiffTag.IMAGELENGTH, height);
output.SetField(TiffTag.ROWSPERSTRIP, 1);
output.SetField(TiffTag.SAMPLESPERPIXEL, 1);
output.SetField(TiffTag.BITSPERSAMPLE, 8);
output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
output.SetField(TiffTag.COMPRESSION, Compression.LZW);
output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
if (xresolution != -1 && yresolution != -1)
{
output.SetField(TiffTag.XRESOLUTION, xresolution);
output.SetField(TiffTag.YRESOLUTION, yresolution);
}
byte[] samples = new byte[width];
for (int y = 0, index = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgb = raster[index++];
// compute pixel brightness taking human eye's sensitivity
// to each of red, green and blue colors into account
byte gray = (byte)(Tiff.GetR(rgb) * 0.299 + Tiff.GetG(rgb) * 0.587 + Tiff.GetB(rgb) * 0.114);
// Alternative formulas for RGB -> Gray conversion
//byte gray = (byte)(Tiff.GetR(rgb) * 0.2125 + Tiff.GetG(rgb) * 0.7154 + Tiff.GetB(rgb) * 0.0721);
//byte gray = (byte)((Tiff.GetR(rgb) + Tiff.GetG(rgb) + Tiff.GetB(rgb))/3);
samples[x] = gray;
}
output.WriteEncodedStrip(y, samples, samples.Length);
}
}
}
希望,它會做的伎倆。
這是現有解決方案的一個很好的選擇。 +1 –