今天整个水土流失定量分析系统的所有功能算是实现好啦。
今天实现的主要是因子归一化。其实因子归一化的方法和之前算植被覆盖率的方法差不多,都是重分类的方法,用数组的setValue方法即可。
private void 因子归一化ToolStripMenuItem_Click(object sender, EventArgs e)
{
// 自定义的提示信息
string customMessage1 = "请输入想要归一化的栅格";
IRaster resultRaster = null;
// 显示自定义提示信息
MessageBox.Show(customMessage1, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
IRasterDataset rasterDataset = OpenTiffFile();
if (rasterDataset == null)
{
MessageBox.Show("未选择任何TIFF文件或者打开文件失败。");
return;
}
//调用 reclass 方法
resultRaster = reclass5(rasterDataset.CreateDefaultRaster());
IRasterLayer rasterLayer = new RasterLayerClass();
rasterLayer.CreateFromRaster(resultRaster);
rasterLayer.Name = "重分类";
axMapControl2.AddLayer((ILayer)rasterLayer, 0);
axMapControl2.ActiveView.Refresh();
SaveRasterToFile(resultRaster);
}
private IRaster reclass5(IRaster pRaster)
{
IRasterProps rasterProps = (IRasterProps)pRaster;
// 设置栅格数据起始点
IPnt pBlockSize = new Pnt();
pBlockSize.SetCoords(rasterProps.Width, rasterProps.Height);
// 选取整个范围
IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize);
// 左上点坐标
IPnt tlp = new Pnt();
tlp.SetCoords(0, 0);
// 读入栅格
IRasterBandCollection pRasterBands = pRaster as IRasterBandCollection;
IRasterBand pRasterBand = pRasterBands.Item(0);
IRawPixels pRawPixels = pRasterBands.Item(0) as IRawPixels;
pRawPixels.Read(tlp, pPixelBlock);
// 将PixBlock的值组成数组
System.Array pSafeArray = pPixelBlock.get_SafeArray(0) as System.Array;
// 获取像元值的最大值和最小值
double minValue = double.MaxValue;
double maxValue = double.MinValue;
for (int y = 0; y < rasterProps.Height; y++)
{
for (int x = 0; x < rasterProps.Width; x++)
{
double value = Convert.ToDouble(pSafeArray.GetValue(x, y));
if (value > -100000 && value < 100000) // 忽略空值
{
if (value < minValue)
minValue = value;
if (value > maxValue)
maxValue = value;
}
}
}
// 设置分界值为最大值和最小值
double lowerValue = minValue;
double upperValue = maxValue;
MessageBox.Show(lowerValue.ToString());
MessageBox.Show(upperValue.ToString());
// 对每个像元值进行重新分类
for (int y = 0; y < rasterProps.Height; y++)
{
for (int x = 0; x < rasterProps.Width; x++)
{
double value = Convert.ToDouble(pSafeArray.GetValue(x, y));
if (value == lowerValue)
pSafeArray.SetValue(0.0f, x, y);
else if (value == upperValue)
pSafeArray.SetValue(1.0f, x, y);
else if (value > lowerValue && value < upperValue)
{
double normalizedValue = (value - lowerValue) / (upperValue - lowerValue);
pSafeArray.SetValue((float)normalizedValue, x, y);
}
else
{
pSafeArray.SetValue(float.NaN, x, y); // 设置为空值
}
}
}
pPixelBlock.set_SafeArray(0, pSafeArray);
// 编辑raster,将更新的值写入raster中
IRasterEdit rasterEdit = pRaster as IRasterEdit;
rasterEdit.Write(tlp, pPixelBlock);
rasterEdit.Refresh();
return pRaster;
}