C++ TIFF 文件解析与体积计算
C++ TIFF 文件解析与体积计算
本代码使用 C++ 和 libtiff 库解析 TIFF 文件,并计算 DEM 图像的总填方体积和总挖方体积。
#include <stdio.h>
#include <stdlib.h>
#include <tiffio.h>
#define ROWS 327
#define COLS 486
#define PIXEL_SIZE 5
int main(int argc, char* argv[]) {
TIFF *tif;
float *data;
uint32 width, height;
uint16 bits_per_sample, samples_per_pixel;
tsize_t strip_size;
unsigned long long total_fill_volume = 0, total_cut_volume = 0;
int i, j;
if (argc < 2) {
fprintf(stderr, "Usage: %s <input file>
", argv[0]);
exit(1);
}
tif = TIFFOpen(argv[1], "r");
if (!tif) {
fprintf(stderr, "Error opening TIFF file
");
exit(1);
}
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel);
if (width != COLS || height != ROWS || bits_per_sample != 32 || samples_per_pixel != 1) {
fprintf(stderr, "Invalid TIFF format
");
exit(1);
}
strip_size = TIFFStripSize(tif);
data = (float*) _TIFFmalloc(strip_size);
if (!data) {
fprintf(stderr, "Error allocating memory
");
exit(1);
}
for (i = 0; i < height; i++) {
TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, i, 0), data, strip_size);
for (j = 0; j < width; j++) {
float elevation = data[j];
if (elevation > 0) {
total_fill_volume += (PIXEL_SIZE * PIXEL_SIZE * elevation);
} else {
total_cut_volume += (PIXEL_SIZE * PIXEL_SIZE * (-elevation));
}
}
}
printf("Total fill volume: %llu cubic meters
", total_fill_volume);
printf("Total cut volume: %llu cubic meters
", total_cut_volume);
_TIFFfree(data);
TIFFClose(tif);
return 0;
}
运行代码:
- 打开命令行窗口(Windows)或终端(Mac/Linux)。
- 切换到代码所在的目录,例如输入命令:
cd D:\kjfx\Project9\Project9。 - 编译代码,输入命令:
gcc -o dem dem.cpp -ltiff。 - 运行代码,输入命令:
./dem D:\kjfx\dem.tif。 - 程序输出结果,包括总填方体积和总挖方体积。
代码解释:
-
包含头文件:
stdio.h:标准输入输出库stdlib.h:标准库函数tiffio.h:libtiff 库头文件
-
定义宏:
ROWS:图像行数COLS:图像列数PIXEL_SIZE:像素大小(单位:米)
-
主函数
main:- 检查命令行参数,确保输入了 TIFF 文件路径
- 使用
TIFFOpen打开 TIFF 文件 - 获取 TIFF 文件的信息,如宽度、高度、比特深度、样本数
- 检查 TIFF 文件格式是否符合要求
- 分配内存存储 TIFF 数据
- 使用
TIFFReadEncodedStrip读取 TIFF 数据 - 循环遍历每个像素,计算填方体积和挖方体积
- 输出计算结果
- 释放内存和关闭 TIFF 文件
注意:
- 确保已安装 libtiff 库,可以使用
pkg-config --cflags --libs libtiff查询库的编译选项。 - 确保 TIFF 文件的格式与代码中的参数一致,包括行数、列数、比特深度和样本数。
- 可以根据实际情况调整
PIXEL_SIZE的值。
代码中的 D:\kjfx\Project9\Project9\dem.cpp 和 D:\kjfx\dem.tif 是示例路径,需要根据实际情况修改。
原文地址: http://www.cveoy.top/t/topic/fVf4 著作权归作者所有。请勿转载和采集!