C语言计算DEM数据填方挖方体积
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> #include <math.h>
#define PIXEL_SIZE 5.0 // 像素大小 #define NO_DATA_VALUE -99999 // 无效像素值
int main() { FILE* fp_dem; const char* filename = "D:\kjfx\dem.tif"; int width = 486, height = 327, i, j; double* elevation; double fill_volume = 0.0, cut_volume = 0.0;
// 打开DEM.tif文件
fp_dem = fopen(filename, "rb");
if (fp_dem == NULL) {
printf("Error: cannot open file %s!
", filename); return 1; }
// 分配内存空间
elevation = (double*)malloc(width * height * sizeof(double));
if (elevation == NULL) {
printf("Error: cannot allocate memory!
"); fclose(fp_dem); return 1; }
// 读取DEM.tif数据
int valid_pixel_count = 0;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
double value;
size_t n = fread(&value, sizeof(double), 1, fp_dem);
if (n != 1) {
printf("Error: cannot read file!
"); free(elevation); fclose(fp_dem); return 1; } elevation[i * width + j] = value; if (value != NO_DATA_VALUE) { valid_pixel_count++; } } }
// 判断是否存在有效像素值
if (valid_pixel_count == 0) {
printf("Error: no valid pixel value in file %s!
", filename); free(elevation); fclose(fp_dem); return 1; }
double epsilon = 1;
// 遍历像素值,计算填方和挖方的体积
int valid_pixel_processed = 0;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
double elev1 = elevation[i * width + j];
if (elev1 == NO_DATA_VALUE) {
continue;
}
double elev2 = NO_DATA_VALUE;
if (i > 0) {
elev2 = elevation[(i - 1) * width + j];
if (elev2 != NO_DATA_VALUE) {
double diff = elev1 - elev2 + epsilon; // 加上偏移量
if (diff > 0) {
cut_volume += diff * PIXEL_SIZE * PIXEL_SIZE;
}
else {
fill_volume += (-diff) * PIXEL_SIZE * PIXEL_SIZE;
}
}
}
if (i < height - 1) {
elev2 = elevation[(i + 1) * width + j];
if (elev2 != NO_DATA_VALUE) {
double diff = elev1 - elev2 + epsilon;
if (diff > 0) {
cut_volume += diff * PIXEL_SIZE * PIXEL_SIZE;
}
else {
fill_volume += (-diff) * PIXEL_SIZE * PIXEL_SIZE;
}
}
}
if (j > 0) {
elev2 = elevation[i * width + j - 1];
if (elev2 != NO_DATA_VALUE) {
double diff = elev1 - elev2 + epsilon;
if (diff > 0) {
cut_volume += diff * PIXEL_SIZE * PIXEL_SIZE;
}
else {
fill_volume += (-diff) * PIXEL_SIZE * PIXEL_SIZE;
}
}
}
if (j < width - 1) {
elev2 = elevation[i * width + j + 1];
if (elev2 != NO_DATA_VALUE) {
double diff = elev1 - elev2 + epsilon;
if (diff > 0) {
cut_volume += diff * PIXEL_SIZE * PIXEL_SIZE;
}
else {
fill_volume += (-diff) * PIXEL_SIZE * PIXEL_SIZE;
}
}
}
valid_pixel_processed++;
}
}
// 判断是否所有有效像素值都已处理
if (valid_pixel_processed != valid_pixel_count) {
printf("Warning: not all valid pixel values are processed!
"); }
// 输出结果
if (isnan(fill_volume)) {
printf("Fill volume = N/A
"); } else { printf("Fill volume = %.2f m3 ", fill_volume); } if (isinf(cut_volume)) { printf("Cut volume = N/A "); } else { printf("Cut volume = %.2f m3 ", cut_volume); } // 释放内存空间 free(elevation);
// 关闭文件
fclose(fp_dem);
return 0;
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/jobB 著作权归作者所有。请勿转载和采集!