TIFF文件中的负灰度值为白色

时间:2015-12-02 21:37:13

标签: c# image-processing libtiff libtiff.net

我正在使用BitMiracle的LibTiff.NET库来处理一些TIFF图像文件。我需要根据标准化公式转换每个像素的灰度值,这个公式将导致负像素值。

我将Sampleformat TIFF标记更改为:

TiffTag.SAMPLEFORMAT, BitMiracle.LibTiff.Classic.SampleFormat.INT

但所有负灰度值在结果图像中显示为亮白色。

如果我通过添加最低灰度值的倒数来偏移所有值,则图像是正确的。

我做错了什么?完整代码:

       public void convertTIFF(string sourceFile)
    {
        Tiff tif = Tiff.Open(sourceFile, "r"); //These are all 16Bit, unsigned TIFFs
        var height = tif.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
        var width = tif.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
        var res = tif.GetField(TiffTag.XRESOLUTION)[0].ToInt();
        var resy = tif.GetField(TiffTag.YRESOLUTION)[0].ToInt();

        string fileName = string.Format("{0}_STD.tif", sourceFile );
        using (Tiff output = Tiff.Open(fileName, "w"))
        {
            output.SetField(TiffTag.IMAGEWIDTH, width);
            output.SetField(TiffTag.IMAGELENGTH, height);
            output.SetField(TiffTag.SAMPLESPERPIXEL, 1);
            output.SetField(TiffTag.SAMPLEFORMAT, BitMiracle.LibTiff.Classic.SampleFormat.UINT);
            output.SetField(TiffTag.BITSPERSAMPLE, 16);
            output.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT);
            output.SetField(TiffTag.ROWSPERSTRIP, width);
            output.SetField(TiffTag.XRESOLUTION, res);
            output.SetField(TiffTag.YRESOLUTION, resy);

            output.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.INCH);
            output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
            output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
            output.SetField(TiffTag.COMPRESSION, Compression.NONE);
            output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

            byte[] scanline = new byte[tif.ScanlineSize()]; //Input buffer
            byte[] buffer = new byte[tif.ScanlineSize()]; //Output buffer

            for (int i = 0; i < height; i++)
            {
                tif.ReadScanline(scanline, i);
                short[] samples = new short[width];
                {
                    ushort[] temp = new ushort[width];
                    Buffer.BlockCopy(scanline, 0, temp, 0, scanline.Length);
                    for (int t = 0; t < width; t++)
                    {
                        ushort row = temp[t];
                        var rowStd = ConvertToReference(row); //This function standardises the grayscale value, results possible in range -2000 to 10000
                        samples[t] = (short)(rowStd);
                    }
                }
                Buffer.BlockCopy(samples, 0, buffer, 0, buffer.Length);
                output.WriteScanline(buffer, i);
            }
        }
    }

0 个答案:

没有答案