Search code examples
c#tiffgrayscalelibtiff.net

Reading 32-bit grayscale Tiff using Libtiff.Net


I've tried to read a 32-bit grayscale tiff file which each pixel in the image contains a floating point number. But during the reading process, the buffer array contains 4 values for each pixel. For instance [ pixel value = 43.0 --> byte values for the pixel = {0 , 0 , 44 , 66}]. I can't understand the relation between float pixel value and the byte values. I also wrote the image using the buffer but pixel values for output image are int values like 1073872896. Any suggestion would be appreciated.

using (Tiff input = Tiff.Open(@"E:\Sample_04.tif", "r"))
        {
            // get properties to use in writing output image file
            int width = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
            int height = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
            int samplesPerPixel = input.GetField(TiffTag.SAMPLESPERPIXEL)[0].ToInt();
            int bitsPerSample = input.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
            int photo = input.GetField(TiffTag.PHOTOMETRIC)[0].ToInt();

            int scanlineSize = input.ScanlineSize();  
            byte[][] buffer = new byte[height][]; 

            for (int i = 0; i < height; i++)
            {
                buffer[i] = new byte[scanlineSize];
                input.ReadScanline(buffer[i], i);
            }

        using (Tiff output = Tiff.Open("output.tif", "w"))
                {
                    output.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel);
                    output.SetField(TiffTag.IMAGEWIDTH, width);
                    output.SetField(TiffTag.IMAGELENGTH, height);
                    output.SetField(TiffTag.BITSPERSAMPLE, bitsPerSample);
                    output.SetField(TiffTag.ROWSPERSTRIP, output.DefaultStripSize(0));
                    output.SetField(TiffTag.PHOTOMETRIC, photo);
                    output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                    output.SetField(TiffTag.COMPRESSION, compression);

                    int j = 0;
                    for (int i = 0; i < h; i++)
                    {

                        output.WriteScanline(buffer[i], j);
                        j++;
                    }
                }
        }

Update 1:

I found out the relation between four bytes and the pixel value using BitConverter class in c# that is like this: byte[] a = { 0, 0, 44, 66 } --> 43 = BitConverter.ToSingle(a, 0) and 1110179840 = BitConverter.ToInt32(a, 0). It seem bytes are converted to int32 and now the question is how convert byte values to float?

Update 2: The original tiff file and the tiff after writing the snippet code have been attached.Why is the output tiff file messed up?

Input tiff Output tiff


Solution

  • I added this line of code to convert pixel values to floating number and it works fine.

    output.SetField(TiffTag.SAMPLEFORMAT, SampleFormat.IEEEFP);