//函数名:OpenRasterDataset //功能:给定空间和Dataset的名称,获取RasterDataset //参数:directoryName:workspace's file path // fileName:Dataset's name including the extension for example .tif //备注: Libraries needed to run the code:ESRI.ArcGIS.Geodatabase, ESRI.ArcGIS.DataSourcesRaster public IRasterDataset OpenRasterDataset(string directoryName, string fileName) { //Open the raster dataset with the given name. //directoryName is the directory where the file resides //fileName is the filename to be opened //Open the workspace IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); // define the directory as a raster workspace IRasterWorkspace rasterWorkspace = workspaceFactory.OpenFromFile(directoryName, 0) as IRasterWorkspace; //Open the raster dataset IRasterDataset rasterDataset = null; rasterDataset = rasterWorkspace.OpenRasterDataset(fileName); // Return raster dataset return(rasterDataset); }
private void RasterfileLoad_Click(object sender, EventArgs e) { OpenFileDialog pOpenFileDialog = new OpenFileDialog(); pOpenFileDialog.CheckFileExists = true; pOpenFileDialog.Title = "打开Raster文件"; pOpenFileDialog.Filter = "栅格文件(*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif)|(*.jpg)|*.jpg|(*.img)|*.img"; pOpenFileDialog.ShowDialog(); string pRasterFileName = pOpenFileDialog.FileName; if (pRasterFileName == "") { return; } string pPath = System.IO.Path.GetDirectoryName(pRasterFileName); string pFileName = System.IO.Path.GetFileName(pRasterFileName); IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pPath, 0); IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace; IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(pFileName); //影像金字塔的判断和创建 IRasterPyramid3 pRasPyramid = pRasterDataset as IRasterPyramid3; if (pRasPyramid != null) { if (!(pRasPyramid.Present)) { pRasPyramid.Create(); //创建金字塔 } } IRaster pRaster = pRasterDataset.CreateDefaultRaster(); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; mainMapControl.AddLayer(pLayer, 0); }
/// <summary> /// 添加栅格数据 /// </summary> /// <param name="mapControl">要添加栅格数据的地图控件</param> public void AddRasterFile(AxMapControl mapControl) { //获得文件 OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "打开Raster文件"; openFileDialog.Filter = "栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img"; openFileDialog.CheckFileExists = true; openFileDialog.ShowDialog(); //拆分路径和文件名 string fullPath = openFileDialog.FileName; if (fullPath == "") { return; } string fileDir = Path.GetDirectoryName(fullPath); string fileName = Path.GetFileName(fullPath); //从工作空间拿数据集 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(fileDir, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName); //栅格金字塔 IRasterPyramid3 rasPyramid = rasterDataset as IRasterPyramid3; if (rasPyramid != null) { if (!rasPyramid.Present) { rasPyramid.Create(); } } //从数据集拿数据 IRaster raster = rasterDataset.CreateDefaultRaster(); IRasterLayer rasterLayer = new RasterLayerClass(); rasterLayer.CreateFromRaster(raster); //加载数据 mapControl.AddLayer(rasterLayer); mapControl.ActiveView.Refresh(); }
static void Main(string[] args) { //运行环境初始化 ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop); IAoInitialize aoinitialize = new AoInitializeClass(); esriLicenseStatus status = aoinitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard); string path = System.Environment.CurrentDirectory; string name = "result.tif"; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)(workspaceFactory.OpenFromFile(path, 0)); IRasterDataset pRasterDataset = rasterWorkspace.OpenRasterDataset(name); //创建栅格瓦片 CreateTilesFromRasterDataset(pRasterDataset, rasterWorkspace as IWorkspace, 500, 500); //修改栅格的值 ChangeRasterValue(pRasterDataset as IRasterDataset2); aoinitialize.Shutdown(); }
public static IRasterDataset OpenRasterDataset(string inFile, int bandIndex) { IWorkspaceFactory pWorkspaceFactory = null; IRasterWorkspace rasterWorkspace = null; IRasterDataset rasterDataset = null; int Index = inFile.LastIndexOf("\\"); string filePath = inFile.Substring(0, Index); string fileName = inFile.Substring(Index + 1); try { pWorkspaceFactory = new RasterWorkspaceFactory(); rasterWorkspace = (IRasterWorkspace)pWorkspaceFactory.OpenFromFile(filePath, 0); rasterDataset = rasterWorkspace.OpenRasterDataset(fileName); if (bandIndex > 0) { IRasterBandCollection pRasterBandCollection = rasterDataset as IRasterBandCollection; IRasterBand pBand = pRasterBandCollection.Item(bandIndex - 1); rasterDataset = pBand as IRasterDataset; } } catch (Exception ex) { //Console.WriteLine("Failed in Opening RasterDataset. " + ex.InnerException.ToString()); //Log.WriteLog(typeof(RasterMapAlgebraOp), ex); throw ex; } finally { if (pWorkspaceFactory != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspaceFactory); } if (rasterWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWorkspace); } } return(rasterDataset); }
/// <summary> /// 打开栅格数据. /// </summary> /// <param name="filePath">文件路径.</param> /// <returns>IRasterDataset.</returns> public static IRasterDataset OpenFileRasterDataset(string filePath) { try { //新建工作空间工厂 IWorkspaceFactory WorkspaceFactory = new RasterWorkspaceFactoryClass(); //新建工作空间 IWorkspace Workspace = WorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0); //新建栅格工作空间 IRasterWorkspace rasterWorkspace = (IRasterWorkspace)Workspace; // IGeoDataset rasterSet = (IGeoDataset)rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(fullpath)); //读取栅格数据 IRasterDataset rasterSet = (IRasterDataset)rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(filePath)); //返回IRasterDataset return(rasterSet); } catch (Exception ex) { XtraMessageBox.Show("读取栅格数据集失败!\n" + ex.Message); return(null); } }
/// <summary> /// 打开adf文件格式栅格数据 /// </summary> /// <param name="rasterPath"></param> /// <param name="fileName"></param> public static void OpenRasterLayer(string rasterPath, string fileName) { IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory(); IWorkspace SWorkspace = workspaceFactory.OpenFromFile(rasterPath, 0); IRasterWorkspace rasterWorkspace = SWorkspace as IRasterWorkspace; IRasterDataset pRasterDataset = (IRasterDataset)rasterWorkspace.OpenRasterDataset(fileName); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromDataset(pRasterDataset); IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass() { FromColor = new RgbColorClass() { Red = 197, Green = 68, Blue = 56 }, ToColor = new RgbColorClass() { Red = 80, Green = 110, Blue = 207 }, Size = 100 };//Red = 80, Green = 110, Blue = 207 IMultiPartColorRamp multiPartColorRamp = new MultiPartColorRampClass(); multiPartColorRamp.set_Ramp(0, colorRamp); bool outCreate = false; colorRamp.CreateRamp(out outCreate); //设置渲染参数 IRasterStretchColorRampRenderer rasterStretchColorRampRenderer = new RasterStretchColorRampRendererClass(); IRasterRenderer rasterRenderer = rasterStretchColorRampRenderer as IRasterRenderer; rasterRenderer.Raster = pRasterLayer.Raster; rasterRenderer.Update(); rasterStretchColorRampRenderer.BandIndex = 0; rasterStretchColorRampRenderer.ColorRamp = multiPartColorRamp as IColorRamp; rasterRenderer.Update(); pRasterLayer.Renderer = rasterRenderer; MainFrom.m_mapControl.AddLayer(pRasterLayer); }
/// <summary> /// 加载栅格数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddRaster_Click(object sender, EventArgs e) { string title = "打开Raster文件"; string filter = "栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img"; OpenFileDialog pOpenFileDialog = createOpenFileDialog(title, filter); string pRasterFileName = pOpenFileDialog.FileName; if (pRasterFileName == "") { return; } string pPath = System.IO.Path.GetDirectoryName(pRasterFileName); string pFileName = System.IO.Path.GetFileName(pRasterFileName); IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory(); IRasterWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pPath, 0) as IRasterWorkspace; IRasterDataset pRasterDataSet = pWorkspace.OpenRasterDataset(pFileName); // 影像金字塔判断与创建 IRasterPyramid3 pRasPyrmid; pRasPyrmid = pRasterDataSet as IRasterPyramid3; if (pRasPyrmid != null) { if (!(pRasPyrmid.Present)) { // 创建金字塔 pRasPyrmid.Create(); } } IRaster pRaster = pRasterDataSet.CreateDefaultRaster(); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; MainMapControl.AddLayer(pLayer); }
/// <summary> /// Save modification to the original file. /// </summary> public static void SaveEdits() { if (ActiveLayer == null || Edits.Count == 0) { return; } ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.EngineOrDesktop); // Get the original file IRasterLayer rasterLayer = (IRasterLayer)Editor.ActiveLayer; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(rasterLayer.FilePath), 0); IRasterDataset2 mRasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(rasterLayer.FilePath)); IRaster mRaster = mRasterDataset.CreateFullRaster(); Editor.WriteEdits(mRaster); System.Runtime.InteropServices.Marshal.ReleaseComObject(mRaster); ArcMap.Document.ActiveView.Refresh(); }
/// <summary> /// 打开栅格文件 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private ILayer openRasterFile(string fileName) { string workSpacePath = System.IO.Path.GetDirectoryName(fileName); string RasterFileName = System.IO.Path.GetFileName(fileName); IWorkspaceFactory wsf = new RasterWorkspaceFactoryClass(); IRasterWorkspace rws = (IRasterWorkspace)wsf.OpenFromFile(workSpacePath, 0);//打开工作空间 IRasterDataset rasterDataset = rws.OpenRasterDataset(RasterFileName); //影像金字塔判断与创建 IRasterPyramid rasPyrmid = rasterDataset as IRasterPyramid; if (rasPyrmid != null) { if (!(rasPyrmid.Present)) { rasPyrmid.Create(); } } IRaster raster = rasterDataset.CreateDefaultRaster(); IRasterLayer rLayer = new RasterLayerClass(); ILayer layer = rLayer as ILayer; return(layer); }
private void btnOpenraster_Click(object sender, EventArgs e) { OpenFileDialog pOpenFileDialog = new OpenFileDialog(); pOpenFileDialog.Filter = "TIFF(*.tif)|*.tif|GRID(*.Grid)|*.grid|IMAGINE(*.img)|*.img"; if (pOpenFileDialog.ShowDialog() == DialogResult.OK) { comboBoxOpenraster.Text = pOpenFileDialog.FileName; if (comboBoxOpenraster.Text != "")//获取打开的栅格数据的路径信息及像元值 { IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass(); filePath_raster = comboBoxOpenraster.Text; fileName_raster = System.IO.Path.GetFileName(comboBoxOpenraster.Text); IRasterWorkspace pRasterWorkspace = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath_raster), 0) as IRasterWorkspace; IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(fileName_raster); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromDataset(pRasterDataset); IRaster pRaster = pRasterLayer.Raster; IRasterAnalysisProps pRasterAnalysisProps = (IRasterAnalysisProps)pRaster; txtCellSize.Text = Convert.ToString(pRasterAnalysisProps.PixelHeight); } } }
/// <summary> /// 加载栅格文件到主地图控件 /// </summary> /// <param name="rasterPath">The raster path.</param> private void AddRasterFileToMap(string rasterPath) { try { IRasterLayer rasterLayer = new RasterLayerClass(); string directoryName = System.IO.Path.GetDirectoryName(rasterPath); string fileName = System.IO.Path.GetFileName(rasterPath); IRasterWorkspace rasterWorkspace = EngineAPI.OpenWorkspace(directoryName, DataType.raster) as IRasterWorkspace; IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName); rasterLayer.CreateFromDataset(rasterDataset); IRasterPyramid3 rasterPyramid = rasterDataset as IRasterPyramid3; if (rasterPyramid != null && !rasterPyramid.Present) { //new frmCreatePyramid(new List<string> //{ // rasterLayer.FilePath //}) //{ // Owner = EnviVars.instance.MainForm //}.ShowDialog(); //using (GPExecutor gp = new GPExecutor()) { EnviVars.instance.GpExecutor.CreatePyramid(new List <string> { rasterLayer.FilePath }); } } this.axMapControl.AddLayer(rasterLayer, 0); } catch (Exception ex) { //XtraMessageBox.Show("加载数据失败!", "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); Log.WriteLog(typeof(frmPreview), ex); throw ex; } }
private void buttton_tiff_Click(object sender, EventArgs e) { axMapControl1.ClearLayers(); //string tiffPath = "tiff文件/未命名.tiff";D://users//lenovo//documents//visual studio 2015//Projects//Teamwork//Teamwork//tiff文件 if (tiffPath == "") { return; } int Index = tiffPath.LastIndexOf("\\"); string fileName = tiffPath.Substring(Index + 1); string filePath = tiffPath.Substring(0, Index); IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass(); //利用工厂对象去生成一个raster文件的工作空间 IRasterWorkspace pRasterWorkspace = (IRasterWorkspace)pWorkspaceFactory.OpenFromFile(filePath, 0); //到指定路径下 IRasterDataset pRasterDataset = (IRasterDataset)pRasterWorkspace.OpenRasterDataset(fileName); //利用要素集去接收对应的raster文件 IRasterLayer pRasterLayer = new RasterLayerClass(); //生成一个矢量图层对象 pRasterLayer.CreateFromDataset(pRasterDataset); //利用矢量图层对象去创建对应的raster文件 axMapControl1.Map.AddLayer(pRasterLayer); //添加对应的图层 axMapControl1.Update(); axMapControl1.ActiveView.Refresh(); }
//定义栅格打开函数 public static void OpenRaster(string rasterFileName, AxMapControl _MapControl) { if (!File.Exists(rasterFileName)) { return; } try { //文件名处理 string ws = System.IO.Path.GetDirectoryName(rasterFileName); string fbs = System.IO.Path.GetFileName(rasterFileName); //创建工作空间 IWorkspaceFactory pWork = new RasterWorkspaceFactoryClass(); //打开工作空间路径,工作空间的参数是目录,不是具体的文件名 IRasterWorkspace pRasterWS = (IRasterWorkspace)pWork.OpenFromFile(ws, 0); //打开工作空间下的文件, IRasterDataset pRasterDataset = pRasterWS.OpenRasterDataset(fbs); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromDataset(pRasterDataset); //添加到图层控制中 _MapControl.Map.AddLayer(pRasterLayer as ILayer); } catch { } }
/// <summary> /// Save the edition as a specified file. /// </summary> /// <param name="fileName"></param> public static void SaveEditsAs(string fileName) { if (ActiveLayer == null) { return; } Random rnd = new Random(); string tempFile = rnd.Next().ToString(); ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.EngineOrDesktop); // Get the original file IRasterLayer rasterLayer = (IRasterLayer)Editor.ActiveLayer; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(rasterLayer.FilePath), 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(rasterLayer.FilePath)); // Open the new file save location IWorkspace mWorkspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0); // Copy file to the new location rasterDataset.Copy(tempFile, mWorkspace); // Save the original file to a new file ISaveAs saveAs = (ISaveAs)rasterDataset; IRasterDataset2 mRasterDataset = (IRasterDataset2)saveAs.SaveAs(System.IO.Path.GetFileName(fileName), mWorkspace, RasterFile.GetFormat(System.IO.Path.GetExtension(fileName))); IRaster mRaster = mRasterDataset.CreateFullRaster(); // Save edits to file Editor.WriteEdits(mRaster); System.Runtime.InteropServices.Marshal.ReleaseComObject(mRaster); }
/// <summary> /// 加载栅格数据文件 /// </summary> /// <param name="axMapControl">地图控件引用</param> /// <param name="strFilePath">文件路径</param> /// <returns>正常:“”,异常:异常字符;</returns> private SystemErrorType LoadRasterFile(ref AxMapControl axMapControl, string strFilePath) { if (strFilePath == "") { return(SystemErrorType.enumFilePathIsNull); } try { IWorkspaceFactory pWorkspaceFactory = null; IRasterWorkspace pRasterWorkspace = null; IRasterDataset pRasterDataset = null; IRasterLayer pRasterLayer = null; String WorkspacePath = strFilePath.Substring(0, strFilePath.LastIndexOf('\\'));//e.g. c:/data/a.shp pWorkspaceFactory = new RasterWorkspaceFactoryClass() as IWorkspaceFactory; //如果符合要求 , 打开栅格数据文件并加载到地图控件中。 if (pWorkspaceFactory.IsWorkspace(WorkspacePath)) { pRasterWorkspace = pWorkspaceFactory.OpenFromFile(WorkspacePath, 0) as IRasterWorkspace; pRasterDataset = pRasterWorkspace.OpenRasterDataset(strFilePath.Substring(strFilePath.LastIndexOf('\\') + 1)); pRasterLayer = new RasterLayerClass() as IRasterLayer; pRasterLayer.CreateFromDataset(pRasterDataset); axMapControl.ClearLayers(); axMapControl.AddLayer(pRasterLayer); axMapControl.ActiveView.Refresh(); //axMapControl.Extent = axMapControl.FullExtent; } else { return(SystemErrorType.enumDataIsIllegal); } } catch (Exception) { return(SystemErrorType.enumArcObjectHandleError); } return(SystemErrorType.enumOK); }
public static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); // To make changes to a Mosaic Dataset, a Standard or Advanced license is required. esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Flags to specify the operation to perform bool addToRD = true; // Create NDVI Custom Function Raster Dataset bool addToMD = false; // Add NDVI Custom Function to MD bool writeTemplateToXml = false; // Serialize a template form of the NDVI Custom Funtion to Xml. bool getfromXml = false; // Get a template object back from its serialized xml. #region Specify inputs. // Raster Dataset parameters string workspaceFolder = @"c:\temp"; string rasterDatasetName = "Dubai_ov.tif"; // Output parameters for Function Raster Dataset string outputFolder = @"c:\temp"; string outputName = "NDVICustomFunctionSample.afr"; // Mosaic dataset parameters // GDB containing the Mosaic Dataset string mdWorkspaceFolder = @"c:\temp\testGdb.gdb"; // Name of the mosaic dataset string mdName = "testMD"; // NDVI Custom Function Parameters string bandIndices = @"4 3"; // Xml file path to save to or read from xml. string xmlFilePath = @"e:\Dev\Samples CSharp\CustomRasterFunction\Xml\NDVICustomAFR.xml"; #endregion if (addToRD) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(workspaceFolder, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(rasterDatasetName); AddNDVICustomToRD(rasterDataset, outputFolder, outputName, bandIndices); // Cleanup workspaceFactory = null; rasterWorkspace = null; rasterDataset = null; } if (addToMD) { AddNDVICustomDataToMD(mdWorkspaceFolder, mdName, bandIndices, true); } if (writeTemplateToXml && xmlFilePath != "") { // Create a template with the NDVI Custom Function. IRasterFunctionTemplate ndviCustomFunctionTemplate = CreateNDVICustomTemplate(bandIndices); // Serialize the template to an xml file. bool status = WriteToXml(ndviCustomFunctionTemplate, xmlFilePath); } if (getfromXml && xmlFilePath != "") { // Create a RasterFunctionTemplate object from the serialized xml. object serializedObj = ReadFromXml(xmlFilePath); if (serializedObj is IRasterFunctionTemplate) { Console.WriteLine("Success."); } else { Console.WriteLine("Failed."); } } Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } catch (Exception exc) { Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } }
private void btnok_Click(object sender, EventArgs e) { ESRI.ArcGIS.DataManagementTools.CreatePansharpenedRasterDataset cpr = new CreatePansharpenedRasterDataset(); string inraster = GetLayerList(quanse.Text); string inpanchromaticimage = GetLayerList(duoguangpu.Text); cpr.in_raster = inraster; cpr.in_panchromatic_image = inpanchromaticimage; cpr.out_raster_dataset = textbaocun.Text; cpr.red_channel = Convert.ToInt32(redboduan.Text.ToString()); cpr.green_channel = Convert.ToInt32(greenboduan.Text.ToString()); cpr.blue_channel = Convert.ToInt32(blueboduan.Text.ToString()); cpr.infrared_channel = 1; cpr.red_weight = Convert.ToDouble(redquanzhong.Text.ToString()); cpr.green_weight = Convert.ToDouble(greenquanzhong.Text.ToString()); cpr.blue_weight = Convert.ToDouble(bluequanzhong.Text.ToString()); cpr.infrared_weight = Convert.ToDouble(jinhongwaiquanzhong.Text.ToString()); cpr.pansharpening_type = ronghefangfa.Text; cpr.sensor = chuanganqi.Text; Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; object obj = gp.Execute(cpr, null); IGeoProcessorResult gpResult = obj as IGeoProcessorResult; if (gpResult.Status == esriJobStatus.esriJobSucceeded) { DialogResult dr = MessageBox.Show("多波段合成操作成功"); if (dr == DialogResult.OK) { //结果添加到工作空间 if (addResult.Checked == true) { string fileFullName = textbaocun.Text; if (fileFullName == "") { return; } string filePathName = System.IO.Path.GetDirectoryName(fileFullName); string fileName = System.IO.Path.GetFileName(fileFullName); IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory(); //创建工作空间工厂 IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(filePathName, 0); //打开工作空间 IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace; //创建栅格工作空间 IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(fileName); //创建Dataset //影像金字塔创建与判断 IRasterPyramid2 pRasPymid = pRasterDataset as IRasterPyramid2; if (pRasPymid != null) { if (!(pRasPymid.Present)) { pRasPymid.Create();//创建金字塔 } } IRaster pRaster = pRasterDataset.CreateDefaultRaster(); IRasterLayer pRasterLayer = new RasterLayer(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; axmapcontrol.AddLayer(pLayer, 0); } } } else { MessageBox.Show("多波段合成操作失败"); } }
/// <summary> /// Create a Mosaic Dataset in the geodatabase provided using the parameters defined by MDParamaters. /// </summary> /// <param name="gdbWorkspace">Geodatabase to create the Mosaic dataser in.</param> public void CreateMosaicDataset(IWorkspace gdbWorkspace) { try { #region Global Declarations IMosaicDataset theMosaicDataset = null; IMosaicDatasetOperation theMosaicDatasetOperation = null; IMosaicWorkspaceExtensionHelper mosaicExtHelper = null; IMosaicWorkspaceExtension mosaicExt = null; #endregion #region CreateMosaicDataset try { Console.WriteLine("Create Mosaic Dataset: " + MDParameters.mosaicDatasetName + ".amd"); /// Setup workspaces. /// Create Srs ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); // Create the mosaic dataset creation parameters object. ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass(); // Set the number of bands for the mosaic dataset. // If defined as zero leave defaults if (MDParameters.mosaicDatasetBands != 0) { creationPars.BandCount = MDParameters.mosaicDatasetBands; } // Set the pixel type of the mosaic dataset. // If defined as unknown leave defaults if (MDParameters.mosaicDatasetBits != rstPixelType.PT_UNKNOWN) { creationPars.PixelType = MDParameters.mosaicDatasetBits; } // Create the mosaic workspace extension helper class. mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass(); // Find the right extension from the workspace. mosaicExt = mosaicExtHelper.FindExtension(gdbWorkspace); // Default is none. if (MDParameters.productDefinitionKey.ToLower() != "none") { // Set the product definition keyword and properties. // (The property is called band definition keyword and band properties in the object). ((ICreateMosaicDatasetParameters2)creationPars).BandDefinitionKeyword = MDParameters.productDefinitionKey; MDParameters.productDefinitionProps = SetBandProperties(MDParameters.productDefinitionKey); if (MDParameters.productDefinitionProps.Count == 0) { Console.WriteLine("Setting production definition properties failed."); return; } ((ICreateMosaicDatasetParameters2)creationPars).BandProperties = MDParameters.productDefinitionProps; } // Use the extension to create a new mosaic dataset, supplying the // spatial reference and the creation parameters object created above. theMosaicDataset = mosaicExt.CreateMosaicDataset(MDParameters.mosaicDatasetName, MDParameters.mosaicDatasetSrs, creationPars, MDParameters.configKeyword); } catch (Exception exc) { Console.WriteLine("Exception Caught while creating Mosaic Dataset: " + exc.Message); return; } #endregion #region OpenMosaicDataset Console.WriteLine("Opening Mosaic Dataset"); theMosaicDataset = null; // Use the extension to open the mosaic dataset. theMosaicDataset = mosaicExt.OpenMosaicDataset(MDParameters.mosaicDatasetName); // The mosaic dataset operation interface is used to perform operations on // a mosaic dataset. theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset); #endregion #region Preparing Raster Type Console.WriteLine("Preparing Raster Type"); // Create a Raster Type Name object. IRasterTypeName theRasterTypeName = new RasterTypeNameClass(); // Assign the name of the Raster Type to the name object. // The Name field accepts a path to an .art file as well // the name for a built in Raster Type. theRasterTypeName.Name = MDParameters.rasterTypeName; // Use the Open function from the IName interface to get the Raster Type object. IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open()); if (theRasterType == null) { Console.WriteLine("Raster Type not found " + MDParameters.rasterTypeName); } // Set the URI Filter on the loaded raster type. if (MDParameters.rasterTypeProductFilter != "") { // Get the supported URI filters from the raster type object using the // raster type properties interface. IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters; IItemURIFilter productFilter = null; for (int i = 0; i < mySuppFilters.Count; ++i) { // Set the desired filter from the supported filters. productFilter = (IItemURIFilter)mySuppFilters.get_Element(i); if (productFilter.Name == MDParameters.rasterTypeProductFilter) { theRasterType.URIFilter = productFilter; } } } // Enable the correct templates in the raster type. string[] rasterProductNames = MDParameters.rasterTypeProductName.Split(';'); bool enableTemplate = false; if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != "")) { // Get the supported item templates from the raster type. IItemTemplateArray templateArray = theRasterType.ItemTemplates; for (int i = 0; i < templateArray.Count; ++i) { // Go through the supported item templates and enable the ones needed. IItemTemplate template = templateArray.get_Element(i); enableTemplate = false; for (int j = 0; j < rasterProductNames.Length; ++j) { if (template.Name == rasterProductNames[j]) { enableTemplate = true; } } if (enableTemplate) { template.Enabled = true; } else { template.Enabled = false; } } } if (MDParameters.dataSourceSrs != null) { ((IRasterTypeProperties)theRasterType).SynchronizeParameters.DefaultSpatialReference = MDParameters.dataSourceSrs; } #endregion #region Add DEM To Raster Type if (MDParameters.rasterTypeAddDEM && ((IRasterTypeProperties)theRasterType).SupportsOrthorectification) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile( System.IO.Path.GetDirectoryName(MDParameters.rasterTypeDemPath), 0);; IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset( System.IO.Path.GetFileName(MDParameters.rasterTypeDemPath)); IGeometricFunctionArguments geometricFunctionArguments = new GeometricFunctionArgumentsClass(); geometricFunctionArguments.DEM = myRasterDataset; ((IRasterTypeProperties)theRasterType).OrthorectificationParameters = geometricFunctionArguments; } #endregion #region Preparing Data Source Crawler Console.WriteLine("Preparing Data Source Crawler"); // Create a new property set to specify crawler properties. IPropertySet crawlerProps = new PropertySetClass(); // Specify a file filter crawlerProps.SetProperty("Filter", MDParameters.dataSourceFilter); // Specify whether to search subdirectories. crawlerProps.SetProperty("Recurse", true); // Specify the source path. crawlerProps.SetProperty("Source", MDParameters.dataSource); // Get the recommended crawler from the raster type based on the specified // properties using the IRasterBuilder interface. IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps); #endregion #region Add Rasters Console.WriteLine("Adding Rasters"); // Create a AddRaster parameters object. IAddRastersParameters AddRastersArgs = new AddRastersParametersClass(); // Specify the data crawler to be used to crawl the data. AddRastersArgs.Crawler = theCrawler; // Specify the raster type to be used to add the data. AddRastersArgs.RasterType = theRasterType; // Use the mosaic dataset operation interface to add // rasters to the mosaic dataset. theMosaicDatasetOperation.AddRasters(AddRastersArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Create a calculate cellsize ranges parameters object. ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass(); // Use the mosaic dataset operation interface to calculate cellsize ranges. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Building Boundary Console.WriteLine("Building Boundary"); // Create a build boundary parameters object. IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass(); // Set flags that control boundary generation. boundaryArgs.AppendToExistingBoundary = true; // Use the mosaic dataset operation interface to build boundary. theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null); #endregion if (MDParameters.buildOverviews) { #region Defining Overviews Console.WriteLine("Defining Overviews"); // Create a define overview parameters object. IDefineOverviewsParameters defineOvArgs = new DefineOverviewsParametersClass(); // Use the overview tile parameters interface to specify the overview factor // used to generate overviews. ((IOverviewTileParameters)defineOvArgs).OverviewFactor = 3; // Use the mosaic dataset operation interface to define overviews. theMosaicDatasetOperation.DefineOverviews(defineOvArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Calculate cell size ranges to update the Min/Max pixel sizes. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Generating Overviews Console.WriteLine("Generating Overviews"); // Create a generate overviews parameters object. IGenerateOverviewsParameters genPars = new GenerateOverviewsParametersClass(); // Set properties to control overview generation. IQueryFilter genQuery = new QueryFilterClass(); ((ISelectionParameters)genPars).QueryFilter = genQuery; genPars.GenerateMissingImages = true; genPars.GenerateStaleImages = true; // Use the mosaic dataset operation interface to generate overviews. theMosaicDatasetOperation.GenerateOverviews(genPars, null); #endregion } #region Report Console.WriteLine("Success."); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in CreateMD: " + exc.Message); Console.WriteLine("Shutting down."); #endregion } }
/// <summary> /// 新建面图层 /// </summary> public void CreatePolygonLayer() { SaveFileDialog sfdPoint = new SaveFileDialog(); sfdPoint.Title = "请选择面图层的存储位置"; sfdPoint.Filter = "Shapefile(*.shp)|*.shp|All files(*.*)|*.*"; sfdPoint.RestoreDirectory = true; if (sfdPoint.ShowDialog() == DialogResult.OK) { LocalFilePath = sfdPoint.FileName; FilePath = System.IO.Path.GetDirectoryName(LocalFilePath); FileName = System.IO.Path.GetFileName(LocalFilePath); IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; IField pField = new FieldClass(); IFieldEdit pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = "SHAPE"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeometryDef = new GeometryDefClass(); IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit; pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; pFieldEdit.GeometryDef_2 = pGeometryDef; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory(); IWorkspace workspace; workspace = workspaceFactory.OpenFromFile(Application.StartupPath + "\\out", 0); //inPath栅格数据存储路径 IRasterWorkspace rastWork = (IRasterWorkspace)workspace; IRasterDataset rastDataset; rastDataset = rastWork.OpenRasterDataset("ps2010.img");//inName栅格文件名 IGeoDataset geoDS = rastDataset as IGeoDataset; pGeometryDefEdit.SpatialReference_2 = geoDS.SpatialReference; pFieldsEdit.AddField(pField); //新建字段 pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Length_2 = 15; pFieldEdit.Name_2 = "结构类型"; pFieldEdit.AliasName_2 = "结构类型"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldsEdit.AddField(pField); //新建字段 pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.Length_2 = 15; pFieldEdit.Name_2 = "权重"; pFieldEdit.AliasName_2 = "权重"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldsEdit.AddField(pField); IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0) as IFeatureWorkspace; pFeatureWorkspace.CreateFeatureClass(FileName, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); m_mapControl.AddShapeFile(FilePath, FileName); m_mapControl.ActiveView.Refresh(); } }
/// <summary> /// 结果统计 /// </summary> /// <param name="file">输入栅格</param> /// <param name="DTable">统计数据表</param> /// <returns>返回信息</returns> public bool Statistics(string file, out DataTable DTable) { DTable = null; long blockCount = 0; bool result; string sMsg; try { FileInfo fi = new FileInfo(file); string fileName = fi.Name; string filePath = fi.DirectoryName; //打开栅格数据 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory(); IWorkspace workspace = workspaceFactory.OpenFromFile(filePath, 0); //filePath栅格数据存储路径 if (workspace == null) { MessageBox.Show("Could not open the workspace."); } IRasterWorkspace rastWork = (IRasterWorkspace)workspace; //IRasterDataset rasterDatst = rastWork.OpenRasterDataset(fileName); //IRasterBandCollection rasterbandCollection = (IRasterBandCollection)rasterDatst; string fName = fileName.Substring(0, fileName.LastIndexOf(".")); if (File.Exists(@filePath + "\\" + fName + ".hdr")) { //创建栅格属性表 if (EnviVars.instance.GpExecutor.RasterTable(file, out sMsg)) { IRasterDataset rasterDatst = rastWork.OpenRasterDataset(fileName); IRasterBandCollection rasterbandCollection = (IRasterBandCollection)rasterDatst; for (int i = 0; i < rasterbandCollection.Count; i++) { //像素 IRasterBand rasterBand = rasterbandCollection.Item(i); IRawPixels rawPixels = (IRawPixels)rasterBand; IRasterProps rasterProps = (IRasterProps)rawPixels; //像元大小 double blockX = (double)rasterProps.MeanCellSize().X; double blockY = (double)rasterProps.MeanCellSize().Y; double blockArea = blockX * blockY; //栅格属性表 ITable table = rasterBand.AttributeTable; DataTable pTable = new DataTable(); for (int j = 0; j < table.Fields.FieldCount; j++) { pTable.Columns.Add(table.Fields.get_Field(j).Name); } pTable.Columns[0].ColumnName = "作物名称"; pTable.Columns[1].ColumnName = "像元值"; pTable.Columns[2].ColumnName = "像元个数(points)"; pTable.Columns.Add("所占比例"); pTable.Columns.Add("所占面积(㎡)"); ICursor pCursor = table.Search(null, false); //行数 IRow pRrow = pCursor.NextRow(); string Value = RDSCHA((@filePath + "\\" + fName + ".hdr"), "points"); string[] strs = Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); int y = 0; while (pRrow != null) { DataRow pRow = pTable.NewRow(); for (int k = 1; k < pRrow.Fields.FieldCount; k++) { pRow[k] = pRrow.get_Value(k).ToString(); } blockCount += long.Parse(pRow[2].ToString());//像元个数统计 pRow[0] = strs[Convert.ToInt32(pRrow.get_Value(1))].Trim(); pRow[4] = double.Parse(pRow[2].ToString()) * blockArea; pTable.Rows.Add(pRow); pRrow = pCursor.NextRow(); } DataRow row = pTable.NewRow(); for (int m = 0; m < pTable.Rows.Count; m++) { pTable.Rows[m]["所占比例"] = (double.Parse(pTable.Rows[m][2].ToString()) / blockCount).ToString("P3"); double s = double.Parse(pTable.Rows[m][2].ToString()); } DTable = pTable; } } else { XtraMessageBox.Show(sMsg, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { IRasterDataset rasterDatst = rastWork.OpenRasterDataset(fileName); IRasterBandCollection rasterbandCollection = (IRasterBandCollection)rasterDatst; for (int i = 0; i < rasterbandCollection.Count; i++) { //像素 IRasterBand rasterBand = rasterbandCollection.Item(i); IRawPixels rawPixels = (IRawPixels)rasterBand; IRasterProps rasterProps = (IRasterProps)rawPixels; double blockX = (double)rasterProps.MeanCellSize().X; double blockY = (double)rasterProps.MeanCellSize().Y; double blockArea = blockX * blockY; //像元大小 ITable table = rasterBand.AttributeTable; //栅格属性表 DataTable pTable = new DataTable(); for (int j = 1; j < table.Fields.FieldCount; j++) { pTable.Columns.Add(table.Fields.get_Field(j).Name); string t = table.Fields.get_Field(j).Name; } pTable.Columns[1].ColumnName = "像元个数(points)"; pTable.Columns.Add("所占比例"); pTable.Columns.Add("所占面积(㎡)"); ICursor pCursor = table.Search(null, false); IRow pRrow = pCursor.NextRow(); while (pRrow != null) { DataRow pRow = pTable.NewRow(); for (int k = 1; k < pRrow.Fields.FieldCount; k++) { object l = pRrow.get_Value(k).ToString(); pRow[k - 1] = pRrow.get_Value(k).ToString(); } blockCount += long.Parse(pRow[1].ToString());//像元个数统计 pRow[3] = double.Parse(pRow[1].ToString()) * blockArea; pTable.Rows.Add(pRow); pRrow = pCursor.NextRow(); } DataRow row = pTable.NewRow(); for (int m = 0; m < pTable.Rows.Count; m++) { pTable.Rows[m]["所占比例"] = (double.Parse(pTable.Rows[m][1].ToString()) / blockCount).ToString("P3"); double s = double.Parse(pTable.Rows[m][1].ToString()); } DTable = pTable; } } result = true; } catch (Exception ex) { XtraMessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); result = false; } return(result); }
public static void LoadGeoData(AxMapControl axMapControl1, AxMapControl axMapControl2, string strFileN) { string strFExtenN = System.IO.Path.GetExtension(strFileN); switch (strFExtenN) { case ".shp": { string strPath = System.IO.Path.GetDirectoryName(strFileN); string strFile = System.IO.Path.GetFileNameWithoutExtension(strFileN); axMapControl1.AddShapeFile(strPath, strFile); axMapControl2.ClearLayers(); axMapControl2.AddShapeFile(strPath, strFile); axMapControl2.Extent = axMapControl2.FullExtent; break; } case ".bmp": case ".tif": case ".jpg": case ".img": { IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass(); string pathName = System.IO.Path.GetDirectoryName(strFileN); string fileName = System.IO.Path.GetFileName(strFileN); IWorkspace pWS = pWSF.OpenFromFile(pathName, 0); IRasterWorkspace pRWS = pWS as IRasterWorkspace; IRasterDataset pRasterDataSet = pRWS.OpenRasterDataset(fileName); IRasterPyramid pRasPyramid = pRasterDataSet as IRasterPyramid; if (pRasPyramid != null) { if (!(pRasPyramid.Present)) { pRasPyramid.Create(); } } IRaster pRaster = pRasterDataSet.CreateDefaultRaster(); IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; axMapControl1.AddLayer(pLayer, 0); axMapControl2.ClearLayers(); axMapControl2.AddLayer(pLayer, 0); axMapControl2.Extent = axMapControl2.FullExtent; break; } case ".mxd": { if (axMapControl1.CheckMxFile(strFExtenN)) { axMapControl1.LoadMxFile(strFExtenN); } else { MessageBox.Show("所选择的文件不是Mxd文件!", "提示信息"); } break; } default: break; } }
public void DoSimulation() { try { //0准备开始模拟 ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager; FormANNCAWizard formANNCAWizard = VariableMaintainer.CurrentFormANNCAWizard; Random random = new Random(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //0.1获得数据 int rowCount = formANNCAWizard.CurrentStructRasterMetaData.RowCount; int columnCount = formANNCAWizard.CurrentStructRasterMetaData.ColumnCount; float[,] simulationStartImage = formANNCAWizard.SimulationStartImage; float[,] simulationEndImage = formANNCAWizard.SimulationEndImage; float[,] simulationImage = formANNCAWizard.SimulationImage; //0.2计算初始每种土地利用类型的单元数量 List <StructLanduseInfoAndCount> listLanduseInfoAndCount; //记录每种土地利用类型的单元数 listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>(); StructLanduseInfoAndCount landuseInfoAndCount; foreach (StructLanduseInfo structLanduseInfo in formANNCAWizard.LandUseClassificationInfo.AllTypes) { landuseInfoAndCount = new StructLanduseInfoAndCount(); landuseInfoAndCount.structLanduseInfo = structLanduseInfo; landuseInfoAndCount.LanduseTypeCount = 0; listLanduseInfoAndCount.Add(landuseInfoAndCount); } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount); } } //0.3显示输出结果窗体和图表窗体 dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40"); dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41"); dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String43")); Application.DoEvents(); //0.4绘制初始的图表 List <string> listPointPairListName = new List <string>(); List <string> notToDrawList = new List <string>(); notToDrawList.Add(resourceManager.GetString("String44")); dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName); dockableWindowGraphy.RefreshGraph(); int convertedCellCount = 0; //模拟中总共转换的元胞数量 int randomRow, randomColumn; //Monte Carlo方法选取的随机行和随机列 int convertCountInOneIteration = formANNCAWizard.ConvertCount / formANNCAWizard.Iterations; //每次迭代应转换的数量 int convertCountOnce = 0; //每次迭代已经转换的数量 float oldValue, newValue; //每次转换前土地利用类型的新值和旧值 int iteration = 0; //迭代的次数 List <float> listLanduseValues = new List <float>(); //记录土地利用类型值的List for (int j = 0; j < formANNCAWizard.LandUseClassificationInfo.AllTypesCount; j++) { listLanduseValues.Add(formANNCAWizard.LandUseClassificationInfo.AllTypes[j].LanduseTypeValue); } int neiWindowSize = formANNCAWizard.NeighbourWindowSize; int inputNeuronsCount = formANNCAWizard.InputNeuronsCount; int outputNeuronsCount = formANNCAWizard.OutputNeuronsCount; //2.开始进行转换 while (convertedCellCount < formANNCAWizard.ConvertCount) { convertCountOnce = 0; //2.3选择元胞与随机比较进行转换 //完成一次迭代 while (convertCountOnce < convertCountInOneIteration) { //随机选择一个栅格进行计算 randomRow = random.Next(0, rowCount); randomColumn = random.Next(0, columnCount); //计算逻辑为: //这里需要首先获取当前元胞的输入值 //然后通过神经网络计算每种土地利用类型的概率,乘以随机量 //然后选出最高的概率 //再查看是否是同样的土地利用类型,如果不是则转变 //如果不是并且概率大于一个值,则进行转变(目前先不用) //如果是空值,则不进行计算 if (simulationImage[randomRow, randomColumn] == -9999f) { continue; } double[] tempInputsArray = new double[inputNeuronsCount]; double[] tempOutputsArray = new double[outputNeuronsCount]; //获取该栅格的空间变量值 for (int i = 0; i < formANNCAWizard.ListVaribaleImages.Count; i++) { tempInputsArray[i] = formANNCAWizard.ListVaribaleImages[i][randomRow, randomColumn]; } //获取该栅格的邻域值 NeighbourOperator neighbourOperator = new NeighbourOperator(); float[] counts = neighbourOperator.GetNeighbourCount(simulationImage, randomRow, randomColumn, neiWindowSize, rowCount, columnCount, formANNCAWizard.LandUseClassificationInfo.AllTypesCount, listLanduseValues); for (int z = 0; z < counts.Length; z++) { tempInputsArray[formANNCAWizard.ListVaribaleImages.Count + z] = counts[z] / (neiWindowSize * neiWindowSize - 1); } //获取该栅格的土地利用类型 tempInputsArray[inputNeuronsCount - 1] = simulationImage[randomRow, randomColumn]; //计算神经网络输出的概率值 double[] output = formANNCAWizard.ANN.ANNActivationNetwork.Compute(tempInputsArray); double maxOutput = 0; int maxIndex = -1; Random r = new Random(1); double gamma; double disturbance; double probability; double[] probabilityArray = new double[output.Length]; for (int k = 0; k < output.Length; k++) { gamma = random.NextDouble(); disturbance = 1 + Math.Pow((-Math.Log(gamma)), formANNCAWizard.Delta); probabilityArray[k] = disturbance * output[k]; if (maxOutput < probabilityArray[k]) { maxOutput = probabilityArray[k]; maxIndex = k; } } probability = maxOutput; //计算最高值的最终概率 //未使用邻域因素模拟较为散,所以加入邻域因素。但可能导致难以达到需要的转换数量,模拟时间过长。 double neiValue = 0f; for (int t = 0; t < listLanduseValues.Count; t++) { if (listLanduseValues[t] == formANNCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue) { neiValue = Convert.ToDouble(counts[t]) / (neiWindowSize * neiWindowSize - 1); break; } } probability = probability * neiValue; //得到应转变为的土地利用类型值,以及当前土地利用类型值 newValue = formANNCAWizard.LandUseClassificationInfo.AllTypes[maxIndex].LanduseTypeValue; oldValue = simulationImage[randomRow, randomColumn]; //oldValue有时取到0值等不正确的值 bool isOldValueCorrect = false; for (int w = 0; w < formANNCAWizard.LandUseClassificationInfo.AllTypes.Count; w++) { if (oldValue == formANNCAWizard.LandUseClassificationInfo.AllTypes[w].LanduseTypeValue) { isOldValueCorrect = true; } } if (!isOldValueCorrect) { continue; } //根据转换矩阵进行判断是否可以转换 DataTable dtMatrix = formANNCAWizard.DTMatrix; int oldValueIndex = -1; for (int k = 0; k < formANNCAWizard.LandUseClassificationInfo.AllTypesCount; k++) { if (formANNCAWizard.LandUseClassificationInfo.AllTypes[k].LanduseTypeValue == oldValue) { oldValueIndex = k; break; } } string canConvert = dtMatrix.Rows[oldValueIndex][maxIndex].ToString(); if (canConvert == "0") { continue; } //与设定的阈值进行比较 double convertThreshold = formANNCAWizard.ConvertThreshold; if ((oldValue != newValue) && (probability >= convertThreshold)) { simulationImage[randomRow, randomColumn] = newValue; CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount); //以城市用地的转变量为总转变量的标准 for (int w = 0; w < formANNCAWizard.LandUseClassificationInfo.UrbanValues.Count; w++) { if (newValue == formANNCAWizard.LandUseClassificationInfo.UrbanValues[w].LanduseTypeValue) { convertCountOnce++; convertedCellCount++; } } //System.Diagnostics.Debug.WriteLine(convertedCellCount + " - Old: " + oldValue + " New: " + newValue); } } iteration++; System.Diagnostics.Debug.WriteLine("iteration: " + iteration); //2.4.刷新外部界面并输出中间结果数据 if (convertedCellCount == 1 || (iteration % formANNCAWizard.RefreshInterval == 0 && convertedCellCount != 0)) { //刷新图像 formANNCAWizard.SimulationImage = simulationImage; VariableMaintainer.IsNeedRefresh = true; //刷新图表窗体 string landuseTypeName = ""; for (int k = 0; k < listLanduseInfoAndCount.Count; k++) { for (int l = 0; l < listPointPairListName.Count; l++) { if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName; } else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName; } else { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName; } if (landuseTypeName == listPointPairListName[l]) { dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l); } } } dockableWindowGraphy.RefreshGraph(); //刷新输出结果窗体 dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString() + resourceManager.GetString("String46")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString()); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); } //输出中间结果 if (formANNCAWizard.IsOutput && (iteration % formANNCAWizard.OutputImageInterval == 0)) { GeneralOpertor.WriteDataFloat(formANNCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString() + "_ann_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount); } } //3.完成模拟,输出结果。 stopWatch.Stop(); VariableMaintainer.IsSimulationFinished = true; dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String48")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String49") + GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); //修改结果栅格的属性表 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = workspaceFactory.OpenFromFile( VariableMaintainer.CurrentFormANNCAWizard.OutputFolder, 0) as IRasterWorkspace; IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name); IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3; rasterDatasetEdit3.BuildAttributeTable(); IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3; rasterDataset3.Refresh(); if (formANNCAWizard.SimulationEndImageName != "") { //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_ANN_Reslut" + GeneralOpertor.GetNowString() + ".txt", // simulationImage, rowCount,columnCount); DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix( simulationImage, simulationEndImage, rowCount, columnCount, formANNCAWizard.LandUseClassificationInfo); double overallAccuracy = 0d; double kappa = 0d; GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formANNCAWizard.LandUseClassificationInfo); FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix(); formConfusionMatrix.DataTableValues = dtMatrixNumber; DataTable dtMatrixPercent = dtMatrixNumber.Clone(); GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent); formConfusionMatrix.DataTablePercents = dtMatrixPercent; formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber; formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %"; formConfusionMatrix.LabelKappa.Text = kappa.ToString("0.000"); float[] fomValues = GeneralOpertor.GetMultiFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage, rowCount, columnCount); formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] + "\nC: " + fomValues[2] + "\nD: " + fomValues[3]; formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000"); formConfusionMatrix.LabelPA.Text = fomValues[5].ToString("0.000"); formConfusionMatrix.LabelUA.Text = fomValues[6].ToString("0.000"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String84")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String83")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000")); dockableWindowOutput.AppendText("\n"); formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formANNCAWizard.SimulationLayerName; formConfusionMatrix.ShowDialog(); } dockableWindowOutput.AppendText("-------------------------------------------"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 获取栅格数据 /// </summary> /// <param name="pWorkSpace"></param> /// <param name="RasterName"></param> /// <returns></returns> public IRasterDataset GetRasterDataset(IRasterWorkspace pWorkSpace, string RasterName) { if (pWorkSpace == null) return null; try { return pWorkSpace.OpenRasterDataset(RasterName); } catch { return null; } }
//添加矢量和栅格数据 private void barButtonItem28_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { try { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.CheckFileExists = true; openFileDialog.Title = "打开Shape和Raster文件"; openFileDialog.Filter = "ESRI Shapefile(*.shp)|*.shp|栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string pFullPath = openFileDialog.FileName; if (pFullPath == "") { return; } int pIndex = pFullPath.LastIndexOf("\\"); string pFilePath = pFullPath.Substring(0, pIndex); //文件路径 string pFileName = pFullPath.Substring(pIndex + 1); //文件名 if (pFileName.Contains("shp")) { IWorkspaceFactory pWorkspaceFactory; IFeatureWorkspace pFeatureWorkspace; IFeatureLayer pFeatureLayer; //实例化ShapefileWorkspaceFactory工作空间,打开Shape文件 pWorkspaceFactory = new ShapefileWorkspaceFactory(); pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(pFilePath, 0); //创建并实例化要素集 IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName); pFeatureLayer = new FeatureLayer(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName; //ClearAllData(); //新增删除数据 Variable.pMapFrm.mainMapControl.Map.AddLayer(pFeatureLayer); Variable.pMapFrm.mainMapControl.ActiveView.Refresh(); } else { IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory(); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFilePath, 0); IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace; IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(pFileName); //影像金字塔判断与创建 IRasterPyramid3 pRasPyrmid; pRasPyrmid = pRasterDataset as IRasterPyramid3; if (pRasPyrmid != null) { if (!(pRasPyrmid.Present)) { pRasPyrmid.Create(); //创建金字塔 } } IRaster pRaster; pRaster = pRasterDataset.CreateDefaultRaster(); IRasterLayer pRasterLayer; pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; Variable.pMapFrm.mainMapControl.AddLayer(pLayer, 0); } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.ToString(), "异常"); } }
public void Reclassify() { InitColorRamp(); IRasterWorkspace pRWS; IWorkspaceFactory pWorkspaceFactory; pWorkspaceFactory = new RasterWorkspaceFactory(); String wsp; int r; int l; r = ComboBoxInLayer.Text.LastIndexOf("\\"); l = ComboBoxInLayer.Text.LastIndexOf("."); wsp = ComboBoxInLayer.Text.Substring(0, r); pRWS = (IRasterWorkspace)pWorkspaceFactory.OpenFromFile(wsp, 0); try { string ws = System.IO.Path.GetDirectoryName(ComboBoxInLayer.Text); string fbs = System.IO.Path.GetFileName(ComboBoxInLayer.Text); IWorkspaceFactory pWork = new RasterWorkspaceFactory(); IRasterWorkspace pRasterWs = pWork.OpenFromFile(ws, 0) as IRasterWorkspace; pRster = pRasterWs.OpenRasterDataset(fbs).CreateDefaultRaster(); IRasterBandCollection pRasterBandCol; pRasterBandCol = (IRasterBandCollection)pRster; IRawPixels pRawpixel; pRawpixel = (IRawPixels)pRasterBandCol.Item(0); IRasterProps pRasterProps; pRasterProps = (IRasterProps)pRawpixel; IPnt pSize; pSize = new DblPnt(); pSize.SetCoords(pRasterProps.Width, pRasterProps.Height); IPixelBlock pPixelBlock; pPixelBlock = pRawpixel.CreatePixelBlock(pSize); IPnt pPnt; pPnt = new DblPnt(); pPnt.X = 0; //the origin (top left corner) of the PixelBlock pPnt.Y = 0; pRawpixel.Read(pPnt, pPixelBlock); float PixelValue; minValue = 10000000; maxValue = 0; List <double> allValue = new List <double>(); for (int i = 0; i < pPixelBlock.Width; i++) { for (int j = 0; j < pPixelBlock.Height; j++) { PixelValue = (float)pPixelBlock.GetVal(0, i, j); allValue.Add(PixelValue); if (PixelValue != null) { if (PixelValue > maxValue) { maxValue = PixelValue; } if (PixelValue < minValue) { minValue = PixelValue; } } } } IRasterBand pRasterBand = new RasterBand(); pRasterBand = pRasterBandCol.Item(0); pRasterBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic; //double[] amount = pRasterBand.Histogram.Counts; pRasterStatistic = pRasterBand.Statistics; maxValue = (float)pRasterStatistic.Maximum; minValue = (float)pRasterStatistic.Minimum; //if (comboBox1.Text.Trim() == "等间隔") //{//先求每个等分间距 float Tmpincrement; DataRow FilterRow; Tmpincrement = (maxValue - minValue) / Convert.ToInt16(CmbLineCount.Text); FilterDataTable.Rows.Clear(); for (int i = 1; i <= Convert.ToInt16(CmbLineCount.Text); i++) { FilterRow = FilterDataTable.NewRow(); FilterRow[0] = Convert.ToString(minValue + Tmpincrement * (i - 1)) + "~" + Convert.ToString(minValue + Tmpincrement * i); FilterRow[1] = i; FilterRow[2] = i; FilterDataTable.Rows.Add(FilterRow); } DataGridFilterData.DataSource = FilterDataTable; DataGridFilterData.Refresh(); // } //else // { ////allValue.Sort(); ////List<double> valuesort = new List<double>(); ////valuesort = BublleSort(allValue); //allValue.Sort(); //int amount = pPixelBlock.Width * pPixelBlock.Height; //int Tmpincrement; //DataRow FilterRow; //Tmpincrement = (amount) / Convert.ToInt16(CmbLineCount.Text); //FilterDataTable.Rows.Clear(); //for (int i = 1; i < Convert.ToInt16(CmbLineCount.Text); i++) //{ // FilterRow = FilterDataTable.NewRow(); // if (allValue[Tmpincrement * (i - 1)] == allValue[Tmpincrement * (i)]) // break; // FilterRow[0] = Convert.ToString(allValue[Tmpincrement * (i - 1)]) + "~" + Convert.ToString(allValue[Tmpincrement * (i)]); // FilterRow[1] = i; // FilterDataTable.Rows.Add(FilterRow); //} //if (allValue[Tmpincrement * Convert.ToInt16(CmbLineCount.Text)] != maxValue) //{ // FilterRow = FilterDataTable.NewRow(); // FilterRow[0] = Convert.ToString(allValue[Tmpincrement * Convert.ToInt16(CmbLineCount.Text)]) + "~" + Convert.ToString(maxValue); // FilterRow[1] = Convert.ToInt16(CmbLineCount.Text); // FilterDataTable.Rows.Add(FilterRow); //} //DataGridFilterData.DataSource = FilterDataTable; //DataGridFilterData.Refresh(); //} } catch (Exception ex) { MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } }
//AE+C#修改栅格数据像素值 //private void ChangeRasterValue(IRasterDataset2 pRasterDatset, double dbScale, double dbOffset) //{ // IRaster2 pRaster2 = pRasterDatset.CreateFullRaster() as IRaster2; // IPnt pPntBlock = new PntClass(); // pPntBlock.X = 128; // pPntBlock.Y = 128; // IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock); // IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; // if (pRasterEdit.CanEdit()) // { // IRasterBandCollection pBands = pRasterDatset as IRasterBandCollection; // IPixelBlock3 pPixelblock3 = null; // int pBlockwidth = 0; // int pBlockheight = 0; // System.Array pixels; // IPnt pPnt = null; // object pValue; // long pBandCount = pBands.Count; // //获取Nodata // IRasterProps pRasterPro = pRaster2 as IRasterProps; // object pNodata = pRasterPro.NoDataValue; // //double dbNoData = Convert.ToDouble(((double[])pNodata)[0]); // double dbNoData = getNoDataValue(pNodata); // if (double.IsNaN(dbNoData)) // return; // do // { // pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3; // pBlockwidth = pPixelblock3.Width; // pBlockheight = pPixelblock3.Height; // for (int k = 0; k < pBandCount; k++) // { // pixels = (System.Array)pPixelblock3.get_PixelData(k); // for (int i = 0; i < pBlockwidth; i++) // { // for (int j = 0; j < pBlockheight; j++) // { // pValue = pixels.GetValue(i, j); // double ob = Convert.ToDouble(pValue); // if (ob != dbNoData) // { // ob *= dbScale; //翻转 // ob += dbOffset; //Z方向偏移 // } // //pixels.SetValue(ob, i, j); // IRasterProps pRP = pRaster2 as IRasterProps; // if (pRP.PixelType == rstPixelType.PT_CHAR) // pixels.SetValue(Convert.ToChar(ob), i, j); // else if (pRP.PixelType == rstPixelType.PT_UCHAR) // pixels.SetValue(Convert.ToByte(ob), i, j); // else if (pRP.PixelType == rstPixelType.PT_FLOAT) // pixels.SetValue(Convert.ToSingle(ob), i, j); // else if (pRP.PixelType == rstPixelType.PT_DOUBLE) // pixels.SetValue(Convert.ToDouble(ob), i, j); // else if (pRP.PixelType == rstPixelType.PT_ULONG) // pixels.SetValue(Convert.ToInt32(ob), i, j); // else // ; // } // } // pPixelblock3.set_PixelData(k, pixels); // System.Array textPixel = null; // textPixel = (System.Array)pPixelblock3.get_PixelData(k); // } // pPnt = pRasterCursor.TopLeft; // pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3); // } // while (pRasterCursor.Next()); // pRasterEdit.Refresh(); // System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); // } //} private bool rasterTransfer(IRasterLayer pRasterLayer, string szFilename, double[] dbRotateMatrix, double[] dbOffsetMatrix) { if (pRasterLayer == null || dbRotateMatrix == null || dbOffsetMatrix == null || dbRotateMatrix.Length != 9 || dbOffsetMatrix.Length != 3) { return(false); } //IRasterLayer pResultLayer = new RasterLayerClass(); //pResultLayer.CreateFromRaster(pRasterLayer.Raster); //pResult = new RasterLayer(); //pResult.co IGeoReference pGeoReference = pRasterLayer as IGeoReference; //XY平面平移和旋转 double dbScale = Math.Sqrt(dbRotateMatrix[0] * dbRotateMatrix[0] + dbRotateMatrix[1] * dbRotateMatrix[1]); double dbTheta = Math.Acos(dbRotateMatrix[0] / dbScale); IPoint pt = new PointClass(); pt.X = 0; pt.Y = 0; pGeoReference.Rotate(pt, -dbTheta / Math.PI * 180); //旋转 pGeoReference.Shift(-dbOffsetMatrix[0], -dbOffsetMatrix[1]); //平移 //pGeoReference.Rotate(pt, dbTheta / Math.PI * 180); //旋转 pGeoReference.ReScale(1 / dbScale, 1 / dbScale); //拉伸 try { if (!File.Exists(szFilename)) { pGeoReference.Rectify(szFilename, "TIFF"); IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); } //MessageBox.Show("转换完成!"); } catch (System.Exception ex) { //MessageBox.Show("转换出错!"); return(false); } finally { pGeoReference.Reset(); } //Open a raster file workspace. IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace) workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szFilename), 0); //Open a file raster dataset. IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(szFilename)); IRasterDataset2 rasterDataset2 = rasterDataset as IRasterDataset2; ClsRasterOp pRasterOp = new ClsRasterOp(); pRasterOp.ChangeRasterValue(rasterDataset2, dbRotateMatrix[8], dbOffsetMatrix[2]); ////Z方向变化 //System.Array pixels, dstPixels; //IPixelBlock3 pixelBlock3 = null; //IRaster2 pRaster2 = rasterDataset.Raster as IRaster2; //IRaster pRaster = pDstLayer.Raster; //IRasterEdit pEdit = pRaster as IRasterEdit; //IRasterCursor rasterCursor = pRaster2.CreateCursorEx(null);//null时为128*128 //do //{ // IPnt nSize = new PntClass(); // nSize.X = rasterCursor.PixelBlock.Width; // nSize.Y = rasterCursor.PixelBlock.Height; // pixelblock4 = rasterCursor.PixelBlock as IPixelBlock3; // pixelBlock3 = pRaster.CreatePixelBlock(nSize) as IPixelBlock3; // int nWidth = pixelBlock3.Width; // int nHeight = pixelBlock3.Height; // pixels = (System.Array)pixelBlock3.get_PixelData(0); // dstPixels = (System.Array)pixelblock4.get_PixelData(0); // for (int i = 0; i < nWidth; i++) // { // for (int j = 0; j < nHeight; j++) // { // object obj = pixels.GetValue(i, j); // double ob = Convert.ToDouble(obj); // ob *= dbRotateMatrix[8]; //翻转 // ob += dbOffsetMatrix[2]; //Z方向偏移 // dstPixels.SetValue(ob, i, j); // } // } // //写回数据 // pEdit.Write(rasterCursor.TopLeft, pixelblock4 as IPixelBlock); //} while (rasterCursor.Next() == true); return(true); }
/// <summary> /// 获取文件大小 /// </summary> /// <param name="task"></param> /// <returns></returns> private int CalculateSize(TransferTask task) { if (task.Category == TaskCategory.Files) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024)); } else if (task.Category == TaskCategory.Features) { DirectoryInfo dir = new DirectoryInfo(System.IO.Path.GetDirectoryName(task.SourceFileName)); string nickName = System.IO.Path.GetFileNameWithoutExtension(task.SourceFileName); FileInfo[] fs = dir.GetFiles(string.Format("*{0}*", nickName)); int length = 0; foreach (FileInfo f in fs) { length += (int)f.Length; } if (task.DestFileName.ToLower().Contains(".gdb")) { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { return(length / 1024 + 1150); } } else { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { return(length / 1024); } } } else if (task.Category == TaskCategory.Raster) { if (task.DestFileName.ToLower().Contains(".gdb")) { if (task.SourceFileName.ToLower().Contains(".gdb")) { IWorkspaceFactory inputWsF = null; IWorkspace inputWs = null; IRasterWorkspace inputRstWs = null; IRasterDataset2 inputRstDs = null; IRaster inputRaster = null; string inputDirectory = string.Empty; string inputRstName = string.Empty; string input = task.SourceFileName.Trim(); if (input.ToLower().Contains(".gdb")) { inputWsF = new FileGDBWorkspaceFactoryClass(); inputDirectory = input.Substring(0, input.IndexOf(".gdb") + 4); } else { inputWsF = new RasterWorkspaceFactoryClass(); inputDirectory = System.IO.Path.GetDirectoryName(input); } inputRstName = System.IO.Path.GetFileName(input); inputWs = inputWsF.OpenFromFile(inputDirectory, 0); inputRstWs = inputWs as IRasterWorkspace; inputRstDs = inputRstWs.OpenRasterDataset(inputRstName) as IRasterDataset2; inputRaster = inputRstDs.CreateDefaultRaster(); IRawBlocks inputRawBlocks = (IRawBlocks)inputRstDs; IRasterInfo inputRstInfo = inputRawBlocks.RasterInfo; IRasterProps in_rasterProps = (IRasterProps)inputRaster; int Height = in_rasterProps.Height; int Width = in_rasterProps.Width; rstPixelType in_rstPT = in_rasterProps.PixelType; int BandsCount = inputRstInfo.BandCount; Dictionary <rstPixelType, int> DictPT = new Dictionary <rstPixelType, int>(); DictPT.Clear(); DictPT.Add(rstPixelType.PT_DOUBLE, 64); DictPT.Add(rstPixelType.PT_FLOAT, 32); DictPT.Add(rstPixelType.PT_LONG, 32); DictPT.Add(rstPixelType.PT_SHORT, 32); DictPT.Add(rstPixelType.PT_UCHAR, 8); DictPT.Add(rstPixelType.PT_ULONG, 32); DictPT.Add(rstPixelType.PT_USHORT, 32); DictPT.Add(rstPixelType.PT_CHAR, 8); int Depth = 32; DictPT.TryGetValue(in_rasterProps.PixelType, out Depth); return((int)(1.0 * Height * Width * BandsCount * Depth / 8.0 / 1024)); } else { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024 + 1150)); } } else { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024)); } } } return(task.Size); }
public void DoSimulation() { //0准备开始模拟 ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager; FormDTCAWizard formDTCAWizard = VariableMaintainer.CurrentFormDTCAWizard; Random random = new Random(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //0.1获得数据 int rowCount = formDTCAWizard.CurrentStructRasterMetaData.RowCount; int columnCount = formDTCAWizard.CurrentStructRasterMetaData.ColumnCount; float[,] simulationStartImage = formDTCAWizard.SimulationStartImage; float[,] simulationEndImage = formDTCAWizard.SimulationEndImage; float[,] simulationImage = formDTCAWizard.SimulationImage; //0.2计算初始每种土地利用类型的单元数量 List <StructLanduseInfoAndCount> listLanduseInfoAndCount; //记录每种土地利用类型的单元数 listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>(); StructLanduseInfoAndCount landuseInfoAndCount; foreach (StructLanduseInfo structLanduseInfo in formDTCAWizard.LandUseClassificationInfo.AllTypes) { landuseInfoAndCount = new StructLanduseInfoAndCount(); landuseInfoAndCount.structLanduseInfo = structLanduseInfo; landuseInfoAndCount.LanduseTypeCount = 0; listLanduseInfoAndCount.Add(landuseInfoAndCount); } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount); } } //0.3显示输出结果窗体和图表窗体 dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40"); dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41"); dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String43")); Application.DoEvents(); //0.4绘制初始的图表 List <string> listPointPairListName = new List <string>(); List <string> notToDrawList = new List <string>(); notToDrawList.Add(resourceManager.GetString("String44")); dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName); dockableWindowGraphy.RefreshGraph(); int convertedCellCount = 0; //模拟中总共转换的元胞数量 int randomRow, randomColumn; //Monte Carlo方法选取的随机行和随机列 int convertCountInOneIteration = formDTCAWizard.ConvertCount / formDTCAWizard.Iterations; //每次迭代应转换的数量 int convertCountOnce = 0; //每次迭代已经转换的数量 float oldValue, newValue; //每次转换前土地利用类型的新值和旧值 int iteration = 0; //迭代的次数 //float gamma = 1f / formDTCAWizard.Iterations; //float gamma = 0.4f; DecisionTree decisionTree = formDTCAWizard.CurrentDecisionTree; List <float> listUrbanValues = new List <float>(); for (int j = 0; j < formDTCAWizard.LandUseClassificationInfo.UrbanValues.Count; j++) { listUrbanValues.Add(formDTCAWizard.LandUseClassificationInfo.UrbanValues[j].LanduseTypeValue); } int neiWindowSize = formDTCAWizard.NeighbourWindowSize; try { //2.开始进行转换 while (convertedCellCount < formDTCAWizard.ConvertCount) { convertCountOnce = 0; while (convertCountOnce < convertCountInOneIteration) { //随机选择一个栅格进行计算 randomRow = random.Next(0, rowCount); randomColumn = random.Next(0, columnCount); //计算逻辑为: //这里需要首先获取当前元胞的输入值 //然后通过决策树计算是否发生转变 //然后看随机数是否小于等于预定值,则进行转变 //如果是空值,则不进行计算 if (simulationImage[randomRow, randomColumn] == -9999f) { continue; } //如果模拟影像该栅格是空值,也不进行计算 if (formDTCAWizard.ListVaribaleImages[formDTCAWizard.ListVaribaleImages.Count - 1][randomRow, randomColumn] == -9999f) { continue; } //如果已经是城市用地,则不计算 if (simulationImage[randomRow, randomColumn] == formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue) { continue; } double[] tempInputsArray = new double[formDTCAWizard.ListVaribaleImages.Count]; //获取该栅格的各空间变量值和其他输入变量 for (int i = 0; i < formDTCAWizard.ListVaribaleImages.Count; i++) { tempInputsArray[i] = formDTCAWizard.ListVaribaleImages[i][randomRow, randomColumn]; } //获取该栅格的邻域中城市用地数量 tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 2] = CommonLibrary.GeneralOpertor.GetNeighbors(randomRow, randomColumn, simulationImage, rowCount, columnCount, neiWindowSize, listUrbanValues); //获取该栅格当前的土地利用类型值 tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 1] = simulationImage[randomRow, randomColumn]; //计算决策树输出的转换值 int output = formDTCAWizard.CurrentDecisionTree.Compute(tempInputsArray); //如果计算为不转换,则不进行转换 if (output == 0) { continue; } //如果可以转换为城市用地 if (!formDTCAWizard.LandUseClassificationInfo.IsExistInConvertValue(simulationImage[randomRow, randomColumn])) { continue; } Random r = new Random(1); double convertThreshold = random.NextDouble(); //得到应转变为的土地利用类型值,以及当前土地利用类型值 newValue = formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue; oldValue = simulationImage[randomRow, randomColumn]; //未使用邻域因素模拟较为散,所以加入邻域因素 double neighbourValue = tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 2] / (neiWindowSize * neiWindowSize - 1); //double probability = convertThreshold * neighbourValue; //if ((oldValue != newValue) && (convertThreshold <= gamma)) //if ((oldValue != newValue) && (probability >= gamma)) //20170619添加限制层数据 // if ((VariableMaintainer.RestrictImage[randomRow, randomColumn] == 2) || (VariableMaintainer.RestrictImage[randomRow, randomColumn] == 1)) //if (VariableMaintainer.RestrictImage[randomRow, randomColumn] == 1) // continue; //引入随机因素,如果邻域因素大于随机数 if ((oldValue != newValue) && (neighbourValue > convertThreshold)) { simulationImage[randomRow, randomColumn] = newValue; CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount); convertCountOnce++; convertedCellCount++; //System.Diagnostics.Debug.WriteLine(convertedCellCount + " - Old: " + oldValue + " New: " + newValue); } } iteration++; //2.4.刷新外部界面并输出中间结果数据 if (convertedCellCount == 1 || (iteration % formDTCAWizard.RefreshInterval == 0 && convertedCellCount != 0)) { //刷新图像 formDTCAWizard.SimulationImage = simulationImage; VariableMaintainer.IsNeedRefresh = true; //刷新图表窗体 string landuseTypeName = ""; for (int k = 0; k < listLanduseInfoAndCount.Count; k++) { for (int l = 0; l < listPointPairListName.Count; l++) { if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName; } else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName; } else { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName; } if (landuseTypeName == listPointPairListName[l]) { dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l); } } } dockableWindowGraphy.RefreshGraph(); //刷新输出结果窗体 dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString() + resourceManager.GetString("String46")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString()); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); } //输出中间结果 if (formDTCAWizard.IsOutput && (iteration % formDTCAWizard.OutputImageInterval == 0)) { GeneralOpertor.WriteDataFloat(formDTCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString() + "_ann_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount); } } } catch (Exception ex) { MessageBox.Show("DTCA: " + ex.Message); } //3.完成模拟,输出结果。 stopWatch.Stop(); //isFinished = true; VariableMaintainer.IsSimulationFinished = true; dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String48")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String49") + GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); //修改结果栅格的属性表 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = workspaceFactory.OpenFromFile( VariableMaintainer.CurrentFormDTCAWizard.OutputFolder, 0) as IRasterWorkspace; IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name); IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3; rasterDatasetEdit3.BuildAttributeTable(); IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3; rasterDataset3.Refresh(); if (formDTCAWizard.SimulationEndImageName != "") { //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_ANN_Reslut" + GeneralOpertor.GetNowString() + ".txt", // simulationImage, rowCount,columnCount); StructBinaryConfusionMatrix structConfusionMatrix = GeneralOpertor.GetBinaryAccuracy( simulationImage, simulationEndImage, rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo); string accuracyString = GeneralOpertor.GetBinaryAccuracyReportString(structConfusionMatrix, convertedCellCount); dockableWindowOutput.AppendText(accuracyString); DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix( simulationImage, simulationEndImage, rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo); double overallAccuracy = 0d; double kappa = 0d; GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formDTCAWizard.LandUseClassificationInfo); FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix(); formConfusionMatrix.DataTableValues = dtMatrixNumber; DataTable dtMatrixPercent = dtMatrixNumber.Clone(); GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent); formConfusionMatrix.DataTablePercents = dtMatrixPercent; formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber; formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %"; formConfusionMatrix.LabelKappa.Text = kappa.ToString("0.000"); float[] fomValues = GeneralOpertor.GetBinaryFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage, rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue); formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] + "\nC: " + fomValues[2] + "\nD: " + fomValues[3]; formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000"); formConfusionMatrix.LabelPA.Text = fomValues[5].ToString("0.000"); formConfusionMatrix.LabelUA.Text = fomValues[6].ToString("0.000"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String84")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String83")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000")); dockableWindowOutput.AppendText("\n"); formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formDTCAWizard.SimulationLayerName; formConfusionMatrix.ShowDialog(); } dockableWindowOutput.AppendText("-------------------------------------------"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); }
/// <summary> /// 最终版-------视域分析------ /// </summary> /// <returns></returns> public void ViewAnalyze() { Geoprocessor g = new Geoprocessor(); //实例化一个GP对象 g.OverwriteOutput = true; try { var filename1 = ApplicationV.Data_MonitorPath + "\\va_original"; Visibility v = new Visibility(); v.in_raster = (BuildingLayer as IRasterLayer).Raster; v.in_observer_features = (CameraLayer as IFeatureLayer).FeatureClass; v.out_raster = filename1; //创建Visibility分析工具 v.z_factor = 1; v.outer_radius = buffersize.ToString(); g.Execute(v, null); object sev = ""; Console.WriteLine(g.GetMessages(ref sev)); } catch (Exception e) { object sev = ""; MessageBox.Show(g.GetMessages(ref sev)); return; } //添加第一步处理后的数据 这里还要进行【条件函数】 //新建工作空间 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(ApplicationV.Data_MonitorPath, 0); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspace; IRasterDataset firstDataset = rasterWorkspace.OpenRasterDataset("va_original"); IRaster firstraster = firstDataset.CreateDefaultRaster(); var pRasterLayer = new RasterLayerClass(); pRasterLayer.CreateFromRaster(firstraster); ILayer pLayer = pRasterLayer as ILayer; pLayer.Visible = false; mainMapControl.AddLayer(pLayer, mainMapControl.LayerCount - 1); try { var filename2 = ApplicationV.Data_MonitorPath + "\\va_result"; var con = new Con(); con.in_conditional_raster = firstraster; con.where_clause = "value=0"; con.in_true_raster_or_constant = 0; con.in_false_raster_or_constant = 120; con.out_raster = filename2; g.Execute(con, null); } catch (Exception e) { object sev = ""; MessageBox.Show(g.GetMessages(ref sev)); return; } //最终导入图层 IRasterDataset SecondDataset = rasterWorkspace.OpenRasterDataset("va_result"); IRaster secondraster = SecondDataset.CreateDefaultRaster(); var ppRasterLayer = new RasterLayerClass(); ppRasterLayer.CreateFromRaster(secondraster); ILayer ppLayer = ppRasterLayer as ILayer; mainMapControl.AddLayer(ppLayer, MapUtils.GetLayerIndex("建筑") + 1); }
public void DoSimulation() { //0准备开始模拟 ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager; FormLogisticCAWizard formLogisticCAWizard = VariableMaintainer.CurrentFormLogisticCAWizard; Random random = new Random(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //0.1获得数据 int rowCount = formLogisticCAWizard.CurrentStructRasterMetaData.RowCount; int columnCount = formLogisticCAWizard.CurrentStructRasterMetaData.ColumnCount; float[,] simulationStartImage = formLogisticCAWizard.SimulationStartImage; float[,] simulationEndImage = formLogisticCAWizard.SimulationEndImage; float[,] simulationImage = formLogisticCAWizard.SimulationImage; //0.2计算初始每种土地利用类型的单元数量 List <StructLanduseInfoAndCount> listLanduseInfoAndCount; //记录每种土地利用类型的单元数 listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>(); StructLanduseInfoAndCount landuseInfoAndCount; foreach (StructLanduseInfo structLanduseInfo in formLogisticCAWizard.LandUseClassificationInfo.AllTypes) { landuseInfoAndCount = new StructLanduseInfoAndCount(); landuseInfoAndCount.structLanduseInfo = structLanduseInfo; landuseInfoAndCount.LanduseTypeCount = 0; listLanduseInfoAndCount.Add(landuseInfoAndCount); } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount); } } //0.3显示输出结果窗体和图表窗体 dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40"); dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41"); dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String43")); Application.DoEvents(); //0.4绘制初始的图表 List <string> listPointPairListName = new List <string>(); List <string> notToDrawList = new List <string>(); notToDrawList.Add(resourceManager.GetString("String44")); dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName); dockableWindowGraphy.RefreshGraph(); //1.计算Pg float[,] pg = new float[rowCount, columnCount]; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { if (simulationStartImage[i, j] == formLogisticCAWizard.LandUseClassificationInfo.NullValue.LanduseTypeValue) { pg[i, j] = formLogisticCAWizard.LandUseClassificationInfo.NullValue.LanduseTypeValue; } else { pg[i, j] += Convert.ToSingle(formLogisticCAWizard.Coefficents[0]); for (int k = 0; k < formLogisticCAWizard.ListVariableLayersName.Count; k++) { pg[i, j] += Convert.ToSingle(formLogisticCAWizard.Coefficents[k + 1]) * formLogisticCAWizard.VaribaleImages[k][i, j]; } } pg[i, j] = 1 / (1 + Convert.ToSingle(Math.Exp(-1 * pg[i, j]))); } } //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\pg.txt", pg, rowCount, columnCount); int convertedCellCount = 0; //模拟中总共转换的元胞数量 List <float> neighbours; //Moore领域的元胞 float omega; //扩散系数 float conSuitable; //适应度函数 float maxPct; //每次迭代时最大的Pct值 float[,] pct; float[,] pst; float sumPtt = 0; //Ptt的总和 int randomRow, randomColumn; //Monte Carlo方法选取的随机行和随机列 int convertCountInOneIteration = formLogisticCAWizard.ConvertCount / formLogisticCAWizard.Iterations; //每次迭代应转换的数量 int convertCountOnce = 0; //每次迭代已经转换的数量 float oldValue, newValue; //每次转换前土地利用类型的新值和旧值 int[,] changeCells = new int[rowCount, columnCount]; //记录每次转换为城市的单元。 int iteration = 0; //迭代的次数 //2.开始进行转换 while (convertedCellCount < formLogisticCAWizard.ConvertCount) { if (convertedCellCount % formLogisticCAWizard.OutputImageInterval == 0 && convertedCellCount != 0) { changeCells = new int[rowCount, columnCount]; } convertCountOnce = 0; //2.1每次迭代先得到Pct和MaxPct maxPct = float.MinValue; pct = new float[rowCount, columnCount]; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { neighbours = CommonLibrary.GeneralOpertor.GetMooreNeighbors(i, j, simulationImage, rowCount, columnCount); omega = Convert.ToSingle(CommonLibrary.GeneralOpertor.GetUrbanCount(neighbours, formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue)) / (neighbours.Count - 1); if (formLogisticCAWizard.LandUseClassificationInfo.IsExistInConvertValue(simulationImage[i, j])) { conSuitable = 1f; } else { conSuitable = 0f; } pct[i, j] = pg[i, j] * conSuitable * omega; if (pct[i, j] > maxPct) { maxPct = pct[i, j]; } } } //CommonOperator.WriteData(Application.StartupPath + @"\\OutputData\pct.txt", pct, structAsciiImageFileMetaData); //2.2再得到Pst pst = new float[rowCount, columnCount]; sumPtt = 0; //2.2.1先得到ptt和Ptt的总和 for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { pst[i, j] = pct[i, j] * Convert.ToSingle(Math.Exp(-1f * formLogisticCAWizard.Delta * (1f - pct[i, j] / maxPct))); sumPtt += pst[i, j]; } } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { pst[i, j] = convertCountInOneIteration * pst[i, j] / sumPtt; } } //CommonOperator.WriteData(Application.StartupPath + @"\\OutputData\pst.txt", pst, structAsciiImageFileMetaData); //2.3选择元胞与随机比较进行转换 //完成一次迭代 while (convertCountOnce < convertCountInOneIteration) { randomRow = random.Next(0, rowCount); randomColumn = random.Next(0, columnCount); if (pst[randomRow, randomColumn] > Convert.ToSingle(random.NextDouble())) { oldValue = simulationImage[randomRow, randomColumn]; newValue = formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue; simulationImage[randomRow, randomColumn] = newValue; CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount); convertCountOnce++; convertedCellCount++; changeCells[randomRow, randomColumn] = 1; } } iteration++; //2.4.刷新外部界面并输出中间结果数据 if (convertedCellCount == 1 || (iteration % formLogisticCAWizard.RefreshInterval == 0 && convertedCellCount != 0)) { //刷新图像 formLogisticCAWizard.SimulationImage = simulationImage; VariableMaintainer.IsNeedRefresh = true; //刷新图表窗体 string landuseTypeName = ""; for (int k = 0; k < listLanduseInfoAndCount.Count; k++) { for (int l = 0; l < listPointPairListName.Count; l++) { if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName; } else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT") { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName; } else { landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName; } if (landuseTypeName == listPointPairListName[l]) { dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l); } } } dockableWindowGraphy.RefreshGraph(); //刷新输出结果窗体 dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString() + resourceManager.GetString("String46")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString()); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); } //输出中间结果 if (formLogisticCAWizard.IsOutput && (iteration % formLogisticCAWizard.OutputImageInterval == 0)) { GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString() + "_lr_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount); } } //3.完成模拟,输出结果。 stopWatch.Stop(); VariableMaintainer.IsSimulationFinished = true; dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String48")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String49") + GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); //修改结果栅格的属性表 IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = workspaceFactory.OpenFromFile( VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder, 0) as IRasterWorkspace; IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name); IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3; rasterDatasetEdit3.BuildAttributeTable(); IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3; rasterDataset3.Refresh(); if (formLogisticCAWizard.SimulationEndImageName != "") { //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_LR_Reslut" + GeneralOpertor.GetNowString() + ".txt", // simulationImage, rowCount, columnCount); StructBinaryConfusionMatrix structConfusionMatrix = GeneralOpertor.GetBinaryAccuracy( simulationImage, simulationEndImage, rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo); string accuracyString = GeneralOpertor.GetBinaryAccuracyReportString(structConfusionMatrix, convertedCellCount); dockableWindowOutput.AppendText(accuracyString); DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix( simulationImage, simulationEndImage, rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo); double overallAccuracy = 0d; double kappa = 0d; GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formLogisticCAWizard.LandUseClassificationInfo); FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix(); formConfusionMatrix.DataTableValues = dtMatrixNumber; DataTable dtMatrixPercent = dtMatrixNumber.Clone(); GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent); formConfusionMatrix.DataTablePercents = dtMatrixPercent; formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber; formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %"; formConfusionMatrix.LabelKappa.Text = kappa.ToString("0.000"); float[] fomValues = GeneralOpertor.GetBinaryFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage, rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue); formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] + "\nC: " + fomValues[2] + "\nD: " + fomValues[3]; formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000"); formConfusionMatrix.LabelPA.Text = fomValues[5].ToString("0.000"); formConfusionMatrix.LabelUA.Text = fomValues[6].ToString("0.000"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String84")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent)); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String83")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000")); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000")); dockableWindowOutput.AppendText("\n"); formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formLogisticCAWizard.SimulationLayerName; formConfusionMatrix.ShowDialog(); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); } dockableWindowOutput.AppendText("-------------------------------------------"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.AppendText("\n"); dockableWindowOutput.ScrollTextbox(); Application.DoEvents(); }