// 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:

  1. 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).
  2. 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 the DataType.
  3. File Handling:

    • Opens the input image file for reading.
    • Creates an output file named 'NDVI' for writing.
  4. Data Reading:

    • Reads the red and near-infrared band data from the input file using fReadFile.Seek and fReadFile.Read.
  5. NDVI Calculation:

    • Iterates through each pixel and calculates the NDVI using the formula: (NearRed - Red) / (NearRed + Red).
  6. Data Writing:

    • Writes the calculated NDVI values to the output file.
  7. Memory Management:

    • Deallocates the memory used for the NDVI, red, and near-infrared arrays.
  8. File Closing:

    • Closes both the input and output files.

Keywords: NDVI, Normalized Difference Vegetation Index, Landsat, TM, Remote Sensing, C++, Image Processing, Raster Data

C++ NDVI Calculation from Landsat TM Imagery

原文地址: https://www.cveoy.top/t/topic/jlM4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录