double bilinear_height(DataAccessor pSrcAcc, double I, double J)
   {

	   double z1=0,z2=0,z3=0,z4=0;
       pSrcAcc->toPixel(int(J),int(I));
	   VERIFY(pSrcAcc.isValid());
	   z1 = pSrcAcc->getColumnAsDouble();

       pSrcAcc->toPixel(int(J)+1,int(I));
	   VERIFY(pSrcAcc.isValid());
	   z2 = pSrcAcc->getColumnAsDouble();

       pSrcAcc->toPixel(int(J),int(I)+1);
	   VERIFY(pSrcAcc.isValid());
	   z3 = pSrcAcc->getColumnAsDouble();

       pSrcAcc->toPixel(int(J)+1,int(I)+1);
	   VERIFY(pSrcAcc.isValid());
	   z4 = pSrcAcc->getColumnAsDouble();

       double a=0,b=0,c=0,d=0;    

	   d = z1;
	   a = (z2-z1);
	   b = (z3-z1);
	   c = (z4+z1-z2-z3);
	   
	   double H = a*(J-int(J))+b*(I-int(I))+c*(I-int(I))*(J-int(J))+d; 

	   return H;
   }
bool Deconvolution::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Deconvolution Sharpening", "app", "619F3C8A-FB70-44E0-B211-B116E604EDDA");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Deconvolution_Sharpening_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   Service<DesktopServices> pDesktop;
   DeconvolutionDlg dlg(pDesktop->getMainWidget());
   int stat = dlg.exec();
   if (stat != QDialog::Accepted)
   {
	   return true;
   }

   double minGrayValue;
   double maxGrayValue;
   double deltaValue = 0.0;

   int nFilterType = dlg.getCurrentFilterType();
   int windowSize = dlg.getCurrentWindowSize();
   double sigmaVal = dlg.getSigmaValue();
   double gamaVal = dlg.getGamaValue();
   windowSize = (windowSize-1)/2;
   
   if (NULL != pOriginalImage)
   {
	   free(pOriginalImage);
   }
   pOriginalImage = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   
   double *OrigData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *NewData  = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *ConvoData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount());
   double *pTempData;

   InitializeData(pSrcAcc, pOriginalImage, OrigData, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType());
   GetGrayScale(&minGrayValue, &maxGrayValue, pDesc->getDataType());
   
   //Perform deconvolution iteratively
   for (int num = 0; num < MAX_ITERATION_NUMBER; num++)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Deconvolution process", num*100/MAX_ITERATION_NUMBER, NORMAL);
      }
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }
         
         free(OrigData);
         free(NewData);
         free(ConvoData);
         
         return false;
      }
      
      deltaValue = DeconvolutionFunc(OrigData, pOriginalImage, NewData, ConvoData, sigmaVal, gamaVal, 
                                     windowSize, pDesc->getRowCount(), pDesc->getColumnCount(), nFilterType, maxGrayValue, minGrayValue);


      pTempData = OrigData;
      OrigData = NewData;
      NewData = pTempData;

	  double errorRate = deltaValue/(maxGrayValue-minGrayValue);
	  if (errorRate < CONVERGENCE_THRESHOLD)
	  {
		  break;
	  }
   }
   
   free(NewData);
   free(ConvoData);


   //Output result
   unsigned int nCount = 0;
   for (int i = 0; i < pDesc->getRowCount(); i++)
   {
       for (int j = 0; j < pDesc->getColumnCount(); j++)		   
	   {		   
		   if (!pDestAcc.isValid())
           {       
		       std::string msg = "Unable to access the cube data.";        
			   pStep->finalize(Message::Failure, msg);
                       
			   if (pProgress != NULL)                      
			   {         
			       pProgress->updateProgress(msg, 0, ERRORS);       
			   }   
			   free(OrigData);                  
			   return false;              
		   }
			   
		   pDestAcc->toPixel(i, j);	
		   switchOnEncoding(ResultType, restoreImageValue, pDestAcc->getColumn(), (OrigData+nCount));
		   nCount++;

	   }
   }
   
   free(OrigData);  


   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Deconvolution enhancement is complete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Deconvolution enhancement Result", pResultCube.release());

   pStep->finalize();


   return true;
}
Esempio n. 3
0
void ConvolutionFilterShell::ConvolutionFilterThread::convolve(const T*)
{
   int numResultsCols = mInput.mpIterCheck->getNumSelectedColumns();
   if (mInput.mpResult == NULL)
   {
      return;
   }

   const RasterDataDescriptor* pResultDescriptor = static_cast<const RasterDataDescriptor*>(
      mInput.mpResult->getDataDescriptor());

   // account for AOIs which extend outside the dataset
   int maxRowNum = static_cast<int>(mInput.mpDescriptor->getRowCount()) - 1;
   mRowRange.mFirst = std::max(0, mRowRange.mFirst);
   mRowRange.mLast = std::min(mRowRange.mLast, maxRowNum);

   unsigned int bandCount = mInput.mBands.size();
   for (unsigned int bandNum = 0; bandNum < bandCount; ++bandNum)
   {
      FactoryResource<DataRequest> pResultRequest;
      pResultRequest->setRows(pResultDescriptor->getActiveRow(mRowRange.mFirst),
         pResultDescriptor->getActiveRow(mRowRange.mLast));
      pResultRequest->setColumns(pResultDescriptor->getActiveColumn(0),
         pResultDescriptor->getActiveColumn(numResultsCols - 1));
      pResultRequest->setBands(pResultDescriptor->getActiveBand(bandNum),
         pResultDescriptor->getActiveBand(bandNum));
      pResultRequest->setWritable(true);
      DataAccessor resultAccessor = mInput.mpResult->getDataAccessor(pResultRequest.release());
      if (!resultAccessor.isValid())
      {
         return;
      }

      int oldPercentDone = -1;
      int rowOffset = static_cast<int>(mInput.mpIterCheck->getOffset().mY);
      int startRow = mRowRange.mFirst + rowOffset;
      int stopRow = mRowRange.mLast + rowOffset;

      int columnOffset = static_cast<int>(mInput.mpIterCheck->getOffset().mX);
      int startColumn = columnOffset;
      int stopColumn = numResultsCols + columnOffset - 1;

      int yshift = (mInput.mKernel.Nrows() - 1) / 2;
      int xshift = (mInput.mKernel.Ncols() - 1) / 2;

      FactoryResource<DataRequest> pRequest;
      pRequest->setRows(mInput.mpDescriptor->getActiveRow(std::max(0, startRow - yshift)),
         mInput.mpDescriptor->getActiveRow(std::min(maxRowNum, stopRow + mInput.mKernel.Nrows() - yshift)));
      pRequest->setColumns(mInput.mpDescriptor->getActiveColumn(startColumn),
         mInput.mpDescriptor->getActiveColumn(stopColumn));
      pRequest->setBands(mInput.mpDescriptor->getActiveBand(mInput.mBands[bandNum]),
         mInput.mpDescriptor->getActiveBand(mInput.mBands[bandNum]));
      DataAccessor accessor = mInput.mpRaster->getDataAccessor(pRequest.release());
      if (!accessor.isValid())
      {
         return;
      }

      Service<ModelServices> model;
      ModelServices* pModel = model.get();
      int numRows = stopRow - startRow + 1;
      for (int row_index = startRow; row_index <= stopRow; ++row_index)
      {
         int percentDone = 100 * ((bandNum * numRows) + (row_index - startRow)) / (numRows * bandCount); 
         if (percentDone > oldPercentDone)
         {
            oldPercentDone = percentDone;
            getReporter().reportProgress(getThreadIndex(), percentDone);
         }
         if (mInput.mpAbortFlag != NULL && *mInput.mpAbortFlag)
         {
            break;
         }

         for (int col_index = startColumn; col_index <= stopColumn; ++col_index)
         {
            double accum = 0.0;
            if (mInput.mpIterCheck->getPixel(col_index, row_index))
            {
               for (int kernelrow = 0; kernelrow < mInput.mKernel.Nrows(); kernelrow++)
               {
                  int neighbor_row = row_index - yshift + kernelrow;
                  int real_row = std::min(std::max(0, neighbor_row),
                     static_cast<int>(mInput.mpDescriptor->getRowCount()) - 1);
                  for (int kernelcol = 0; kernelcol < mInput.mKernel.Ncols(); kernelcol++)
                  {
                     int neighbor_col = col_index - xshift + kernelcol;
                     int real_col = std::min(std::max(0, neighbor_col),
                        static_cast<int>(mInput.mpDescriptor->getColumnCount()) - 1);
                     accessor->toPixel(real_row, real_col);
                     if (accessor.isValid() == false)
                     {
                        return;
                     }

                     double val = 0.0;
                     pModel->getDataValue<T>(reinterpret_cast<T*>(accessor->getColumn()), COMPLEX_MAGNITUDE, 0, val);
                     accum += mInput.mKernel(kernelrow+1, kernelcol+1) * val / mInput.mKernel.Storage();
                  }
               }
            }
            if (resultAccessor.isValid() == false)
            {
               return;
            }

            switchOnEncoding(pResultDescriptor->getDataType(), assignResult,
                             resultAccessor->getColumn(), accum + mInput.mOffset);
            resultAccessor->nextColumn();
         }
         resultAccessor->nextRow();
      }
   }
}
   double edgeDetection7(DataAccessor pSrcAcc, int row, int col, int rowSize, int colSize)
   {
      int prevCol = std::max(col - 1, 0);
      int prevRow = std::max(row - 1, 0);
      int nextCol = std::min(col + 1, colSize - 1);
      int nextRow = std::min(row + 1, rowSize - 1);

	  int prevCol1 = std::max(col-2,0);
	  int prevRow1= std::max(row-2,0);
	  int nextCol1= std::min(col+2,colSize-1);
	  int nextRow1= std::min(row+2,rowSize-1);

	  pSrcAcc->toPixel(prevRow1, prevCol1);
      int row1col1 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow1, prevCol);
      int row1col2 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow1, col);
      int row1col3 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow1, nextCol);
      int row1col4 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow1, nextCol1);
      int row1col5 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow, prevCol1);
      int row2col1 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow, prevCol);
      int row2col2 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow, col);
      int row2col3 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow, nextCol);
      int row2col4 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(prevRow, nextCol1);
      int row2col5 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(row, prevCol1);
      int row3col1 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(row, prevCol);
      int row3col2 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(row, col);
      int row3col3 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(row, nextCol);
      int row3col4 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(row, nextCol1);
      int row3col5 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(nextRow, prevCol1);
      int row4col1 = pSrcAcc->getColumnAsInteger();

	  pSrcAcc->toPixel(nextRow, prevCol);
      int row4col2 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow, col);
      int row4col3 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow, nextCol);
      int row4col4 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow, nextCol1);
      int row4col5 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow1, prevCol1);
      int row5col1 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow1, prevCol);
      int row5col2 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow1, col);
      int row5col3 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow1, nextCol);
      int row5col4 = pSrcAcc->getColumnAsInteger();

      pSrcAcc->toPixel(nextRow1, nextCol1);
      int row5col5 = pSrcAcc->getColumnAsInteger();

	   int g = row1col1 + row1col2 + row1col3 + row1col4 + row1col5 + row2col1 + row2col2 + row2col3 + row2col4
		         + row2col5 + row3col1 + row3col2 + 24*row3col3 + row3col4 + row3col5 + row4col1 + row4col2 + row4col3
				 + row4col4 + row4col5 + row5col1 + row5col2 + row5col3 + row5col4 + row5col5;


	    double value = g/159.0;

		return value;

      
   };
