C++ NDVI Calculation from Landsat TM Imagery
// Function to calculate NDVI from Landsat TM imagery
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];
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)) // Open the image file (parameter)
{
AfxMessageBox('Cannot open the read file!');
return;
}
// Open the file to write (variables of other classes)
if (!fWriteFile.Open('NDVI', CFile::modeCreate | CFile::modeWrite))
{
AfxMessageBox('Please select an output file!');
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++)
NDVIWr[k] = ((float)NearRed[k] - Red[k]) / (NearRed[k] + Red[k]);
fWriteFile.Write(NDVIWr, sizeof(float) * Height * Width);
delete[] NDVIWr;
delete[] Red;
delete[] NearRed;
fReadFile.Close();
fWriteFile.Close();
}
Explanation:
This C++ code defines a function NDVICal that calculates the NDVI from Landsat TM imagery. Here's a breakdown:
-
Input Parameters:
m_pathname: Path to the input image file.Bands: Number of bands in the image.Width: Width of the image.Height: Height of the image.DataType: Data type of the image (used to determine red and near-infrared band indices).
-
Band Selection:
- The code assumes Landsat TM imagery and sets the red band (
fRed) to 3 and the near-infrared band (fNearRed) to 5 based on theDataType.
- The code assumes Landsat TM imagery and sets the red band (
-
File Handling:
- Opens the input image file for reading.
- Creates an output file named 'NDVI' for writing.
-
Data Reading:
- Reads the red and near-infrared band data from the input file using
fReadFile.SeekandfReadFile.Read.
- Reads the red and near-infrared band data from the input file using
-
NDVI Calculation:
- Iterates through each pixel and calculates the NDVI using the formula:
(NearRed - Red) / (NearRed + Red).
- Iterates through each pixel and calculates the NDVI using the formula:
-
Data Writing:
- Writes the calculated NDVI values to the output file.
-
Memory Management:
- Deallocates the memory used for the NDVI, red, and near-infrared arrays.
-
File Closing:
- Closes both the input and output files.
Keywords: NDVI, Normalized Difference Vegetation Index, Landsat, TM, Remote Sensing, C++, Image Processing, Raster Data
原文地址: https://www.cveoy.top/t/topic/jlM4 著作权归作者所有。请勿转载和采集!