c# - 将多波段 16 位 tiff 图像转换为 8 位 tiff 图像

标签 c# arrays image-processing tiff gdal

我从 16 位(范围 0-65535)tif 图像中获取了一些像素数据作为整数数组。我使用 gdal readraster 获得了该值。如何将它们转换为 8 位(0-225)并将其(数组)转换为 8 位 tif 图像?

这是我的一些代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.GDAL;
using OSGeo.OSR;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            Gdal.AllRegister();
            Dataset data1;
            int xsize, ysize;
            int bandsize;

            data1 = Gdal.Open("F:\\po_1473547_bgrn_0000000.tif", Access.GA_ReadOnly);

            bandsize = data1.RasterCount;

            xsize = data1.RasterXSize; //cols
            ysize = data1.RasterYSize; //rows

            Console.WriteLine("cols : "+xsize+", rows : "+ysize);

            Band[] bands = new Band[bandsize];
            for (int i = 0; i < bandsize; i++) {
                bands[i] = data1.GetRasterBand(i+1);
            }


            int[,,] pixel = new int[bandsize,xsize,ysize]; 
            int[] pixtemp = new int[xsize * ysize];


            for (int i = 0; i < bandsize; i++)
            {
                bands[i].ReadRaster(0, 0, xsize, ysize, pixtemp, xsize, ysize, 0, 0);

                for (int j = 0; j < xsize; j++)
                {
                    for (int k = 0; k < ysize; k++)
                    {
                        pixel[i,j,k] = pixtemp[j + k * xsize];
                    }
                }
            }


            Console.WriteLine("");

            for (int i = 0; i < bandsize; i++)
            {
                Console.WriteLine("some pixel from band " + (i+1));
                for (int j = 0; j < 100; j++)
                {
                    Console.Write(" " + pixel[i,100,j]);
                }

                Console.WriteLine("\n\n");
            }
        }
    }
}

我在 Google 上搜索如何做到这一点,但我只找到了数据类型为字节时如何做到这一点。有人请给我提示。

最佳答案

我不了解 GEO Tiff 格式,但要将常规 16 位 tiff 图像文件转换为 8 位图像文件,您需要将 16 位 channel 值缩放为 8 位。下面的示例展示了如何对灰度图像实现这一点。

public static class TiffConverter
{
    private static IEnumerable<BitmapSource> Load16BitTiff(Stream source)
    {
        var decoder = new TiffBitmapDecoder(source, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        for (int i = 0; i < decoder.Frames.Count; i++)
            // return all frames that are present in the input.
            yield return decoder.Frames[i];
    }

    private static BitmapSource NormalizeTiffTo8BitImage(BitmapSource source)
    {
        // allocate buffer & copy image bytes.
        var rawStride = source.PixelWidth * source.Format.BitsPerPixel / 8;
        var rawImage = new byte[rawStride * source.PixelHeight];
        source.CopyPixels(rawImage, rawStride, 0);

        // get both max values of first & second byte of pixel as scaling bounds.
        var max1 = 0; 
        int max2 = 1; 
        for (int i = 0; i < rawImage.Length; i++)
        {
            if ((i & 1) == 0)
            {
                if (rawImage[i] > max1)
                    max1 = rawImage[i];
            }
            else if (rawImage[i] > max2)
                max2 = rawImage[i];
        }

        // determine normalization factors.
        var normFactor = max2 == 0 ? 0.0d : 128.0d / max2;
        var factor = max1 > 0 ? 255.0d / max1 : 0.0d;
        max2 = Math.Max(max2, 1);

        // normalize each pixel to output buffer.
        var buffer8Bit = new byte[rawImage.Length / 2];
        for (int src = 0, dst = 0; src < rawImage.Length; dst++)
        {
            int value16 = rawImage[src++];
            double value8 = ((value16 * factor) / max2) - normFactor;

            if (rawImage[src] > 0)
            {
                int b = rawImage[src] << 8;
                value8 = ((value16 + b) / max2) - normFactor;
            }
            buffer8Bit[dst] = (byte)Math.Min(255, Math.Max(value8, 0));
            src++;
        }

        // return new bitmap source.
        return BitmapSource.Create(
            source.PixelWidth, source.PixelHeight,
            source.DpiX, source.DpiY, 
            PixelFormats.Gray8, BitmapPalettes.Gray256,
            buffer8Bit, rawStride / 2);
    }

    private static void SaveTo(IEnumerable<BitmapSource> src, string fileName)
    {
        using (var stream = File.Create(fileName))
        {
            var encoder = new TiffBitmapEncoder();
            foreach (var bms in src)
                encoder.Frames.Add(BitmapFrame.Create(bms));
            encoder.Save(stream);
        }
    }

    public static void Convert(string inputFileName, string outputFileName)
    {
        using (var inputStream = File.OpenRead(inputFileName))
            SaveTo(Load16BitTiff(inputStream).Select(NormalizeTiffTo8BitImage), outputFileName);
    }
}

用法:

TiffConverter.Convert(@"c:\temp\16bit.tif", @"c:\temp\8bit.tif");

关于c# - 将多波段 16 位 tiff 图像转换为 8 位 tiff 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504707/

相关文章:

javascript - 在对象数组中,返回任何值与特定字符串匹配的对象

c# - DataGrid 显示图像的路径而不是图像本身

C# - Windows 窗体中的简单二维图形绘制

c# - OpenID 登录助手按钮

python-2.7 - 如何识别这个圆边?

javascript - Node.js 是否适合图像代理和操作任务?

image-processing - WebGL 地球 : how to make clouds

c# - 验证服务描述符时出错 'ServiceType: INewsRepository Lifetime: Singleton ImplementationType: NewsRepository' :

c++ - 尝试从指针数组 c++ 打印时出现奇怪的输出

java - 程序布局 - 通过 System.in.read 创建适当大小的数组