C++实现遥感影像NDVI计算 | 使用MFC和CFile类
C++实现TM影像NDVI计算
本代码片段展示了如何使用C++计算TM遥感影像的NDVI。
void CBandMath::NDVICal(CString m_pathname, int Bands, int Width, int Height, int DataType)
{
int fRed, fNearRed; // 定义红波段和近红外波段的索引
if (DataType == 1) // TM数据
{
fRed = 3;
fNearRed = 5;
}
CString m_OutFile; // 输出文件名
float* NDVIWr = new float[Height * Width]; // NDVI结果数组
unsigned char* Red = new unsigned char[Height * Width]; // 红波段数据
unsigned char* NearRed = new unsigned char[Height * Width]; // 近红外波段数据
CFile fReadFile, fWriteFile; // 定义读写文件对象
if (!fReadFile.Open(m_pathname, CFile::modeReadWrite)) // 打开图像文件
{
AfxMessageBox('不能打开所读文件!');
return;
}
if (!fWriteFile.Open('NDVI', CFile::modeCreate | CFile::modeWrite)) // 打开写入文件
{
AfxMessageBox('请选择输出文件!');
return;
}
fReadFile.Seek((fRed - 1) * Height * Width, CFile::begin); // 定位到红波段数据位置
fReadFile.Read(Red, Height * Width); // 读取红波段数据
fReadFile.Seek((fNearRed - 1) * Height * Width, CFile::begin); // 定位到近红外波段数据位置
fReadFile.Read(NearRed, Height * Width); // 读取近红外波段数据
for (int k = 0; k < Height * Width; k++) // 计算NDVI
NDVIWr[k] = ((float)NearRed[k] - Red[k]) / (NearRed[k] + Red[k]);
fWriteFile.Write(NDVIWr, sizeof(float) * Height * Width); // 将NDVI结果写入文件
delete[] NDVIWr; // 释放内存
delete[] Red;
delete[] NearRed;
fReadFile.Close(); // 关闭文件
fWriteFile.Close();
}
函数说明:
- 函数名: NDVICal
- 参数:
m_pathname- 图像文件路径Bands- 波段数Width- 图像宽度Height- 图像高度DataType- 数据类型(1表示TM数据)
- 返回值: 无
代码解释:
- 函数首先定义红波段和近红外波段的索引,并根据数据类型确定其值。
- 然后,定义了存储NDVI结果、红波段数据和近红外波段数据的数组。
- 使用
CFile类打开输入图像文件和输出NDVI文件。 - 使用
Seek方法定位到红波段和近红外波段数据位置,并使用Read方法读取数据。 - 循环计算每个像素的NDVI值。
- 将计算得到的NDVI结果写入输出文件。
- 最后,释放内存并关闭所有文件。
注意:
- 该代码仅适用于TM数据。
- 需要修改输出文件路径和名称。
- 使用该代码前需要链接MFC库。
希望这段代码可以帮助您在C++中计算TM影像的NDVI!
原文地址: https://www.cveoy.top/t/topic/jnwG 著作权归作者所有。请勿转载和采集!