我刚开始在我的 c# 应用程序中使用 LibTIFF.NET 来读取 Tiff 图像作为从 ArcGIS 服务器获得的高度图。我只需要使用图像的像素值填充一个数组,以便基于平滑渐变生成地形。该图像是 LZW 压缩的 32 位灰度 Tiff,其浮点像素值以米为单位表示高度。
现在已经有几天了,我努力返回正确的值,但我得到的只是“0”值,假设它是一个完全黑色或白色的图像!
这是到目前为止的代码:(更新 - 阅读更新 1)
using (Tiff inputImage = Tiff.Open(fileName, "r"))
{
int width = inputImage.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
int height = inputImage.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
int bytesPerPixel = 4;
int count = (int)inputImage.RawTileSize(0); //Has to be: "width * height * bytesPerPixel" ?
int resolution = (int)Math.Sqrt(count);
byte[] inputImageData = new byte[count]; //Has to be: byte[] inputImageData = new byte[width * height * bytesPerPixel];
int offset = 0;
for (int i = 0; i < inputImage.NumberOfTiles(); i++)
{
offset += inputImage.ReadEncodedTile(i, inputImageData, offset, (int)inputImage.RawTileSize(i));
}
float[,] outputImageData = new float[resolution, resolution]; //Has to be: float[,] outputImageData = new float[width * height];
int length = inputImageData.Length;
Buffer.BlockCopy(inputImageData, 0, outputImageData, 0, length);
using (StreamWriter sr = new StreamWriter(fileName.Replace(".tif", ".txt"))) {
string row = "";
for(int i = 0; i < resolution; i++) { //Change "resolution" to "width" in order to have correct array size
for(int j = 0; j < resolution; j++) { //Change "resolution" to "height" in order to have correct array size
row += outputImageData[i, j] + " ";
}
sr.Write(row.Remove(row.Length - 1) + Environment.NewLine);
row = "";
}
}
}
示例文件和结果:http ://terraunity.com/SampleElevationTiff_Results.zip
已经在互联网上到处搜索,找不到针对此特定问题的解决方案。所以我真的很感激帮助,这也使它对其他人有用。
更新1:
根据Antti Leppänen的回答更改了代码,但得到了奇怪的结果,这似乎是一个错误,或者我错过了什么?请在此处查看上传的 zip 文件以使用新的 32x32 tiff 图像查看结果:
http://terraunity.com/SampleElevationTiff_Results.zip
结果:
- LZW 压缩:RawStripSize = ArraySize = 3081 = 55x55 网格
- 未压缩:RawStripSize = ArraySize = 65536 = 256x256 网格
必须是: RawStripSize = ArraySize = 4096 = 32x32 网格
正如您所看到的结果,LibTIFF 会跳过一些行并给出不相关的排序,如果图像大小不是 2 的幂,它甚至会变得更糟!