/// <summary>
 /// Will perform a focal raster operation on an input raster all bands
 /// </summary>
 /// <param name="inRaster">either IRaster, IRasterDataset, or a valid path pointing to a raster</param>
 /// <param name="clm">number of columns (cells)</param>
 /// <param name="rws">number of rows</param>
 /// <param name="statType">the type of operation</param>
 /// <returns>a IRaster that can be used for further analysis</returns>
 public IFunctionRasterDataset calcFocalStatisticsFunction(object inRaster, int clm, int rws, focalType statType)
 {
     IFunctionRasterDataset iR1 = createIdentityRaster(inRaster,rstPixelType.PT_FLOAT);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     switch (statType)
     {
         case focalType.MIN:
         case focalType.MAX:
         case focalType.MEAN:
         case focalType.STD:
             return calcFocalStatisticsRectangle(inRaster, clm, rws, statType);
         case focalType.SUM:
             IFunctionRasterDataset mRs = calcFocalStatisticsFunction(inRaster, clm, rws, focalType.MEAN);
             return calcArithmaticFunction(mRs, clm * rws, esriRasterArithmeticOperation.esriRasterMultiply);
             //rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperSum();
             //break;
         case focalType.MODE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMode();
             break;
         case focalType.MEDIAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMedian();
             break;
         case focalType.VARIANCE:
             IFunctionRasterDataset rs = calcFocalStatisticsFunction(inRaster, clm, rws,focalType.STD);
             return calcArithmaticFunction(rs,2,esriRasterArithmeticOperation.esriRasterPower);
         case focalType.UNIQUE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperUnique();
             break;
         case focalType.ENTROPY:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperEntropy();
             break;
         case focalType.ASM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperProbability();
             break;
         default:
             break;
     }
     FunctionRasters.FocalFunctionArguments args = new FunctionRasters.FocalFunctionArguments(this);
     args.Rows = rws;
     args.Columns = clm;
     //args.WindowType = windowType.RECTANGLE;
     args.InRaster = iR1;
     args.Operation = statType;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        static void Main(string[] args)
        {
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit;

            #region Initialize License
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
                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
            {
                #region Specify input directory and dataset name
                // The directory which contains the Panchromatic Image.
                string panDir = @"C:\Data\QB\Pan";
                // The directory which contains the Multispectral Image.
                string rgbDir = @"C:\Data\QB\MS";
                
                string panImageName = "05JAN27104436-P1BS-005533787010_01_P002.TIF";
                string rgbImageName = "05JAN27104436-M1BS-005533787010_01_P002.TIF";

                // Output filename.
                string outputDataset = @"c:\Temp\QBTemplateCS.afr";
                #endregion

                #region Initialize
                // Setup Workspaces.
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory");
                IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IRasterWorkspace panRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(panDir, 0);
                IRasterWorkspace rgbRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(rgbDir, 0);

                // Open Datasets
                IRasterDataset panDataset = panRasterWorkspace.OpenRasterDataset(panImageName);
                IRasterDataset rgbDataset = rgbRasterWorkspace.OpenRasterDataset(rgbImageName);
                #endregion

                #region Create Variables
                // Create one variable of type IRasterFunctionVariable for each 
                // Raster Dataset opened above
                
                // Create a new Raster Function Variable
                IRasterFunctionVariable panVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                panVar.Name = "panImage";
                // Describe the variable
                panVar.Description = "Panchromatic Image to be used for pansharpening";
                // Specify whether it represents a dataset
                panVar.IsDataset = true;

                // Create a new Raster Function Variable
                IRasterFunctionVariable rgbVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                rgbVar.Name = "rgbImage";
                // Describe the variable
                rgbVar.Description = "Multispectral Image to be used for pansharpening";
                // Specify whether it represents a dataset
                rgbVar.IsDataset = true;
                #endregion

                #region Prepare the Pan Image
                // Setup statistics for each band
                IArray statsArrayPan = new ArrayClass();
                IRasterStatistics statsPanBand = new RasterStatisticsClass();
                statsPanBand.Minimum = 1;
                statsPanBand.Maximum = 2047;
                statsArrayPan.Add(statsPanBand);
                // Create the arguments object for the stretching function
                IStretchFunctionArguments stretchingPanFunctionArguements = new StretchFunctionArgumentsClass();
                // Set the stretching type
                stretchingPanFunctionArguements.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingPanFunctionArguements.Statistics = statsArrayPan;
                // Set the input raster, in this case, the variable for the Pan Image
                stretchingPanFunctionArguements.Raster = panVar;

                // Create the function object to stretch the Pan Image.
                IRasterFunction stretchingPanFunction = new StretchFunction();

                // Create a Raster Function Template object for the stretch function
                IRasterFunctionTemplate stretchingPanFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingPanFunctionT.Function = (IRasterFunction)stretchingPanFunction;
                // Set the arguments for the function
                stretchingPanFunctionT.Arguments = stretchingPanFunctionArguements;
                #endregion

                #region Prepare the Multispectral (RGB) Image
                // Create an array which defines the order of bands
                ILongArray bandIDs = new LongArrayClass();
                bandIDs.Add(2);
                bandIDs.Add(1);
                bandIDs.Add(0);
                // Create an Extract Band Function Arguments object
                IExtractBandFunctionArguments extractRgbBandFunctionArgs = (IExtractBandFunctionArguments)
                    new ExtractBandFunctionArguments();
                // Set the order of bands of the output
                extractRgbBandFunctionArgs.BandIDs = bandIDs;
                // Set the input raster, in this case the variable for the Multispectral Image
                extractRgbBandFunctionArgs.Raster = rgbVar;

                // Create the Extract Band Function object
                IRasterFunction extractRgbBandFunction = new ExtractBandFunction();

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate extractRgbBandFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                extractRgbBandFunctionT.Function = (IRasterFunction)extractRgbBandFunction;
                // Set the arguments for the function
                extractRgbBandFunctionT.Arguments = extractRgbBandFunctionArgs;

                // Setup statistics for each band
                IArray statsArray = new ArrayClass();
                IRasterStatistics statsMulBand1 = new RasterStatisticsClass();
                statsMulBand1.Minimum = 100;
                statsMulBand1.Maximum = 1721;
                statsArray.Add(statsMulBand1);
                IRasterStatistics statsMulBand2 = new RasterStatisticsClass();
                statsMulBand2.Minimum = 95;
                statsMulBand2.Maximum = 2047;
                statsArray.Add(statsMulBand2);
                IRasterStatistics statsMulBand3 = new RasterStatisticsClass();
                statsMulBand3.Minimum = 34;
                statsMulBand3.Maximum = 2006;
                statsArray.Add(statsMulBand3);

                // Create a stretching function for the multispectral image
                IRasterFunction stretchingRGBFunction = new StretchFunction();
                // Create an arguments object for the stretch function
                IStretchFunctionArguments stretchingRGBFunctionArguments = 
                    new StretchFunctionArgumentsClass();
                // Set the type of stretchings to perform
                stretchingRGBFunctionArguments.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingRGBFunctionArguments.Statistics = statsArray;
                // Set the extract band function template created above as the input
                stretchingRGBFunctionArguments.Raster = extractRgbBandFunctionT;

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate stretchingRGBFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingRGBFunctionT.Function = (IRasterFunction)stretchingRGBFunction;
                // Set the arguments for the function
                stretchingRGBFunctionT.Arguments = stretchingRGBFunctionArguments;
                #endregion

                #region Pansharpen the Pan Image with the Multispectral
                // Create a Raster Function Arguments object for the pansharpen function
                IPansharpeningFunctionArguments pansharpFunctionArguements = 
                    new PansharpeningFunctionArgumentsClass();
                // Set the Panchromatic image which has been prepared above
                pansharpFunctionArguements.PanImage = stretchingPanFunctionT;
                // Set the Multispectral image which has been prepared above
                pansharpFunctionArguements.MSImage = stretchingRGBFunctionT;

                // Create a new pansharpen raster function object
                IRasterFunction pansharpenFunction = new PansharpeningFunction();
                // Create a new pansharpen function arguments object
                IPansharpeningFunctionArguments pansharpenFunctionArguements = 
                    new PansharpeningFunctionArgumentsClass();
                // Set the pansharpening type
                pansharpenFunctionArguements.PansharpeningType = 
                    esriPansharpeningType.esriPansharpeningESRI;
                // Create an array of doubles that sets the weights for each band
                IDoubleArray weightsArray = new DoubleArrayClass();
                weightsArray.Add(0.167);
                weightsArray.Add(0.166);
                weightsArray.Add(0.166);
                // and set it on the arguments object
                pansharpenFunctionArguements.Weights = weightsArray;

                // Create a Raster Function Template object for the pansharpen function
                IRasterFunctionTemplate rasterFunction = new RasterFunctionTemplateClass();
                rasterFunction.Function = (IRasterFunction)pansharpenFunction;
                rasterFunction.Arguments = pansharpFunctionArguements;
                ((IRasterFunction)rasterFunction).PixelType = rstPixelType.PT_UCHAR;
                #endregion

                #region Resolve variables
                // Create a PropertySet object to set the values for the 
                // Raster Function Variables created above
                IPropertySet variables = new PropertySet();
                variables.SetProperty("panImage", panDataset);
                variables.SetProperty("rgbImage", rgbDataset);
                #endregion

                #region Create the Function Raster Dataset
                // Create the Function Raster Dataset Object for the Pansharpened Dataset
                IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset();
                // Create a name object for the Function Raster Dataset.
                IFunctionRasterDatasetName functionRasterDatasetName =
                    new FunctionRasterDatasetNameClass();
                // Specify the output filename for the new dataset (including 
                // the .afr extension at the end).
                functionRasterDatasetName.FullName = outputDataset;
                functionRasterDataset.FullName = (IName)functionRasterDatasetName;
                // Initialize the new Function Raster Dataset with the Raster Function 
                // Template and the property set containing the variables and their values.
                functionRasterDataset.Init((IRasterFunction)rasterFunction, variables);

                ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset;
                myTempDset.MakePermanent();
                #endregion

                #region Shutdown
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Shutdown
                Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }        
        }
 public IFunctionRasterDataset calcCensoredRegressFunction(object inRaster, List<float[]> slopes,float lowerLimit=0)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.tobitFunctionDataset();
     FunctionRasters.tobitFunctionArguments args = new FunctionRasters.tobitFunctionArguments(this);
     args.InRasterCoefficients = rRst;
     args.Slopes = slopes;
     args.CensoredValue = lowerLimit;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset calcCombineRasterFunction(IFunctionRasterDataset funcRs)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.combineFunctionDataset();
     FunctionRasters.combineFunctionArguments args = new FunctionRasters.combineFunctionArguments(this);
     args.InRasterDataset = funcRs;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 private IFunctionRasterDataset calcFocalStatisticsRectangle(object iR1, int clm, int rws, focalType statType)
 {
     //Console.WriteLine(statType);
     //Console.WriteLine((esriFocalStatisticType)statType);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new StatisticsFunctionClass();
     //IStatisticsFunctionArguments2 args = new StatisticsFunctionArgumentsClass();
     IStatisticsFunctionArguments args = new StatisticsFunctionArgumentsClass();
     args.Raster = createIdentityRaster(iR1,rstPixelType.PT_FLOAT);
     args.Columns = clm;
     args.Rows = rws;
     args.Type = (esriFocalStatisticType)statType;
     //args.FillNoDataOnly = false;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 //, esriCellsizeType outCellSize = esriCellsizeType.esriCellsizeMinOf, esriExtentType outExtent = esriExtentType.esriExtentIntersectionOf )
 /// <summary>
 /// Will perform an arithmeticOperation on an input raster all bands
 /// </summary>
 /// <param name="inRaster1">either IRaster, IRasterDataset, or a valid path pointing to a raster</param>
 /// <param name="inRaster2">either IRaster, IRasterDataset, a numeric value, or a valid path pointing to a raster</param>
 /// <param name="op">the type of operation</param>
 /// <returns>a IRaster that can be used for further analysis</returns>
 public IFunctionRasterDataset calcArithmaticFunction(object inRaster1, object inRaster2, esriRasterArithmeticOperation op, rstPixelType outRasterType = rstPixelType.PT_FLOAT)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new ArithmeticFunctionClass();
     rsFunc.PixelType = outRasterType;
     //IArithmeticFunctionArguments2 args = new ArithmeticFunctionArgumentsClass();
     IArithmeticFunctionArguments args = new ArithmeticFunctionArgumentsClass();
     if(isNumeric(inRaster1.ToString())&&isNumeric(inRaster2.ToString()))
     {
         Console.WriteLine("Must have at least one raster");
         return null;
     }
     args.Operation = op;
     object iR1, iR2;
     if (isNumeric(inRaster1.ToString())&&!isNumeric(inRaster2.ToString()))
     {
         iR2 = createIdentityRaster(inRaster2,rstPixelType.PT_FLOAT);
         IScalar sc = new ScalarClass();
         int bCnt = ((IRasterBandCollection)iR2).Count;
         float[] d = new float[bCnt];
         for (int i = 0; i < bCnt; i++)
         {
             d[i] = System.Convert.ToSingle(inRaster1);
         }
         sc.Value = d;
         iR1 = sc;
     }
     else if (isNumeric(inRaster2.ToString()) && !isNumeric(inRaster1.ToString()))
     {
         iR1 = createIdentityRaster(inRaster1, rstPixelType.PT_FLOAT);
         IScalar sc = new ScalarClass();
         int bCnt = ((IRasterBandCollection)iR1).Count;
         float[] d = new float[bCnt];
         for (int i = 0; i < bCnt; i++)
         {
             d[i] = System.Convert.ToSingle(inRaster2);
         }
         sc.Value = d;
         iR2 = sc;
     }
     else
     {
         iR1 = createIdentityRaster(inRaster1, rstPixelType.PT_FLOAT);
         iR2 = createIdentityRaster(inRaster2, rstPixelType.PT_FLOAT);
         IRasterBandCollection rsBc1 = (IRasterBandCollection)iR1;
         IRasterBandCollection rsBc2 = (IRasterBandCollection)iR2;
         int bCnt1,bCnt2;
         bCnt1 = rsBc1.Count;
         bCnt2 = rsBc2.Count;
         if (bCnt1 != rsBc2.Count)
         {
             int dif = bCnt1-bCnt2;
             int absDif = Math.Abs(dif);
             if (dif > 0)
             {
                 IRaster rsB = createRaster(getBand(iR2, 0));
                 IRaster[] rsArr = new IRaster[absDif];
                 for (int i = 0; i < absDif; i++)
                 {
                     rsArr[i] = rsB;
                 }
                 iR2 = compositeBandFunction(rsArr);
             }
             else
             {
                 IRaster rsB = createRaster(getBand(iR1, 0));
                 IRaster[] rsArr = new IRaster[absDif];
                 for (int i = 0; i < absDif; i++)
                 {
                     rsArr[i] = rsB;
                 }
                 iR1 = compositeBandFunction(rsArr);
             }
         }
     }
     args.Raster = iR1;
     args.Raster2 = iR2;
     //args.CellsizeType = esriCellsizeType.esriCellsizeMinOf;
     //args.ExtentType = esriExtentType.esriExtentIntersectionOf;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset createMeanShiftFuction(object inRaster, int minCells)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.meanShiftFunctionDataset();
     FunctionRasters.meanShiftFunctionArguments args = new FunctionRasters.meanShiftFunctionArguments(this);
     args.ValueRaster = rRst;
     args.MinCells = minCells;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset setnullToValueFunction(object inRaster, double vl)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.nullToValueFunctionDataset();
     FunctionRasters.nullToValueFunctionArguments args = new FunctionRasters.nullToValueFunctionArguments(this);
     IFunctionRasterDataset IFdset = createIdentityRaster(inRaster);
     args.Raster = IFdset;
     args.Caching = true;
     args.RasterInfo = IFdset.RasterInfo;
     args.NewValue = vl;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset createIdentityRaster(object inRaster,rstPixelType pType)
 {
     if (inRaster == null)
     {
         return null;
     }
     else
     {
         IFunctionRasterDataset trd = createIdentityRaster(inRaster);
         IRasterFunction rsFunc = new IdentityFunctionClass();
         rsFunc.Bind(trd);
         string tempAr = funcDir + "\\" + FuncCnt + ".afr";
         IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
         IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
         frDsetName.FullName = tempAr;
         frDset.FullName = (IName)frDsetName;
         rsFunc.PixelType = pType;
         //rsFunc.Update();
         frDset.Init(rsFunc, trd);
         return frDset;
     }
 }
 public IFunctionRasterDataset createIdentityRaster(object inRaster)
 {
     if (inRaster == null)
     {
         return null;
     }
     else
     {
         if (inRaster is string)
         {
             string oStr;
             inRaster = openRasterDataset(inRaster.ToString(), out oStr);
             if (inRaster == null) return null;
         }
         else if (inRaster is FunctionRasterDataset)
         {
             inRaster = (IRasterDataset)inRaster;
         }
         string tempAr = funcDir + "\\" + FuncCnt + ".afr";
         IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
         IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
         frDsetName.FullName = tempAr;
         frDset.FullName = (IName)frDsetName;
         IRasterFunction rsFunc = (IRasterFunction)new IdentityFunctionClass();
         frDset.Init(rsFunc, inRaster);
         return frDset;
     }
 }
        /// <summary>
        /// performs a convolution analysis for a defined kernel
        /// </summary>
        /// <param name="inRaster"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="kn"></param>
        /// <returns></returns>
        public IFunctionRasterDataset convolutionRasterFunction(object inRaster, int width, int height, double[] kn)
        {
            string tempAr = funcDir + "\\" + FuncCnt + ".afr";
            IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
            IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
            frDsetName.FullName = tempAr;
            frDset.FullName = (IName)frDsetName;
            IRasterFunction rsFunc = new ConvolutionFunctionClass();
            IFunctionRasterDataset rs = createIdentityRaster(inRaster,rstPixelType.PT_FLOAT);
            IConvolutionFunctionArguments args = new ConvolutionFunctionArgumentsClass();
            args.Raster = rs;
            args.Rows = width;
            args.Columns = height;
            IDoubleArray dbArry = new DoubleArrayClass();
            foreach (double d in kn)
            {
                dbArry.Add(d);
            }
            args.Kernel = dbArry;
            args.Type = esriRasterFilterTypeEnum.esriRasterFilterUserDefined;
            frDset.Init(rsFunc, args);
            IFunctionRasterDataset outFrDset = frDset;
            if (width > 3 || height > 3)
            {
                double cSizeX = frDset.RasterInfo.CellSize.X;
                double cSizeY = frDset.RasterInfo.CellSize.Y;
                double addY = 0;
                double addX = 0;
                if (width > 3)
                {
                    addX = (((width + 1) / 2) - 2) * cSizeX;

                }

                if (height > 3)
                {
                    addY = -1 * (((height + 1) / 2) - 2) * cSizeY;

                }
                outFrDset = shiftRasterFunction(frDset, addX, addY);
            }
            return outFrDset;
        }
 public IFunctionRasterDataset constantRasterFunction(IRaster template, IEnvelope NewExtent, double rasterValue, IPnt cellSize)
 {
     IFunctionRasterDataset tDset = createIdentityRaster(template, rstPixelType.PT_FLOAT);
     IConstantFunctionArguments rasterFunctionArguments = (IConstantFunctionArguments)new ConstantFunctionArguments();
     rasterFunctionArguments.Constant = rasterValue;
     IRasterInfo rsInfo = tDset.RasterInfo;
     rsInfo.NativeExtent = NewExtent;
     rsInfo.Extent = NewExtent;
     rsInfo.CellSize = cellSize;
     rasterFunctionArguments.RasterInfo = rsInfo;
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new ConstantFunction();
     frDset.Init(rsFunc, rasterFunctionArguments);
     IRasterInfo2 rsInfo2 = (IRasterInfo2)frDset.RasterInfo;
     IRasterStatistics rsStats = new RasterStatisticsClass();
     rsStats.Mean = rasterValue;
     rsStats.Maximum = rasterValue;
     rsStats.Minimum = rasterValue;
     rsStats.StandardDeviation = rasterValue;
     rsStats.SkipFactorX = 1;
     rsStats.SkipFactorY = 1;
     rsStats.IsValid = true;
     for (int i = 0; i < rsInfo2.BandCount; i++)
     {
         rsInfo2.set_Statistics(i, rsStats);
     }
     return frDset;
 }
 /// <summary>
 /// Used as an if then else statement. The condRaster raster is meant to have values of 1 or 0. If a cell within the input raster has a value 1
 /// then the cell gets the value of inRaster1's corresponding cell. Otherwise that cell gets the value of the inRaster2's corresponding cell.
 /// </summary>
 /// <param name="condRaster">string path, IRaster, IRasterDataset thats cell values are 0 or 1</param>
 /// <param name="inRaster1">string path, IRaster, IRasterDataset, or a numeric value</param>
 /// <param name="inRaster2">string path, IRaster, IRasterDataset, or a numeric value</param>
 /// <returns>IRaster</returns>
 public IFunctionRasterDataset conditionalRasterFunction(object condRaster, object trueRaster, object falseRaster)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     FunctionRasters.conditionalFunctionDataset rsFunc = new FunctionRasters.conditionalFunctionDataset();
     FunctionRasters.conditionalFunctionArguments args = new FunctionRasters.conditionalFunctionArguments(this);
     IFunctionRasterDataset conRs = createIdentityRaster(condRaster);
     if (conRs==null)
     {
         Console.WriteLine("Condition Raster must be a raster");
         return null;
     }
     IFunctionRasterDataset iR1, iR2;
     if (isNumeric(trueRaster.ToString()) && !isNumeric(falseRaster.ToString()))
     {
         iR2 = createIdentityRaster(falseRaster,rstPixelType.PT_FLOAT);
         iR1 = constantRasterFunction(conRs, System.Convert.ToDouble(trueRaster));
     }
     else if (isNumeric(falseRaster.ToString()) && !isNumeric(trueRaster.ToString()))
     {
         iR1 = createIdentityRaster(trueRaster,rstPixelType.PT_FLOAT);
         iR2 = constantRasterFunction(conRs, System.Convert.ToDouble(falseRaster));
     }
     else if (isNumeric(falseRaster.ToString()) && isNumeric(trueRaster.ToString()))
     {
         iR1 = constantRasterFunction(conRs, System.Convert.ToDouble(trueRaster));
         iR2 = constantRasterFunction(conRs, System.Convert.ToDouble(falseRaster));
     }
     else
     {
         iR1 = createIdentityRaster(trueRaster, rstPixelType.PT_FLOAT);
         iR2 = createIdentityRaster(falseRaster,rstPixelType.PT_FLOAT);
     }
     args.ConditionalRaster = conRs;
     args.TrueRaster = iR1;
     args.FalseRaster = iR2;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 /// <summary>
 /// creates a composite band function
 /// </summary>
 /// <param name="rsArray"></param>
 /// <returns></returns>
 public IFunctionRasterDataset compositeBandFunction(IRasterBandCollection rsBandCollection)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new CompositeBandFunctionClass();
     frDset.Init(rsFunc, rsBandCollection);
     return frDset;
 }
 public IFunctionRasterDataset focalBandfunction(object inRaster, localType op, int bandsBefore, int bandsAfter)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     switch (op)
     {
         case localType.MAX:
             break;
         case localType.MIN:
             break;
         case localType.MAXBAND:
             break;
         case localType.MINBAND:
             break;
         case localType.SUM:
             rsFunc = new FunctionRasters.focalBandFunctionDatasetSum();
             break;
         case localType.MULTIPLY:
             break;
         case localType.DIVIDE:
             break;
         case localType.SUBTRACT:
             break;
         case localType.POWER:
             break;
         case localType.MEAN:
             rsFunc = new FunctionRasters.focalBandFunctionDatasetMean();
             break;
         case localType.VARIANCE:
             break;
         case localType.STD:
             rsFunc = new FunctionRasters.focalBandFunctionDatasetStd();
             break;
         case localType.MODE:
             break;
         case localType.MEDIAN:
             break;
         case localType.UNIQUE:
             break;
         case localType.ENTROPY:
             break;
         case localType.ASM:
             break;
         default:
             break;
     }
     FunctionRasters.focalBandFunctionArguments args = new FunctionRasters.focalBandFunctionArguments(this);
     IFunctionRasterDataset inRs = createIdentityRaster(inRaster);
     args.InRaster = inRs;
     args.BandsBefore = bandsBefore;
     args.BandsAfter = bandsAfter;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        public IFunctionRasterDataset reScaleRasterFunction(object inRaster,rstPixelType pType,esriRasterStretchType stretchType)
        {
            IFunctionRasterDataset iR1 = createIdentityRaster(inRaster);
            calcStatsAndHist(iR1);
            string tempAr = funcDir + "\\" + FuncCnt + ".afr";
            IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
            IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
            frDsetName.FullName = tempAr;
            frDset.FullName = (IName)frDsetName;
            IRasterFunction rsFunc = new StretchFunction();
            rsFunc.PixelType = pType;

            //IRasterProps rsProps = (IRasterProps)iR1;
            //rsFunc.RasterInfo.Extent = rsProps.Extent;
            //rsFunc.RasterInfo.CellSize = getCellSize(iR1);
            IStretchFunctionArguments args = new StretchFunctionArgumentsClass();
            args.Raster = iR1;
            args.StretchType = stretchType;
            frDset.Init(rsFunc, args);
            //frDset.Simplify();
            return frDset;
        }
 public IFunctionRasterDataset getBands(object inRaster, ILongArray lArr)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new ExtractBandFunctionClass();
     IExtractBandFunctionArguments args = new ExtractBandFunctionArgumentsClass(); //IExtractBandFunctionArguments2 args = new ExtractBandFunctionArgumentsClass();
     args.Raster = createIdentityRaster(inRaster);
     //args.MissingBandAction = esriMissingBandAction.esriMissingBandActionFindBestMatch;
     args.BandIDs = lArr;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        public IFunctionRasterDataset setValueRangeToNodata(object inRaster,IStringArray sArray)
        {
            string tempAr = funcDir + "\\" + FuncCnt + ".afr";
            IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
            IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
            frDsetName.FullName = tempAr;
            frDset.FullName = (IName)frDsetName;
            IRasterFunction rsFunc = new MaskFunctionClass();
            IMaskFunctionArguments args = new MaskFunctionArgumentsClass(); //IMaskFunctionArguments2 args = new MaskFunctionArgumentsClass();
            args.Raster = returnRaster(inRaster);
            args.NoDataValues = sArray;
            //args.NoDataInterpretation = esriNoDataInterpretation.esriNoDataMatchAll;
            frDset.Init(rsFunc, args);
            return frDset;

            //IRaster rs = returnRaster(inRaster);

            //IRasterProps rsProps = (IRasterProps)rs;
            //IRasterBandCollection rsBc = (IRasterBandCollection)rs;
            //int bCnt = rsBc.Count;
            //System.Array noDataArr = (System.Array)rsProps.NoDataValue;
            //IRasterBandCollection rsBcOut = new RasterClass();
            //for (int i = 0; i < bCnt; i++)
            //{
            //    IRaster brs = getBand(rs, i);
            //    double noData = System.Convert.ToDouble(noDataArr.GetValue(i));
            //    IRemapFilter rFilt = new RemapFilterClass();
            //    foreach (double[] d in minMaxList)
            //    {
            //        rFilt.AddClass(d[0], d[1], noData);
            //    }
            //    rsBcOut.AppendBands((IRasterBandCollection)calcRemapFunction(brs, rFilt));
            //}
            //return (IRaster)rsBcOut;
        }
 public IFunctionRasterDataset localRescalefunction(object inRaster, rasterUtil.localRescaleType op)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     switch (op)
     {
         case localRescaleType.PrcTile:
             rsFunc = new FunctionRasters.localPrctileDataset();
             break;
         default:
             break;
     }
     FunctionRasters.LocalRescaleFunctionArguments args = new FunctionRasters.LocalRescaleFunctionArguments(this);
     IFunctionRasterDataset inRs = createIdentityRaster(inRaster);
     args.InRaster = inRs;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 /// <summary>
 /// performs block summarization
 /// </summary>
 /// <param name="inRaster"></param>
 /// <param name="outWks"></param>
 /// <param name="outRsName"></param>
 /// <param name="numCells"></param>
 /// <returns></returns>
 public IFunctionRasterDataset calcAggregationFunction(object inRaster, int cells, focalType statType)
 {
     IFunctionRasterDataset iR1 = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     switch (statType)
     {
         case focalType.MIN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperMin();
             break;
         case focalType.SUM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperSum();
             break;
         case focalType.MEAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperMean();
             break;
         case focalType.MODE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperMode();
             break;
         case focalType.MEDIAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperMedian();
             break;
         case focalType.VARIANCE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperVar();
             break;
         case focalType.STD:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperStd();
             break;
         case focalType.UNIQUE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperUnique();
             break;
         case focalType.ENTROPY:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperEntropy();
             break;
         case focalType.ASM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperASM();
             break;
         default:
             rsFunc = new FunctionRasters.NeighborhoodHelper.aggregationHelperMax();
             break;
     }
     FunctionRasters.aggregationFunctionArguments args = new FunctionRasters.aggregationFunctionArguments(this);
     args.Cells = cells;
     args.InRaster = iR1;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        /// <summary>
        /// LocalStatistics
        /// </summary>
        /// <param name="inRaster">string, IRasterDataset, or Raster</param>
        /// <returns>IRaster</returns>
        public IFunctionRasterDataset localStatisticsfunction(object inRaster, rasterUtil.localType op)
        {
            string tempAr = funcDir + "\\" + FuncCnt + ".afr";
            IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
            IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
            frDsetName.FullName = tempAr;
            frDset.FullName = (IName)frDsetName;
            IRasterFunction rsFunc = null;
            switch (op)
            {
                case localType.MAX:
                    rsFunc = new FunctionRasters.localMaxFunctionDataset();
                    break;
                case localType.MIN:
                    rsFunc = new FunctionRasters.localMinFunctionDataset();
                    break;
                case localType.SUM:
                    rsFunc = new FunctionRasters.localSumFunctionDataset();
                    break;
                case localType.MULTIPLY:
                    rsFunc = new FunctionRasters.localMultiplyFunctionDataset();
                    break;
                case localType.DIVIDE:
                    rsFunc = new FunctionRasters.localDividFunctionDataset();
                    break;
                case localType.SUBTRACT:
                    rsFunc = new FunctionRasters.localSubtractFunctionDataset();
                    break;
                case localType.POWER:
                    rsFunc = new FunctionRasters.localPowFunctionDataset();
                    break;
                case localType.MEAN:
                    rsFunc = new FunctionRasters.localMeanFunctionDataset();
                    break;
                case localType.VARIANCE:
                    rsFunc = new FunctionRasters.localVarianceFunctionDataset();
                    break;
                case localType.STD:
                    rsFunc = new FunctionRasters.localStandardDeviationFunctionDataset();
                    break;
                case localType.MODE:
                    rsFunc = new FunctionRasters.localModeFunctionDataset();
                    break;
                case localType.MEDIAN:
                    rsFunc = new FunctionRasters.localMedianFunctionDataset();
                    break;
                case localType.UNIQUE:
                    rsFunc = new FunctionRasters.localUniqueValuesFunctionDataset();
                    break;
                case localType.ENTROPY:
                    rsFunc = new FunctionRasters.localEntropyFunctionDataset();
                    break;
                case localType.MAXBAND:
                    rsFunc = new FunctionRasters.localMaxBandFunction();
                    break;
                case localType.MINBAND:
                    rsFunc = new FunctionRasters.localMinBandFunction();
                    break;
                case localType.ASM:
                    rsFunc = new FunctionRasters.localAsmFunctionDataset();
                    break;
                default:
                    break;
            }
            FunctionRasters.LocalFunctionArguments args = new FunctionRasters.LocalFunctionArguments(this);

            IFunctionRasterDataset inRs = createIdentityRaster(inRaster);
            args.InRaster = inRs;
            frDset.Init(rsFunc, args);
            return frDset;
        }
 /// <summary>
 /// calculates an aspect function
 /// </summary>
 /// <param name="inRaster"></param>
 /// <returns></returns>
 public IFunctionRasterDataset calcAspectFunction(IRaster inRaster)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new AspectFunctionClass();
     frDset.Init(rsFunc, inRaster);
     return frDset;
 }
 /// <summary>
 /// creates a mask of valid values (greater than equal to min and less than equal to max)
 /// </summary>
 /// <param name="inRaster"></param>
 /// <param name="BandRanges"></param>
 /// <returns></returns>
 public IFunctionRasterDataset maskDataRange(object inRaster, double[][] BandRanges)
 {
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new MaskFunctionClass();
     IMaskFunctionArguments args = new MaskFunctionArgumentsClass();
     IDoubleArray dbArray = new DoubleArrayClass();
     foreach (double[] d in BandRanges)
     {
         dbArray.Add(d[0]);
         dbArray.Add(d[1]);
     }
     args.Raster = returnRaster(inRaster);
     args.IncludedRanges = dbArray;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset calcClustFunctionKmean(object inRaster, Statistics.dataPrepClusterKmean clus)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.clusterFunctionKmeanDataset();
     FunctionRasters.clusterFunctionArguments args = new FunctionRasters.clusterFunctionArguments(this);
     args.InRasterCoefficients = rRst;
     args.ClusterModel = clus;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        /// <summary>
        /// Opens a raster dataset given a string path
        /// </summary>
        /// <param name="rasterPath">full path to a raster dataset</param>
        /// <returns>IRasterDataset</returns>
        public IRasterDataset openRasterDataset(string rasterPath,out string bnd)
        {
            IRasterDataset rstDset = null;
            bnd = "all";
            try
            {
                IWorkspace wks = null;
                string rstDir = "";
                string extTest = System.IO.Path.GetExtension(rasterPath).ToLower();
                if (extTest == ".nc" || extTest == ".afr")
                {
                    wks = geoUtil.OpenRasterWorkspace(rasterPath);
                    rstDir = System.IO.Path.GetDirectoryName(rasterPath);
                }
                else
                {
                    wks = openRasterDatasetRec(rasterPath);
                    rstDir = wks.PathName;
                }

                string rstName = rasterPath.Replace(rstDir, "").TrimStart(new char[] { '\\' });
                string[] rstNameSplit = rstName.Split(new char[] { '\\' });
                string dataSet = "";
                string rsDset = "";

                switch (rstNameSplit.Length)
                {
                    case 1:
                        rsDset = rstNameSplit[0];
                        break;
                    case 2:
                        rsDset = rstNameSplit[0];
                        bnd = rstNameSplit[1];
                        break;
                    default:
                        dataSet = rstNameSplit[0];
                        rsDset = rstNameSplit[1];
                        bnd = rstNameSplit[2];
                        string[] bndsp = bnd.Split(new char[] { '_' });
                        bnd = bndsp[bndsp.Length - 1];
                        break;
                }
                //Console.WriteLine("Raster Dir = " + rstDir);
                //Console.WriteLine("Raster Name = " + rstName);
                //Console.WriteLine("Raster DataSet = " + dataSet);
                //Console.WriteLine("RsDset = " + rsDset);
                //Console.WriteLine("Bnd = " + bnd);
                if (wks.Type == esriWorkspaceType.esriLocalDatabaseWorkspace || wks.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                {
                    IRasterWorkspaceEx rsWks = (IRasterWorkspaceEx)wks;
                    rstDset = rsWks.OpenRasterDataset(rsDset);
                }
                else
                {
                    //Console.WriteLine(wks.PathName);
                    //Console.WriteLine(wks.WorkspaceFactory.get_WorkspaceDescription(true));
                    //string ext = System.IO.Path.GetExtension(wks.PathName).ToLower();
                    if (extTest == ".nc")
                    {
                        INetCDFWorkspace rsWks = (INetCDFWorkspace)wks;
                        IMDWorkspace mdWks = (IMDWorkspace)wks;
                        NetCDFRasterDatasetName rsDsetName = new NetCDFRasterDatasetNameClass();
                        IMDRasterDatasetView rsDsetV = (IMDRasterDatasetView)rsDsetName;
                        string xDim, yDim, bandDim, vNm;
                        getDeminsions(rsWks, out xDim, out yDim, out bandDim, out vNm);
                        //Console.WriteLine("BandDim = " + bandDim.ToString());
                        //Console.WriteLine("xDim = " + xDim.ToString());
                        //Console.WriteLine("yDim = " + yDim.ToString());
                        rsDsetV.Variable = vNm;
                        rsDsetV.XDimension = xDim;
                        rsDsetV.YDimension = yDim;
                        rsDsetV.BandDimension = bandDim;
                        rstDset = (IRasterDataset)mdWks.CreateView(rsDset, (IMDDatasetView)rsDsetV);
                    }
                    else if (extTest == ".afr")
                    {
                        IFunctionRasterDatasetName fDsName = new FunctionRasterDatasetNameClass();
                        fDsName.FullName = rasterPath;
                        IName name = (IName)fDsName;
                        IFunctionRasterDataset ds = (IFunctionRasterDataset)name.Open();
                        rstDset = (IRasterDataset)ds;
                    }
                    else
                    {
                        IRasterWorkspace rsWks = (IRasterWorkspace)wks;
                        rstDset = rsWks.OpenRasterDataset(rsDset);
                    }
                }
                return rstDset;
            }
            catch
            {
                return null;
            }
        }
 public IFunctionRasterDataset calcFocalSampleFunction(object inRaster, HashSet<string> offset, focalType statType)
 {
     IFunctionRasterDataset iR1 = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     switch (statType)
     {
         case focalType.MIN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperMin();
             break;
         case focalType.SUM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperSum();
             break;
         case focalType.MEAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperMean();
             break;
         case focalType.MODE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperMode();
             break;
         case focalType.MEDIAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperMedian();
             break;
         case focalType.VARIANCE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperVariance();
             break;
         case focalType.STD:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperStd();
             break;
         case focalType.UNIQUE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperUnique();
             break;
         case focalType.ENTROPY:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperEntropy();
             break;
         case focalType.ASM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperASM();
             break;
         default:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalSampleHelperMax();
             break;
     }
     FunctionRasters.focalSampleArguments args = new FunctionRasters.focalSampleArguments(this);
     args.OffSets = offset;
     args.Operation = statType;
     //args.WindowType = windowType.RECTANGLE;
     args.InRaster = iR1;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 public IFunctionRasterDataset PixelBlockToRaster(IPixelBlock ValuePb,IPnt TopLeft,object inRasterObject)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRasterObject);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.PixelBlockToRasterFunctionDataset();
     FunctionRasters.PixelBlockToRasterFunctionArguments args = new FunctionRasters.PixelBlockToRasterFunctionArguments(this);
     args.ValuePixelBlock = ValuePb;
     args.ValueRaster = rRst;
     args.TopLeft = TopLeft;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 /// <summary>
 /// Will perform a focal raster operation on an input raster all bands
 /// </summary>
 /// <param name="inRaster">either IRaster, IRasterDataset, or a valid path pointing to a raster</param>
 /// <param name="radius">number of cells that make up the radius of a circle</param>
 /// <param name="statType">the type of opporation</param>
 /// <returns>a IRaster that can be used for further analysis</returns>
 public IFunctionRasterDataset calcFocalStatisticsFunction(object inRaster, int radius, focalType statType)
 {
     IFunctionRasterDataset iR1 = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = null;
     List<int[]> outLst = new List<int[]>();
     int[,] crl = null;
     double[] cArr = null;
     double sumCircle = 0;
     switch (statType)
     {
         case focalType.MIN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMin();
             break;
         case focalType.SUM:
             crl = createFocalWindowCircle(radius, out outLst);
             cArr = (from int i in crl select System.Convert.ToDouble(i)).ToArray();
             return convolutionRasterFunction(iR1,crl.GetUpperBound(0)+1,crl.GetUpperBound(1)+1,cArr);
         case focalType.MEAN:
             crl = createFocalWindowCircle(radius, out outLst);
             sumCircle = (from int i in crl select System.Convert.ToDouble(i)).Sum();
             cArr = (from int i in crl select System.Convert.ToDouble(i)).ToArray();
             IFunctionRasterDataset conRsMean = convolutionRasterFunction(iR1, crl.GetUpperBound(0) + 1, crl.GetUpperBound(1) + 1, cArr);
             return calcArithmaticFunction(conRsMean, sumCircle, esriRasterArithmeticOperation.esriRasterDivide);
         case focalType.MODE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMode();
             break;
         case focalType.MEDIAN:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMedian();
             break;
         case focalType.VARIANCE:
             crl = createFocalWindowCircle(radius, out outLst);
             cArr = (from int i in crl select System.Convert.ToDouble(i)).ToArray();
             double sumCr = cArr.Sum();
             IFunctionRasterDataset rs2 = calcMathRasterFunction(iR1, transType.SQUARED);
             IFunctionRasterDataset sumRs2 = convolutionRasterFunction(rs2, crl.GetUpperBound(0) + 1, crl.GetUpperBound(1) + 1, cArr);
             IFunctionRasterDataset sumRs2M = calcArithmaticFunction(sumRs2, sumCr, esriRasterArithmeticOperation.esriRasterDivide);
             IFunctionRasterDataset sumRs = convolutionRasterFunction(iR1, crl.GetUpperBound(0) + 1, crl.GetUpperBound(1) + 1, cArr);
             IFunctionRasterDataset sumRsSquared = calcMathRasterFunction(sumRs, transType.SQUARED);
             IFunctionRasterDataset difRs = calcArithmaticFunction(sumRsSquared, sumRs2, esriRasterArithmeticOperation.esriRasterMinus);
             return calcArithmaticFunction(difRs, sumCr, esriRasterArithmeticOperation.esriRasterDivide);
         case focalType.STD:
             IRaster var = createRaster(calcFocalStatisticsFunction(iR1, radius, focalType.VARIANCE));
             return calcMathRasterFunction(var, transType.SQRT);
         case focalType.UNIQUE:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperUnique();
             break;
         case focalType.ENTROPY:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperEntropy();
             break;
         case focalType.ASM:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperProbability();
             break;
         default:
             rsFunc = new FunctionRasters.NeighborhoodHelper.focalHelperMax();
             break;
     }
     FunctionRasters.FocalFunctionArguments args = new FunctionRasters.FocalFunctionArguments(this);
     args.Radius = radius;
     args.InRaster = iR1;
     args.Operation = statType;
     frDset.Init(rsFunc, args);
     return frDset;
 }
 /// <summary>
 /// defines unique regions using a 4 neighbor window
 /// </summary>
 /// <param name="inRaster"></param>
 /// <param name="wks"></param>
 /// <param name="outName"></param>
 /// <returns></returns>
 public IFunctionRasterDataset regionGroup(object inRaster)
 {
     IFunctionRasterDataset iR1 = createIdentityRaster(inRaster);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new FunctionRasters.regionGroupFunctionDataset();
     FunctionRasters.regionGroupFunctionArguments args = new FunctionRasters.regionGroupFunctionArguments(this);
     args.InRaster = iR1;
     frDset.Init(rsFunc, args);
     return frDset;
 }
        static void Main(string[] args)
        {
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit;

            #region Initialize License
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
                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
            {
                #region Specify input directory and dataset name
                // The directory which contains the Panchromatic Image.
                string panDir = @"C:\Data\QB\Pan";
                // The directory which contains the Multispectral Image.
                string rgbDir = @"C:\Data\QB\MS";

                string panImageName = "05JAN27104436-P1BS-005533787010_01_P002.TIF";
                string rgbImageName = "05JAN27104436-M1BS-005533787010_01_P002.TIF";

                // Output filename.
                string outputDataset = @"c:\Temp\QBTemplateCS.afr";
                #endregion

                #region Initialize
                // Setup Workspaces.
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory");
                IWorkspaceFactory workspaceFactory   = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IRasterWorkspace  panRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(panDir, 0);
                IRasterWorkspace  rgbRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(rgbDir, 0);

                // Open Datasets
                IRasterDataset panDataset = panRasterWorkspace.OpenRasterDataset(panImageName);
                IRasterDataset rgbDataset = rgbRasterWorkspace.OpenRasterDataset(rgbImageName);
                #endregion

                #region Create Variables
                // Create one variable of type IRasterFunctionVariable for each
                // Raster Dataset opened above

                // Create a new Raster Function Variable
                IRasterFunctionVariable panVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                panVar.Name = "panImage";
                // Describe the variable
                panVar.Description = "Panchromatic Image to be used for pansharpening";
                // Specify whether it represents a dataset
                panVar.IsDataset = true;

                // Create a new Raster Function Variable
                IRasterFunctionVariable rgbVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                rgbVar.Name = "rgbImage";
                // Describe the variable
                rgbVar.Description = "Multispectral Image to be used for pansharpening";
                // Specify whether it represents a dataset
                rgbVar.IsDataset = true;
                #endregion

                #region Prepare the Pan Image
                // Setup statistics for each band
                IArray            statsArrayPan = new ArrayClass();
                IRasterStatistics statsPanBand  = new RasterStatisticsClass();
                statsPanBand.Minimum = 1;
                statsPanBand.Maximum = 2047;
                statsArrayPan.Add(statsPanBand);
                // Create the arguments object for the stretching function
                IStretchFunctionArguments stretchingPanFunctionArguements = new StretchFunctionArgumentsClass();
                // Set the stretching type
                stretchingPanFunctionArguements.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingPanFunctionArguements.Statistics = statsArrayPan;
                // Set the input raster, in this case, the variable for the Pan Image
                stretchingPanFunctionArguements.Raster = panVar;

                // Create the function object to stretch the Pan Image.
                IRasterFunction stretchingPanFunction = new StretchFunction();

                // Create a Raster Function Template object for the stretch function
                IRasterFunctionTemplate stretchingPanFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingPanFunctionT.Function = (IRasterFunction)stretchingPanFunction;
                // Set the arguments for the function
                stretchingPanFunctionT.Arguments = stretchingPanFunctionArguements;
                #endregion

                #region Prepare the Multispectral (RGB) Image
                // Create an array which defines the order of bands
                ILongArray bandIDs = new LongArrayClass();
                bandIDs.Add(2);
                bandIDs.Add(1);
                bandIDs.Add(0);
                // Create an Extract Band Function Arguments object
                IExtractBandFunctionArguments extractRgbBandFunctionArgs = (IExtractBandFunctionArguments)
                                                                           new ExtractBandFunctionArguments();
                // Set the order of bands of the output
                extractRgbBandFunctionArgs.BandIDs = bandIDs;
                // Set the input raster, in this case the variable for the Multispectral Image
                extractRgbBandFunctionArgs.Raster = rgbVar;

                // Create the Extract Band Function object
                IRasterFunction extractRgbBandFunction = new ExtractBandFunction();

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate extractRgbBandFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                extractRgbBandFunctionT.Function = (IRasterFunction)extractRgbBandFunction;
                // Set the arguments for the function
                extractRgbBandFunctionT.Arguments = extractRgbBandFunctionArgs;

                // Setup statistics for each band
                IArray            statsArray    = new ArrayClass();
                IRasterStatistics statsMulBand1 = new RasterStatisticsClass();
                statsMulBand1.Minimum = 100;
                statsMulBand1.Maximum = 1721;
                statsArray.Add(statsMulBand1);
                IRasterStatistics statsMulBand2 = new RasterStatisticsClass();
                statsMulBand2.Minimum = 95;
                statsMulBand2.Maximum = 2047;
                statsArray.Add(statsMulBand2);
                IRasterStatistics statsMulBand3 = new RasterStatisticsClass();
                statsMulBand3.Minimum = 34;
                statsMulBand3.Maximum = 2006;
                statsArray.Add(statsMulBand3);

                // Create a stretching function for the multispectral image
                IRasterFunction stretchingRGBFunction = new StretchFunction();
                // Create an arguments object for the stretch function
                IStretchFunctionArguments stretchingRGBFunctionArguments =
                    new StretchFunctionArgumentsClass();
                // Set the type of stretchings to perform
                stretchingRGBFunctionArguments.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingRGBFunctionArguments.Statistics = statsArray;
                // Set the extract band function template created above as the input
                stretchingRGBFunctionArguments.Raster = extractRgbBandFunctionT;

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate stretchingRGBFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingRGBFunctionT.Function = (IRasterFunction)stretchingRGBFunction;
                // Set the arguments for the function
                stretchingRGBFunctionT.Arguments = stretchingRGBFunctionArguments;
                #endregion

                #region Pansharpen the Pan Image with the Multispectral
                // Create a Raster Function Arguments object for the pansharpen function
                IPansharpeningFunctionArguments pansharpFunctionArguements =
                    new PansharpeningFunctionArgumentsClass();
                // Set the Panchromatic image which has been prepared above
                pansharpFunctionArguements.PanImage = stretchingPanFunctionT;
                // Set the Multispectral image which has been prepared above
                pansharpFunctionArguements.MSImage = stretchingRGBFunctionT;

                // Create a new pansharpen raster function object
                IRasterFunction pansharpenFunction = new PansharpeningFunction();
                // Create a new pansharpen function arguments object
                IPansharpeningFunctionArguments pansharpenFunctionArguements =
                    new PansharpeningFunctionArgumentsClass();
                // Set the pansharpening type
                pansharpenFunctionArguements.PansharpeningType =
                    esriPansharpeningType.esriPansharpeningESRI;
                // Create an array of doubles that sets the weights for each band
                IDoubleArray weightsArray = new DoubleArrayClass();
                weightsArray.Add(0.167);
                weightsArray.Add(0.166);
                weightsArray.Add(0.166);
                // and set it on the arguments object
                pansharpenFunctionArguements.Weights = weightsArray;

                // Create a Raster Function Template object for the pansharpen function
                IRasterFunctionTemplate rasterFunction = new RasterFunctionTemplateClass();
                rasterFunction.Function  = (IRasterFunction)pansharpenFunction;
                rasterFunction.Arguments = pansharpFunctionArguements;
                ((IRasterFunction)rasterFunction).PixelType = rstPixelType.PT_UCHAR;
                #endregion

                #region Resolve variables
                // Create a PropertySet object to set the values for the
                // Raster Function Variables created above
                IPropertySet variables = new PropertySet();
                variables.SetProperty("panImage", panDataset);
                variables.SetProperty("rgbImage", rgbDataset);
                #endregion

                #region Create the Function Raster Dataset
                // Create the Function Raster Dataset Object for the Pansharpened Dataset
                IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset();
                // Create a name object for the Function Raster Dataset.
                IFunctionRasterDatasetName functionRasterDatasetName =
                    new FunctionRasterDatasetNameClass();
                // Specify the output filename for the new dataset (including
                // the .afr extension at the end).
                functionRasterDatasetName.FullName = outputDataset;
                functionRasterDataset.FullName     = (IName)functionRasterDatasetName;
                // Initialize the new Function Raster Dataset with the Raster Function
                // Template and the property set containing the variables and their values.
                functionRasterDataset.Init((IRasterFunction)rasterFunction, variables);

                ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset;
                myTempDset.MakePermanent();
                #endregion

                #region Shutdown
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Shutdown
                Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }
 /// <summary>
 /// Clips a raster to the boundary of a polygon
 /// </summary>
 /// <param name="inRaster">IRaster, IRasterDataset, or string</param>
 /// <param name="geo">Polygon Geometry</param>
 /// <param name="clipType">the type of clip either inside or outside</param>
 /// <returns></returns>
 public IFunctionRasterDataset clipRasterFunction(object inRaster, IGeometry geo, esriRasterClippingType clipType)
 {
     IFunctionRasterDataset rRst = createIdentityRaster(inRaster);
     IRaster2 rRst2 = (IRaster2)createRaster(rRst);
     string tempAr = funcDir + "\\" + FuncCnt + ".afr";
     IFunctionRasterDataset frDset = new FunctionRasterDatasetClass();
     IFunctionRasterDatasetName frDsetName = new FunctionRasterDatasetNameClass();
     frDsetName.FullName = tempAr;
     frDset.FullName = (IName)frDsetName;
     IRasterFunction rsFunc = new ClipFunctionClass();
     IEnvelope env = geo.Envelope;
     double hX = rRst.RasterInfo.CellSize.X / 2;
     double hY = rRst.RasterInfo.CellSize.Y / 2;
     double xMin = env.XMin;
     double xMax = env.XMax;
     double yMin = env.YMin;
     double yMax = env.YMax;
     int clm, rw;
     rRst2.MapToPixel(xMin, yMin,out clm,out rw);
     rRst2.PixelToMap(clm, rw, out xMin, out yMin);
     xMin = xMin - hX;
     yMin = yMin - hY;
     rRst2.MapToPixel(xMax, yMax, out clm, out rw);
     rRst2.PixelToMap(clm, rw, out xMax, out yMax);
     xMax = xMax + hX;
     yMax = yMax + hY;
     env.PutCoords(xMin, yMin, xMax, yMax);
     IClipFunctionArguments args = new ClipFunctionArgumentsClass();
     args.Extent = env;
     args.ClippingGeometry = geo;
     args.ClippingType = clipType;
     args.Raster = rRst;
     frDset.Init(rsFunc, args);
     return frDset;
 }