bool Orthorectification::process(int type, RasterElement *pDSM, GRID DSMGrid, double Geoid_Offset, int DSM_resampling)
{
	StepResource pStep("Orthorectification Process", "app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	pStep->addStep("Start","app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	boxsize=0;

	res_type = type;

	if (res_type == 0) 
	{
		boxsize=0;	
	}
	else if (res_type == 1)
	{
		boxsize=1;		
	}
	else if (res_type == 2)
	{
		boxsize=2;		
	}
	else if (res_type == 3)
	{
		boxsize=3;	
	}

    ProgressResource pResource("ProgressBar");

	Progress *pProgress=pResource.get(); 

	pProgress->setSettingAutoClose(false);

	RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(Image->getDataDescriptor());
    
    FactoryResource<DataRequest> pRequest;
    DataAccessor pSrcAcc = Image->getDataAccessor(pRequest.release());

    RasterDataDescriptor* pDescDSM = static_cast<RasterDataDescriptor*>(pDSM->getDataDescriptor());

	FactoryResource<DataRequest> pRequestDSM;
    DataAccessor pDSMAcc = pDSM->getDataAccessor(pRequestDSM.release());

 
	unsigned int N_Row = int(OrthoGrid.Y_Dim)+1;
	unsigned int N_Col = int(OrthoGrid.X_Dim)+1;

	// Check name of raster element //
	Service<ModelServices> pModel;
    vector<string> mCubeNames = pModel->getElementNames("RasterElement");

	int NameIndex = 0, control=0;
	stringstream out;
	string OutputName=Image->getName();
	string OutputName1 = OutputName.substr(0,OutputName.find_last_of("."));

	while (control == 0)
	{
		control = 1;
		OutputName = OutputName1+"_ortho_";

		out << NameIndex;
		OutputName.append(out.str()+".tiff");		
		
		for (unsigned int k=0; k<mCubeNames.size(); k++)
		{
		if (OutputName.compare(mCubeNames[k]) == 0) control = 0;
		}

		NameIndex++;
		out.str("");
		out.clear();

	}

	// Create output raster element and assoiciated descriptor and accessor //
	
	ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(OutputName,N_Row ,N_Col, FLT4BYTES));

	RasterDataDescriptor* pResultDesc = static_cast<RasterDataDescriptor*> (pResultCube->getDataDescriptor());

    FactoryResource<DataRequest> pResultRequest;
    pResultRequest->setWritable(true);
    DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

    double NodeLat, NodeLon, H_IJ=0;
	//int DSM_I, DSM_J;

    for (unsigned int row = 0; row < N_Row; ++row)
    {
	  if (pProgress != NULL)
	  {
      pProgress->updateProgress("Calculating result", row * 100 / N_Row, NORMAL);
	  }

      if (!pDestAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pProgress->updateProgress(msg, 0, ERRORS);
		 pStep->finalize(Message::Failure, msg);
         return false;
      }

      for (unsigned int col = 0; col < N_Col; ++col)
      {

		  NodeLat = OrthoGrid.Lat_Min+row*OrthoGrid.Lat_Step;
		  NodeLon = OrthoGrid.Lon_Min+col*OrthoGrid.Lon_Step;

		  // RETRIEVE HEIGHT VALUE FROM DSM 

		  if (DSM_resampling == 0) 
		  {
		  int DSM_I = int((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step);
		  int DSM_J = pDescDSM->getRowCount() - int((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step);		  
          pDSMAcc->toPixel(DSM_J,DSM_I);
	      VERIFY(pDSMAcc.isValid());
          H_IJ = (pDSMAcc->getColumnAsDouble());
		  }
		  else
		  {
		  double DSM_I = ((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step);
		  double DSM_J = pDescDSM->getRowCount() - ((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step);
		  H_IJ = bilinear_height(pDSMAcc,DSM_I,DSM_J);
		  }

		  P_COORD NodeImage = Model->SAR_GroundToImage(NodeLon,NodeLat,H_IJ+Geoid_Offset);

		  if ((NodeImage.I>1 && NodeImage.I< Model->Metadata.Width-1) && (NodeImage.J>1 && NodeImage.J< Model->Metadata.Height-1))
		  {
			switchOnEncoding(pResultDesc->getDataType(), copypixel3, pDestAcc->getColumn(), pSrcAcc, int(NodeImage.I), int(NodeImage.J),boxsize, H_IJ);		
		  }		  
		  pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
    }

   Service<DesktopServices> pDesktop;

   Service<ModelServices> pMod;

   GcpList* GcpL = static_cast<GcpList*>(pMod->createElement("corner coordinate","GcpList",pResultCube.get()));
   
   // Update GCPs Information: to account for Opticks reading gcp lat&lon values the opposite way around, 
   // here it is necessary to switch the value to assign lat to gcp.mCoordinate.mX  and lon to gcp.mCoordinate.mY 

   GcpPoint Punto;

   Punto.mCoordinate.mX = OrthoGrid.Lat_Min;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Min;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = 0.0;
   Punto.mPixel.mY = 0.0;

   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Max;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Min;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = 0.0;
   Punto.mPixel.mY = OrthoGrid.Y_Dim;
   
   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Min;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Max;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = OrthoGrid.X_Dim;
   Punto.mPixel.mY = 0.0;
   
   GcpL->addPoint(Punto);

   Punto.mCoordinate.mX = OrthoGrid.Lat_Max;
   Punto.mCoordinate.mY = OrthoGrid.Lon_Max;
   Punto.mCoordinate.mZ = 0.0;
   Punto.mPixel.mX = OrthoGrid.X_Dim;
   Punto.mPixel.mY = OrthoGrid.Y_Dim;
   
   GcpL->addPoint(Punto); 

   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));
 
   SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();  

   pView->setPrimaryRasterElement(pResultCube.get());

   pView->createLayer(RASTER, pResultCube.get());
   
   pView->createLayer(GCP_LAYER,GcpL,"GCP");

   pView->setDataOrigin(LOWER_LEFT);

   pResultCube.release();

   pProgress->updateProgress("Orthorectification is complete.", 100, NORMAL);
   pStep->addStep("End","app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
   pStep->finalize();

   return true;
   
}
bool TextureSegmentation::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("SAR image segmentation", "app", "CC430C1A-9D8C-4bb5-9254-FCF7EECAFA3C");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   EncodingType ResultType = INT1UBYTE;


   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Segmentation_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   if (isAborted())
   {
       std::string msg = getName() + " has been aborted.";
       pStep->finalize(Message::Abort, msg);
       if (pProgress != NULL)
       {
           pProgress->updateProgress(msg, 0, ABORT);
       }
               
	   return false;        
   }

   if (NULL != pBuffer)
   {
	   free(pBuffer);
   }
   pBuffer = (float *)malloc(sizeof(float)*pDesc->getRowCount()*pDesc->getColumnCount());
  
   MakeSegmentation(pSrcAcc, pBuffer, pBuffer, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType());

   //Output the value 
   unsigned int nCount = 0;
   for (unsigned int j = 0; j < pDesc->getColumnCount(); j++)
   {
       for (unsigned int i = 0; i < pDesc->getRowCount(); i++)		   
	   {		   
		   if (!pDestAcc.isValid())
           {       
			   std::string msg = "Unable to access the cube data.";        
			   pStep->finalize(Message::Failure, msg);
                       
			   if (pProgress != NULL)                      
			   {         
				   pProgress->updateProgress(msg, 0, ERRORS);       
			   }                     
			   return false;              
		   }
			   
		   pDestAcc->toPixel(i, j);		   
		   switchOnEncoding(ResultType, restoreSegmentationValue, pDestAcc->getColumn(), (pBuffer+nCount));
		   nCount++;
	   }
   }

   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Image segmentation is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Image segmentation result", pResultCube.release());

   pStep->finalize();
   return true;
}
bool WaveletKSigmaFilter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Wavelet K-Sigma Filter", "app", "1A4BDC34-5A95-419B-8E53-C92333AFFC3E");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Noise_Removal_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType));
   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());

   Service<DesktopServices> pDesktop;
   WaveletKSigmaDlg dlg(pDesktop->getMainWidget());
   int stat = dlg.exec();
   if (stat != QDialog::Accepted)
   {
	  // pProgress->updateProgress("Level 4 " + StringUtilities::toDisplayString(dlg.getLevelThreshold(3))
       //  + " Level5 " + StringUtilities::toDisplayString(dlg.getLevelThreshold(4)), dlg.getLevelThreshold(0), NORMAL);

	   return true;
   }

   unsigned int rowLoops;
   unsigned int colLoops;
   unsigned int rowIndex = 0;
   unsigned int colIndex = 0;
   double ScaleKValue[MAX_WAVELET_LEVELS] = {0.0};
   for (int k=0; k<MAX_WAVELET_LEVELS;k++)
   {
	   ScaleKValue[k] = dlg.getLevelThreshold(k);
   }
   
   if (0 == pDesc->getRowCount()%rowBlocks)
   {
	   rowLoops = pDesc->getRowCount()/rowBlocks;
   }
   else
   {
	   rowLoops = pDesc->getRowCount()/rowBlocks + 1;
   }

   if (0 == pDesc->getColumnCount()%colBlocks)
   {
	   colLoops = pDesc->getColumnCount()/colBlocks;
   }
   else
   {
	   colLoops = pDesc->getColumnCount()/colBlocks + 1;
   }

   for (unsigned int i = 0; i < rowLoops; i++)
   {
	   if ( rowIndex + rowBlocks > pDesc->getRowCount())
	   {
		   rowIndex = pDesc->getRowCount() - rowBlocks;
	   }

	   colIndex = 0;

	   for (unsigned int j = 0; j < colLoops; j++)
	   {
		   if ( colIndex + colBlocks > pDesc->getColumnCount())
	       {
		       colIndex = pDesc->getColumnCount() - colBlocks;
	       }

		   if (pProgress != NULL)
           {
               pProgress->updateProgress("Remove result", (i*colLoops+j) / (rowLoops*colLoops), NORMAL);
           }
           if (isAborted())
           {
               std::string msg = getName() + " has been aborted.";
               pStep->finalize(Message::Abort, msg);
               if (pProgress != NULL)
               {
                   pProgress->updateProgress(msg, 0, ABORT);
               }
               return false;
           }
      
           //Process the data in current block
		   ProcessData(pSrcAcc, pBuffer, rowIndex, colIndex, rowBlocks, colBlocks, ScaleKValue, pDesc->getDataType());

		   //Output the value 
           for (unsigned int m = 0; m < rowBlocks; m++)
		   {
			   for (unsigned int n = 0; n < colBlocks; n++)
			   {
				   if (!pDestAcc.isValid())
                   {
                       std::string msg = "Unable to access the cube data.";
                       pStep->finalize(Message::Failure, msg);
                       if (pProgress != NULL) 
                       {
                           pProgress->updateProgress(msg, 0, ERRORS);
                       }
                       return false;
                   }

				   pDestAcc->toPixel(rowIndex+m, colIndex+n);
				   
				   switchOnEncoding(ResultType, speckleNoiseRemove, pDestAcc->getColumn(), (pBuffer+m*colBlocks+n));
			   }
		   }
		   colIndex += colBlocks;
	   }
	   rowIndex += rowBlocks;
   }

   if (!isBatch())
   {
      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Noise removal is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Noise removal Result", pResultCube.release());

   pStep->finalize();
   return true;
}
Esempio n. 8
0
File: Sam.cpp Progetto: yuguess/GSoC
bool SamAlgorithm::processAll()
{
   auto_ptr<Wavelengths> pWavelengths;

   ProgressTracker progress(getProgress(), "Starting SAM", "spectral", "C4320027-6359-4F5B-8820-8BC72BF1B8F0");
   progress.getCurrentStep()->addProperty("Interactive", isInteractive());

   RasterElement* pElement = getRasterElement();
   if (pElement == NULL)
   {
      progress.report(SAMERR012, 0, ERRORS, true);
      return false;
   }
   progress.getCurrentStep()->addProperty("Cube", pElement->getName());
   const RasterDataDescriptor* pDescriptor = static_cast<RasterDataDescriptor*>(pElement->getDataDescriptor());
   VERIFY(pDescriptor != NULL);

   BitMaskIterator iter(getPixelsToProcess(), pElement);
   unsigned int numRows = iter.getNumSelectedRows();
   unsigned int numColumns = iter.getNumSelectedColumns();
   unsigned int numBands = pDescriptor->getBandCount();
   Opticks::PixelOffset layerOffset(iter.getColumnOffset(), iter.getRowOffset());

   // get cube wavelengths
   DynamicObject* pMetadata = pElement->getMetadata();
   if (pMetadata != NULL)
   {
      pWavelengths.reset(new Wavelengths(pMetadata));
      if (!pWavelengths->isEmpty() && (!pWavelengths->hasEndValues() || !pWavelengths->hasStartValues()))
      {
         pWavelengths->calculateFwhm();
      }
   }
   VERIFY(pWavelengths.get() != NULL);

   int sig_index = 0;
   bool bSuccess = true;

   if (mInputs.mSignatures.empty())
   {
      progress.report(SAMERR005, 0, ERRORS, true);
      return false;
   }
   int iSignatureCount = mInputs.mSignatures.size();

   // Get colors for all the signatures
   vector<ColorType> layerColors, excludeColors;
   excludeColors.push_back(ColorType(0, 0, 0));
   excludeColors.push_back(ColorType(255, 255, 255));
   ColorType::getUniqueColors(iSignatureCount, layerColors, excludeColors);

   // Create a vector for the signature names
   vector<string> sigNames;

   // Create a pseudocolor results matrix if necessary
   RasterElement* pPseudocolorMatrix = NULL;
   RasterElement* pLowestSAMValueMatrix = NULL;
   // Check for multiple Signatures and if the user has selected
   // to combined multiple results in one pseudocolor output layer
   if (iSignatureCount > 1 && mInputs.mbCreatePseudocolor)
   {
      pPseudocolorMatrix = createResults(numRows, numColumns, mInputs.mResultsName);
      pLowestSAMValueMatrix = createResults(numRows, numColumns, "LowestSAMValue");

      if (pPseudocolorMatrix == NULL || pLowestSAMValueMatrix == NULL )
      {
         progress.report(SAMERR007, 0, ERRORS, true);
         return false;
      }

      FactoryResource<DataRequest> pseudoRequest;
      pseudoRequest->setWritable(true);
      string failedDataRequestErrorMessage =
         SpectralUtilities::getFailedDataRequestErrorMessage(pseudoRequest.get(), pPseudocolorMatrix);
      DataAccessor pseudoAccessor = pPseudocolorMatrix->getDataAccessor(pseudoRequest.release());
      if (!pseudoAccessor.isValid())
      {
         string msg = "Unable to access results.";
         if (!failedDataRequestErrorMessage.empty())
         {
            msg += "\n" + failedDataRequestErrorMessage;
         }

         progress.report(msg, 0, ERRORS, true);
         return false;
      }

      FactoryResource<DataRequest> lsvRequest;
      lsvRequest->setWritable(true);
      failedDataRequestErrorMessage =
         SpectralUtilities::getFailedDataRequestErrorMessage(lsvRequest.get(), pLowestSAMValueMatrix);
      DataAccessor lowestSamValueAccessor = pLowestSAMValueMatrix->getDataAccessor(lsvRequest.release());
      if (!lowestSamValueAccessor.isValid())
      {
         string msg = "Unable to access results.";
         if (!failedDataRequestErrorMessage.empty())
         {
            msg += "\n" + failedDataRequestErrorMessage;
         }

         progress.report(msg, 0, ERRORS, true);
         return false;
      }

      //Lets zero out all the results incase we connect to an existing matrix.
      float* pPseudoValue = NULL;
      float* pLowestValue = NULL;

      for (unsigned int row_ctr = 0; row_ctr < numRows; row_ctr++)
      {
         for (unsigned int col_ctr = 0; col_ctr < numColumns; col_ctr++)
         {
            if (!pseudoAccessor.isValid() || !lowestSamValueAccessor.isValid())
            {
               progress.report("Unable to access results.", 0, ERRORS, true);
               return false;
            }

            pLowestValue = reinterpret_cast<float*>(lowestSamValueAccessor->getColumn());
            pPseudoValue = reinterpret_cast<float*>(pseudoAccessor->getColumn());

            //Initialize the matrices
            *pPseudoValue = 0.0f;
            *pLowestValue = 180.0f;

            pseudoAccessor->nextColumn();
            lowestSamValueAccessor->nextColumn();
         }
         pseudoAccessor->nextRow();
         lowestSamValueAccessor->nextRow();
      }
   }

   RasterElement* pResults = NULL;
   bool resultsIsTemp = false;

   // Processes each selected signature one at a time and
   // accumulates results
   for (sig_index = 0; bSuccess && (sig_index < iSignatureCount) && !mAbortFlag; sig_index++)
   {
      // Get the spectrum
      Signature* pSignature = mInputs.mSignatures[sig_index];

      // Create the results matrix
      sigNames.push_back(pSignature->getName());
      std::string rname = mInputs.mResultsName;
      if (iSignatureCount > 1 && !mInputs.mbCreatePseudocolor)
      {
         rname += " " + sigNames.back();
      }
      else if (iSignatureCount > 1)
      {
         rname += "SamTemp";
         resultsIsTemp = true;
      }
      pResults = createResults(numRows, numColumns, rname);
      if (pResults == NULL)
      {
         bSuccess = false;
         break;
      }

      //Send the message to the progress object
      QString messageSigNumber = QString("Processing Signature %1 of %2 : SAM running on signature %3")
         .arg(sig_index+1).arg(iSignatureCount).arg(QString::fromStdString(sigNames.back()));
      string message = messageSigNumber.toStdString();

      vector<double> spectrumValues;
      vector<int> resampledBands;
      bSuccess = resampleSpectrum(pSignature, spectrumValues, *pWavelengths.get(), resampledBands);

      // Check for limited spectral coverage and warning log 
      if (bSuccess && pWavelengths->hasCenterValues() &&
         resampledBands.size() != pWavelengths->getCenterValues().size())
      {
         QString buf = QString("Warning SamAlg014: The spectrum only provides spectral coverage for %1 of %2 bands.")
            .arg(resampledBands.size()).arg(pWavelengths->getCenterValues().size());
         progress.report(buf.toStdString(), 0, WARNING, true);
      }

      if (bSuccess)
      {
         BitMaskIterator iterChecker(getPixelsToProcess(), pElement);

         SamAlgInput samInput(pElement, pResults, spectrumValues, &mAbortFlag, iterChecker, resampledBands);

         //Output Structure
         SamAlgOutput samOutput;

         // Reports current Spectrum SAM is running on
         mta::ProgressObjectReporter reporter(message, getProgress());

         // Initializes all threads
         mta::MultiThreadedAlgorithm<SamAlgInput, SamAlgOutput, SamThread>
            mtaSam(Service<ConfigurationSettings>()->getSettingThreadCount(),
            samInput, 
            samOutput, 
            &reporter);

         // Calculates spectral angle for current signature
         mtaSam.run();

         if (samInput.mpResultsMatrix == NULL)
         {
            Service<ModelServices>()->destroyElement(pResults);
            progress.report(SAMERR006, 0, ERRORS, true);
            mAbortFlag = false;
            return false;
         }

         if ((isInteractive() || mInputs.mbDisplayResults) && iSignatureCount > 1 && mInputs.mbCreatePseudocolor)
         {
            // Merges results in to one output layer if a Pseudocolor
            // output layer has been selected
            FactoryResource<DataRequest> pseudoRequest, currentRequest, lowestRequest;
            pseudoRequest->setWritable(true);
            string failedDataRequestErrorMessage =
               SpectralUtilities::getFailedDataRequestErrorMessage(pseudoRequest.get(), pPseudocolorMatrix);
            DataAccessor daPseudoAccessor = pPseudocolorMatrix->getDataAccessor(pseudoRequest.release());
            if (!daPseudoAccessor.isValid())
            {
               string msg = "Unable to access data.";
               if (!failedDataRequestErrorMessage.empty())
               {
                  msg += "\n" + failedDataRequestErrorMessage;
               }

               progress.report(msg, 0, ERRORS, true);
               return false;
            }

            DataAccessor daCurrentAccessor = pResults->getDataAccessor(currentRequest.release());

            lowestRequest->setWritable(true);
            failedDataRequestErrorMessage =
               SpectralUtilities::getFailedDataRequestErrorMessage(lowestRequest.get(), pLowestSAMValueMatrix);
            DataAccessor daLowestSAMValue = pLowestSAMValueMatrix->getDataAccessor(lowestRequest.release());
            if (!daLowestSAMValue.isValid())
            {
               string msg = "Unable to access data.";
               if (!failedDataRequestErrorMessage.empty())
               {
                  msg += "\n" + failedDataRequestErrorMessage;
               }

               progress.report(msg, 0, ERRORS, true);
               return false;
            }

            float* pPseudoValue = NULL;
            float* pCurrentValue = NULL;
            float* pLowestValue = NULL; 

            for (unsigned  int row_ctr = 0; row_ctr < numRows; row_ctr++)
            {
               for (unsigned  int col_ctr = 0; col_ctr < numColumns; col_ctr++)
               {
                  if (!daPseudoAccessor.isValid() || !daCurrentAccessor.isValid())
                  {
                     Service<ModelServices>()->destroyElement(pResults);
                     progress.report("Unable to access data.", 0, ERRORS, true);
                     return false;
                  }
                  daPseudoAccessor->toPixel(row_ctr, col_ctr);
                  daCurrentAccessor->toPixel(row_ctr, col_ctr);

                  pPseudoValue = reinterpret_cast<float*>(daPseudoAccessor->getColumn());
                  pCurrentValue = reinterpret_cast<float*>(daCurrentAccessor->getColumn());

                  daLowestSAMValue->toPixel(row_ctr, col_ctr);
                  pLowestValue = reinterpret_cast<float*>(daLowestSAMValue->getColumn());

                  if (*pCurrentValue <= mInputs.mThreshold)
                  {
                     if (*pCurrentValue < *pLowestValue)
                     {
                        *pPseudoValue = sig_index+1;
                        *pLowestValue = *pCurrentValue;
                     }
                  }
               }
            }
         }
         else
         {
            ColorType color;
            if (sig_index <= static_cast<int>(layerColors.size()))
            {
               color = layerColors[sig_index];
            }

            double dMaxValue = pResults->getStatistics()->getMax();

            // Displays results for current signature
            displayThresholdResults(pResults, color, LOWER, mInputs.mThreshold, dMaxValue, layerOffset);
         }

         //If we are on the last signature then destroy the lowest value Matrix
         if (sig_index == iSignatureCount-1)
         {
            if (pLowestSAMValueMatrix != NULL)
            {
               Service<ModelServices>()->destroyElement(pLowestSAMValueMatrix);
               pLowestSAMValueMatrix = NULL;
            }
         }
      }
   } //End of Signature Loop Counter

   if (resultsIsTemp || !bSuccess)
   {
      Service<ModelServices>()->destroyElement(pResults);
      pResults = NULL;
   }

   if (bSuccess)
   {
      // Displays final Pseudocolor output layer results
      if ((isInteractive() || mInputs.mbDisplayResults) && iSignatureCount > 1 && mInputs.mbCreatePseudocolor)
      {
         displayPseudocolorResults(pPseudocolorMatrix, sigNames, layerOffset);
      }
   }

   // Aborts gracefully after clean up
   if (mAbortFlag)
   {
      progress.abort();
      mAbortFlag = false;
      return false;
   }

   if (bSuccess)
   {
      if (pPseudocolorMatrix != NULL)
      {
         mpResults = pPseudocolorMatrix;
         mpResults->updateData();
      }
      else if (pResults != NULL)
      {
         mpResults = pResults;
         mpResults->updateData();
      }
      else
      {
         progress.report(SAMERR016, 0, ERRORS, true);
         return false;
      }
      progress.report(SAMNORM200, 100, NORMAL);
   }

   progress.getCurrentStep()->addProperty("Display Layer", mInputs.mbDisplayResults);
   progress.getCurrentStep()->addProperty("Threshold", mInputs.mThreshold);
   progress.upALevel();

   return bSuccess;
}
bool KDISTRIBUTION::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
	
   StepResource pStep("KDISTRIBUTION", "app10", "F298D57C-D816-42F0-AE27-43DAA02C0544");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());

   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL)
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }

      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   FactoryResource<DataRequest> pRequest;
   FactoryResource<DataRequest> pRequest2;

   

   pRequest->setInterleaveFormat(BSQ);
   pRequest2->setInterleaveFormat(BSQ);
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());
   DataAccessor pAcc2 = pCube->getDataAccessor(pRequest2.release());


   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
   "Result", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType()));

   if (pResultCube.get() == NULL)
   {
      std::string msg = "A raster cube could not be created.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());
   const RasterDataDescriptor* pDescriptor = dynamic_cast<const RasterDataDescriptor*>(pCube->getDataDescriptor());


  
   int tester_count = 0;
   int eastCol = 0;
   int northRow = 0;
   int westCol = 0;
   int southRow = 0;
   double zstatistic = 0;
   double total = 0.0;
   double total_sum = 0.0;
   double mean = 0.0;
   double std = 0.0;
   double a=0;
   int rowSize=pDesc->getRowCount();
   int colSize=pDesc->getColumnCount();
   int prevCol = 0;
   int prevRow = 0;
   int nextCol = 0;
   int nextRow = 0;
   double long PFA = 0.0;
   int DEPTH1 = 10;
   int DEPTH2 = 10;
   int DEPTH3 = 1;
   int DEPTH4 = 1;
   int count=0;
   int zero=0;
   double long threshold = 100000.0;


   double look_table1[24][6];

   for(int i=0; i<24; i++)
   {
	   for(int j=0; j<3; j++)
	   {
			   look_table1[i][j]=0.0;
			   	   
	   }
   }
      


   QStringList Names("0.0000001");
   QString value = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Input a PFA value", "Input a PFA value (0.0000001 or 0.00000001)", Names);
   
   std::string strAoi = value.toStdString();
   std::istringstream stm;
   stm.str(strAoi);
   //stm >> PFA;
   PFA=::atof(strAoi.c_str());

   

   if (PFA==0.0000001)
   {
	    

   look_table1[0][0]=1.0;
   look_table1[0][1]=5.0;
   look_table1[0][2]=32.3372530103729330;
   look_table1[1][0]=1.0;
   look_table1[1][1]=10.0;
   look_table1[1][2]=25.0723580041031010;
   look_table1[2][0]=1.0;
   look_table1[2][1]=15.0;
   look_table1[2][2]=22.3991160013551250;
   look_table1[3][0]=1.0;
   look_table1[3][1]=20.0;
   look_table1[3][2]=20.9821949998985920;
   look_table1[4][1]=1.0;
   look_table1[4][2]=40.0;
   look_table1[5][3]=18.7055519975583020;
   look_table1[5][1]=1.0;
   look_table1[5][2]=90.0;
   look_table1[5][3]=18.7055519975583020;

   look_table1[6][0]=2.0;
   look_table1[6][1]=5.0;
   look_table1[6][2]=20.2619339991581950;
   look_table1[7][0]=2.0;
   look_table1[7][1]=10.0;
   look_table1[7][2]=15.4860609951617470;
   look_table1[8][0]=2.0;
   look_table1[8][1]=15.0;
   look_table1[8][2]=13.7276789964777210;
   look_table1[9][0]=2.0;
   look_table1[9][1]=20.0;
   look_table1[9][2]=12.7942589971762930;
   look_table1[10][0]=2.0;
   look_table1[10][1]=40.0;
   look_table1[10][2]=11.2895769983023970;
   look_table1[11][0]=2.0;
   look_table1[11][1]=90.0;
   look_table1[11][2]=10.3695259989909640;

   look_table1[12][0]=3.0;
   look_table1[12][1]=5.0;
   look_table1[12][2]=15.9102209948443050;
   look_table1[13][0]=3.0;
   look_table1[13][1]=10.0;
   look_table1[13][2]=12.0443629977375150;
   look_table1[14][0]=3.0;
   look_table1[14][1]=15.0;
   look_table1[14][2]=10.6203179988032710;
   look_table1[15][0]=3.0;
   look_table1[15][1]=20.0;
   look_table1[15][2]=9.8635499993696367;
   look_table1[16][0]=3.0;
   look_table1[16][1]=40.0;
   look_table1[16][2]=8.6407550002847771;
   look_table1[17][0]=3.0;
   look_table1[17][1]=90.0;
   look_table1[17][2]=7.8893780007488568;

   look_table1[18][0]=4.0;
   look_table1[18][1]=5.0;
   look_table1[18][2]=13.6166519965608130;
   look_table1[19][0]=4.0;
   look_table1[19][1]=10.0;
   look_table1[19][2]=10.2336029990926890;
   look_table1[20][0]=4.0;
   look_table1[20][1]=15.0;
   look_table1[20][2]=10.6203179988032710;
   look_table1[21][0]=4.0;
   look_table1[21][1]=20.0;
   look_table1[21][2]=8.9868610000257512;
   look_table1[22][0]=4.0;
   look_table1[22][1]=40.0;
   look_table1[22][2]=7.2502150006595159;
   look_table1[23][0]=4.0;
   look_table1[23][1]=90.0;
   look_table1[23][2]=6.5879140005669408;
   }
   
   
   if (PFA==0.00000001)
   {
   look_table1[0][0]=1.0;
   look_table1[0][1]=5.0;
   look_table1[0][2]=20.0000019988889410;
   look_table1[1][0]=1.0;
   look_table1[1][1]=10.0;
   look_table1[1][2]=20.0000019988889410;
   look_table1[2][0]=1.0;
   look_table1[2][1]=15.0;
   look_table1[2][2]=20.0000019988889410;
   look_table1[3][0]=1.0;
   look_table1[3][1]=20.0;
   look_table1[3][2]=20.0000019988889410;
   look_table1[4][1]=1.0;
   look_table1[4][2]=40.0;
   look_table1[5][3]=20.0000019988889410;
   look_table1[5][1]=1.0;
   look_table1[5][2]=90.0;
   look_table1[5][3]=20.0000019988889410;

   look_table1[6][0]=2.0;
   look_table1[6][1]=5.0;
   look_table1[6][2]=18.3243529971664460;
   look_table1[7][0]=2.0;
   look_table1[7][1]=10.0;
   look_table1[7][2]=18.3243529971664460;
   look_table1[8][0]=2.0;
   look_table1[8][1]=15.0;
   look_table1[8][2]=16.0869139948664570;
   look_table1[9][0]=2.0;
   look_table1[9][1]=20.0;
   look_table1[9][2]=14.8998299956004820;
   look_table1[10][0]=2.0;
   look_table1[10][1]=40.0;
   look_table1[10][2]=12.9846719970337880;
   look_table1[11][0]=2.0;
   look_table1[11][1]=90.0;
   look_table1[11][2]=11.8094659979133120;

   look_table1[12][0]=3.0;
   look_table1[12][1]=5.0;
   look_table1[12][2]=18.9816659978421360;
   look_table1[13][0]=3.0;
   look_table1[13][1]=10.0;
   look_table1[13][2]=14.1167729961865230;
   look_table1[14][0]=3.0;
   look_table1[14][1]=15.0;
   look_table1[14][2]=12.3304539975234050;
   look_table1[15][0]=3.0;
   look_table1[15][1]=20.0;
   look_table1[15][2]=11.3819769982332450;
   look_table1[16][0]=3.0;
   look_table1[16][1]=40.0;
   look_table1[16][2]=9.8488249993806569;
   look_table1[17][0]=3.0;
   look_table1[17][1]=90.0;
   look_table1[17][2]=8.9039850000877756;

   look_table1[18][0]=4.0;
   look_table1[18][1]=5.0;
   look_table1[18][2]=16.1272319949079020;
   look_table1[19][0]=4.0;
   look_table1[19][1]=10.0;
   look_table1[19][2]=11.9117899978367330;
   look_table1[20][0]=4.0;
   look_table1[20][1]=15.0;
   look_table1[20][2]=10.3636999989953240;
   look_table1[21][0]=4.0;
   look_table1[21][1]=20.0;
   look_table1[21][2]=9.5411879996108926;
   look_table1[22][0]=4.0;
   look_table1[22][1]=40.0;
   look_table1[22][2]=8.2095870006074634;
   look_table1[23][0]=4.0;
   look_table1[23][1]=90.0;
   look_table1[23][2]=7.3860650006785047;
   }
   

   QStringList Names1("10");
   QString value1 = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Input the size of the window width", "Input the size of the window width in terms of the number of pixels (eg. 10)", Names1);
   
   std::string strAoi1 = value1.toStdString();
   std::istringstream stm1;
   stm1.str(strAoi1);
   //stm1 >> DEPTH1;
   DEPTH1=::atof(strAoi1.c_str());

   QStringList Names2("10");
   QString value2 = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Input the size of the window height", "Input the size of the window height in terms of the number of pixels (eg. 10)", Names2);
   
   std::string strAoi2 = value2.toStdString();
   std::istringstream stm2;
   stm2.str(strAoi2);
   //stm2 >> DEPTH2;
   DEPTH2=::atof(strAoi2.c_str());

   QStringList Names3("1");
   QString value3 = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Input the size of the gaurd width", "Input the size of the guard width in terms of the number of pixels (eg. 1)", Names3);
   
   std::string strAoi3 = value3.toStdString();
   std::istringstream stm3;
   stm3.str(strAoi3);
   //stm3 >> DEPTH3;
   DEPTH3=::atof(strAoi3.c_str());

   QStringList Names4("1");
   QString value4 = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Input the size of the guard height", "Input the size of the guard height in terms of the number of pixels (eg. 1)", Names4);
   
   std::string strAoi4 = value4.toStdString();
   std::istringstream stm4;
   stm4.str(strAoi4);
   stm4 >> DEPTH4;
   DEPTH4=::atof(strAoi4.c_str());

   for (int row = 0; row < rowSize; ++row)
   {

      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }

         return false;
      }
      if (!pAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }

         return false;
      }

      if (pProgress != NULL)
      {
         pProgress->updateProgress("Calculating statistics", row * 100 / pDesc->getRowCount(), NORMAL);
      }
	  		
	  

      for (int col = 0; col < colSize; ++col)
      {
		  //p[col]=pAcc2->getColumnAsInteger();
		  
		  westCol=max(col-DEPTH1,zero);
		  northRow=max(row-DEPTH2,zero);
		  eastCol=min(colSize-1,col+DEPTH1);
		  southRow=min(rowSize-1,row+DEPTH2);
		  prevCol=max(col-DEPTH3,zero);
		  prevRow=max(row-DEPTH4,zero);
		  nextCol=min(col+DEPTH3,colSize-1);
		  nextRow=min(row+DEPTH4,rowSize-1);

			pAcc2->toPixel(northRow,westCol);
			
			for(int row1=northRow; row1 < southRow+1; ++row1)
			{
								
				for (int col1=westCol; col1 < eastCol+1; ++col1)
				{

					if((row1>=prevRow && row1<=nextRow) && (col1>=prevCol && col1<=nextCol))
					{
						continue;
					}

					else
					{	   
					 updateStatistics3(pAcc2->getColumnAsDouble(), total, total_sum, count);
					}


					pAcc2->nextColumn();

				}

				pAcc2->nextRow();
			}

			mean = total / count;
			std = sqrt(total_sum / count - mean * mean);
			int ELVI = (mean/std)*(mean/std);
			int v = (ELVI+1)/((ELVI*mean/(std*std))-1);

			pAcc2->toPixel(row,col);
			pDestAcc->toPixel(row,col);
			zstatistic = (pAcc2->getColumnAsDouble()-mean)/std;

				 if(v<=7 && v>=0)
				 { v=5;
				 }

				 if(v<=12 && v>7)
				 {
					 v=10;
				 }

				 if(v<=17 && v>12)
				 {
					 v=15;
				 }

				 if(v<=30 && v>17)
				 {
					 v=20;
				 }

				 if(v<=65 && v>30)
				 {
					 v=40;
				 }

				 if(v<=90 && v>65)
				 {
					 v=90;
				 }


			for(int i=0; i<24; i++)
			{
				if((look_table1[i][0]=ELVI) && (look_table1[i][1]==v))
				{
					threshold=look_table1[i][2];
				}
			}
					
			

			if(zstatistic>threshold)
			{

				switchOnEncoding(pDesc->getDataType(), conversion1, pDestAcc->getColumn(), 1000.0);
			}

			else
			{
				switchOnEncoding(pDesc->getDataType(), conversion1, pDestAcc->getColumn(), 0.0);
			}

			total = 0.0;
			total_sum=0.0;
            threshold=100000.0;
            mean = 0.0;
            std = 0.0;
			count=0;



			pAcc->nextColumn();
	  }

      pAcc->nextRow();

   }



      // Create a GCP layer

