private void btnMiddleFilter_Click(object sender, EventArgs e)
{
string openFileName = "";
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog()==DialogResult.OK)
{
openFileName = ofd.FileName;
}
Gdal.AllRegister();
//更改读写权限
Dataset srcDs = Gdal.Open(openFileName, Access.GA_Update);
DataType srcType = srcDs.GetRasterBand(1).DataType;
int bandCount = srcDs.RasterCount;
int srcWidth = srcDs.RasterXSize;
int srcHeight = srcDs.RasterYSize;
Debug.WriteLine("原始影像数据类型是:{0}", srcType);
Debug.WriteLine("原始影像的列数:{0}", srcWidth);
Debug.WriteLine("原始影像的行数:{0}", srcHeight);
int[] bandArray = new int[bandCount];
for (int i = 0; i < bandCount; i++)
{
bandArray[i] = i + 1;
}
if (srcType == DataType.GDT_UInt16)
{
int[] dataArray = new int[srcWidth * srcHeight * bandCount];
int[] newArray = new int[srcWidth * srcHeight * bandCount];
srcDs.ReadRaster(0, 0, srcWidth, srcHeight, dataArray, srcWidth, srcHeight, bandCount, bandArray, 0, 0, 0);
/***********中值滤波实现**************/
int[] temp = new int[5];
for (int i = 0; i < srcHeight; i++)
{
for (int j = 0; j < srcWidth - 2; j++)
{
if (j >= 2)//从第三列开始
{
temp[0] = dataArray[i * srcWidth + j - 2];
temp[1] = dataArray[i * srcWidth + j - 1];
temp[2] = dataArray[i * srcWidth + j];
temp[3] = dataArray[i * srcWidth + j + 1];
temp[4] = dataArray[i * srcWidth + j + 2];
Array.Sort(temp);//排序
newArray[i * srcWidth + j] = temp[2];
}
else
newArray[i * srcWidth + j] = dataArray[i * srcWidth + j];
}
}
//将更新数值的数据重新写入图像
srcDs.WriteRaster(0, 0, srcWidth, srcHeight, newArray, srcWidth, srcHeight, bandCount, bandArray, 0, 0, 0);
srcDs.FlushCache();
}
//最后释放资源
srcDs.Dispose();
MessageBox.Show("中值滤波:success");
}
原图:
原图细节:
中值滤波结果(不明显,需要结合下面的细节展示来观察):
细节展示: