C++ TIFF 文件体积计算 - 填方挖方计算程序
C++ TIFF 文件体积计算 - 填方挖方计算程序
该程序使用 C++ 读取 TIFF 格式的 DEM 图像,计算总填方体积和总挖方体积,并输出结果。程序使用 libtiff 库解析 TIFF 文件,并根据高程数据进行计算。
代码
#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\n");
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\n");
exit(1);
}
strip_size = TIFFStripSize(tif);
data = (float*) _TIFFmalloc(strip_size);
if (!data) {
fprintf(stderr, "Error allocating memory\n");
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\n", total_fill_volume);
printf("Total cut volume: %llu cubic meters\n", total_cut_volume);
_TIFFfree(data);
TIFFClose(tif);
return 0;
}
运行步骤
-
打开命令行窗口(Windows系统按Win+R,输入cmd,按回车键;Mac系统按Command+空格,输入Terminal,按回车键)。
-
使用
cd命令进入代码所在的目录,例如:
cd D:\kjfx\Project9\Project9
- 编译代码,输入以下命令:
gcc -o dem dem.cpp -ltiff
- 运行代码,输入以下命令:
./dem D:\kjfx\dem.tif
其中,D:\kjfx\dem.tif是dem图像的路径。
- 程序会输出总填方体积和总挖方体积,单位为立方米。
说明
- 代码中使用了 libtiff 库,需要先安装 libtiff 库。
ROWS、COLS和PIXEL_SIZE分别代表 DEM 图像的行数、列数和像素大小,需要根据实际情况进行调整。- 该程序假设 DEM 图像的格式为单通道 32 位浮点型。
注意事项
- 代码中使用了 C++ 标准库中的
stdio.h、stdlib.h和tiffio.h头文件。 - 程序使用了
TIFF数据类型,该数据类型由 libtiff 库定义。 - 代码中使用了
TIFFGetField函数读取 TIFF 文件的元数据,例如图像宽度、高度、位深、采样数等。 - 代码中使用了
TIFFReadEncodedStrip函数读取 TIFF 文件的图像数据。 - 代码中使用了
_TIFFmalloc和_TIFFfree函数分配和释放内存。 - 程序假设 DEM 图像的坐标系是统一的,且像素大小一致。
原文地址: http://www.cveoy.top/t/topic/fVgA 著作权归作者所有。请勿转载和采集!