/*
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(Service<DesktopServices>()->createWindow(pResultCube.get()->getName(), SPATIAL_DATA_WINDOW));

   SpatialDataView* pView = pWindow->getSpatialDataView();
   */


      Service<DesktopServices> pDesktop;

      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(),
         SPATIAL_DATA_WINDOW));

      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         std::string msg = "Unable to create view.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }

      pView->setPrimaryRasterElement(pResultCube.get());
      pView->createLayer(RASTER, pResultCube.get());


	  // Create the GCP list
	     if (pCube->isGeoreferenced() == true)
		 {


   
      const vector<DimensionDescriptor>& rows = pDescriptor->getRows();
      const vector<DimensionDescriptor>& columns = pDescriptor->getColumns();
      if ((rows.empty() == false) && (columns.empty() == false))
      {
         // Get the geocoordinates at the chip corners
		  /*
         VERIFYNRV(rows.front().isActiveNumberValid() == true);
         VERIFYNRV(rows.back().isActiveNumberValid() == true);
         VERIFYNRV(columns.front().isActiveNumberValid() == true);
         VERIFYNRV(columns.back().isActiveNumberValid() == true);
		 */

         unsigned int startRow = rows.front().getActiveNumber();
         unsigned int endRow = rows.back().getActiveNumber();
         unsigned int startCol = columns.front().getActiveNumber();
         unsigned int endCol = columns.back().getActiveNumber();

         GcpPoint ulPoint;
         ulPoint.mPixel = LocationType(startCol, startRow);
         ulPoint.mCoordinate = pCube->convertPixelToGeocoord(ulPoint.mPixel);

         GcpPoint urPoint;
         urPoint.mPixel = LocationType(endCol, startRow);
         urPoint.mCoordinate = pCube->convertPixelToGeocoord(urPoint.mPixel);

         GcpPoint llPoint;
         llPoint.mPixel = LocationType(startCol, endRow);
         llPoint.mCoordinate = pCube->convertPixelToGeocoord(llPoint.mPixel);

         GcpPoint lrPoint;
         lrPoint.mPixel = LocationType(endCol, endRow);
         lrPoint.mCoordinate = pCube->convertPixelToGeocoord(lrPoint.mPixel);

         GcpPoint centerPoint;
         centerPoint.mPixel = LocationType((startCol + endCol) / 2, (startRow + endRow) / 2);
         centerPoint.mCoordinate = pCube->convertPixelToGeocoord(centerPoint.mPixel);

		 /*
         // Reset the coordinates to be in active numbers relative to the chip
         const vector<DimensionDescriptor>& chipRows = pDescriptor->getRows();
         const vector<DimensionDescriptor>& chipColumns = pDescriptor->getColumns();
		 
         VERIFYNRV(chipRows.front().isActiveNumberValid() == true);
         VERIFYNRV(chipRows.back().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.front().isActiveNumberValid() == true);
         VERIFYNRV(chipColumns.back().isActiveNumberValid() == true);
		 
         unsigned int chipStartRow = chipRows.front().getActiveNumber();
         unsigned int chipEndRow = chipRows.back().getActiveNumber();
         unsigned int chipStartCol = chipColumns.front().getActiveNumber();
         unsigned int chipEndCol = chipColumns.back().getActiveNumber();
         ulPoint.mPixel = LocationType(chipStartCol, chipStartRow);
         urPoint.mPixel = LocationType(chipEndCol, chipStartRow);
         llPoint.mPixel = LocationType(chipStartCol, chipEndRow);
         lrPoint.mPixel = LocationType(chipEndCol, chipEndRow);
         centerPoint.mPixel = LocationType((chipStartCol + chipEndCol) / 2, (chipStartRow + chipEndRow) / 2);
		 */
         
         Service<ModelServices> pModel;

         GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement("Corner Coordinates",
            TypeConverter::toString<GcpList>(), pResultCube.get()));
         if (pGcpList != NULL)
         {
            list<GcpPoint> gcps;
            gcps.push_back(ulPoint);
            gcps.push_back(urPoint);
            gcps.push_back(llPoint);
            gcps.push_back(lrPoint);
            gcps.push_back(centerPoint);

            pGcpList->addPoints(gcps);

			pView->createLayer(GCP_LAYER, pGcpList);
		 }
	  }
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("CFAR is compete.", 100, NORMAL);
   }

   pOutArgList->setPlugInArgValue("Result", pResultCube.release());

   pStep->finalize();
   return true;
   
}
Esempio n. 10
0
 void toPixel(int x, int y) {
     dataAccessor->toPixel(y, x);
     if (!dataAccessor.isValid()) { qDebug("DataAccessor invalid after toPixel"); /* throw exception */ }
 }