private void btnMapMultiply_Click(object sender, EventArgs e)
{
string mapMultiply01 = @"E:\\multiply01-109-109.jpg";
string mapMultiply02 = @"E:\\multiply02-109-109.jpg";
Gdal.AllRegister();
//更改读写权限
Dataset srcDs1 = Gdal.Open(mapMultiply01, Access.GA_ReadOnly);
Dataset srcDs2 = Gdal.Open(mapMultiply02, Access.GA_ReadOnly);
DataType srcType = srcDs1.GetRasterBand(1).DataType;
//MessageBox.Show(srcType.ToString());
int bandCount = srcDs1.RasterCount;
int srcWidth = srcDs1.RasterXSize;
int srcHeight = srcDs1.RasterYSize;
int[] bandArray = new int[bandCount];
for (int i = 0; i < bandCount; i++)
{
bandArray[i] = i + 1;
}
//注意,JPG没有实现Create方法来创建
//Dataset dstDs= drv.Create(dstFileName,srcWidth,srcHeight,bandCount,DataType.GDT_Byte,null);
//首先创建一个内存的驱动
string strMemory = @"E:\MultiplyMemory.jpg";
Driver dryMemory = Gdal.GetDriverByName("MEM");
Dataset dsMemory = dryMemory.Create(strMemory, srcWidth, srcHeight, bandCount, DataType.GDT_Byte, null);
int[] dataArray1 = new int[srcWidth * srcHeight * bandCount];
int[] dataArray2 = new int[srcWidth * srcHeight * bandCount];
int[] newArray = new int[srcWidth * srcHeight * bandCount];
srcDs1.ReadRaster(0, 0, srcWidth, srcHeight, dataArray1, srcWidth, srcHeight, bandCount, bandArray, 0, 0, 0);
srcDs2.ReadRaster(0, 0, srcWidth, srcHeight, dataArray2, srcWidth, srcHeight, bandCount, bandArray, 0, 0, 0);
if (srcType == DataType.GDT_Byte)
{
/***********图像代数相加实现**************/
for (int iband = 0; iband < 3; iband++)
{
int temp = iband * srcHeight * srcWidth;
for (int i = 0; i < srcHeight; i++)
{
for (int j = 0; j < srcWidth; j++)
{
if (dataArray2[temp + i * srcWidth + j]!=0)
{
//因为该图是截图得到的,不是纯粹的0、1二值图,里面含有0,253,254,255等,因此将其统一为0和1两个值
dataArray2[temp + i * srcWidth + j] = 1;
}
newArray[temp + i * srcWidth + j] = dataArray1[temp + i * srcWidth + j] * dataArray2[temp + i * srcWidth + j];
}
}
}
//将更新数值的数据重新写入图像
dsMemory.WriteRaster(0, 0, srcWidth, srcHeight, newArray, srcWidth, srcHeight, bandCount, bandArray, 0, 0, 0);
dsMemory.FlushCache();
}
Driver drvJPG = Gdal.GetDriverByName("JPEG");
string dstFileName = @"E:\Result_Multiply.jpg";
drvJPG.CreateCopy(dstFileName, dsMemory, 1, null, null, null);
//最后释放资源
dsMemory.Dispose();
srcDs1.Dispose();
srcDs2.Dispose();
MessageBox.Show("图像相乘:success");
}
原图1:
原图2:
相乘效果:
课件效果: