Exemple #1
0
TInt TFsFormatNext::DoRequestL(CFsRequest* aRequest)
//
// Format the next part of the media.
//
	{

	__PRINT1(_L("TFsFormatNext::DoRequestL() drv:%d"), aRequest->DriveNumber());
	CFormatCB* format=(CFormatCB*)aRequest->ScratchValue();
	TInt r=format->CheckMount();
	if (r!=KErrNone && r!=KErrInUse)
        {
    	__PRINT1(_L("TFsFormatNext::DoRequestL() err:%d"), r);
        return r;
        }

	TPtr8 pStep((TUint8*)&format->CurrentStep(),sizeof(TInt));
	aRequest->ReadL(KMsgPtr0,pStep);

	OstTrace1(TRACE_FILESYSTEM, FSYS_ECFORMATCBDOFORMATSTEPL, "this %x", format);

	TRAP(r,format->DoFormatStepL());

	OstTraceExt2(TRACE_FILESYSTEM, FSYS_ECFORMATCBDOFORMATSTEPLRET, "r %d  iCurrentStep %d", r, (TUint) format->CurrentStep());

	if (r==KErrNone)
		aRequest->WriteL(KMsgPtr0,pStep);
	if (r==KErrNone && format->CurrentStep()==0)
		{
		FsNotify::DiskChange(aRequest->DriveNumber());
		}
	return(r);
	}
bool GetPrimaryRasterLayer::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "5D20DF72-1C71-4a5d-9B1A-398A91154EBD");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (pInArgList == NULL || pOutArgList == NULL)
   {
      reportError("Invalid Plug-In Arg List specified.", "8161F92F-124F-4118-8E24-532187A442AA");
      return false;
   }

   if (extractInputArgs(pInArgList) == false)
   {
      return false;
   }

   LayerList* pLayerList = mpSpatialDataView->getLayerList();
   VERIFY(pLayerList != NULL);

   RasterElement* pElement = pLayerList->getPrimaryRasterElement();
   RasterLayer* pLayer = dynamic_cast<RasterLayer*>(pLayerList->getLayer(RASTER, pElement));
   if (pOutArgList->setPlugInArgValue(Executable::LayerArg(), pLayer) == false)
   {
      reportError("Unable to set output argument.", "B4DE1827-3B96-4a96-89BB-62431B6E81CF");
      return false;
   }

   reportComplete();
   return true;
}
bool Interpolation::print_DEM_on_file(std::string name_file, Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> demRM)
{
	StepResource pStep("Writing DEM on a text file", "app", "c0c1c382-1f1e-11e4-b0cb-b2227cce2b54");
	ProgressResource pResource("ProgressBar");
	Progress *pProgress = pResource.get(); 
    pProgress-> setSettingAutoClose(true);
	
	std::ofstream dem_file;
	dem_file.open (name_file);
    dem_file << "DEM generated from the input LAS file\n";
	dem_file << "i" << '\t' << "j" << '\t' << "z(i,j)" << '\n';  
	for (int row = 0; row < demRM.rows(); row++)
	{
			for (int col = 0; col <demRM.cols(); col++)
			{
				dem_file << row << '\t' << col << '\t' << demRM(row, col) << '\n';  
			}
			pProgress->updateProgress("Writing DEM ("+ name_file + ") on a text file", row * 100 / demRM.rows(), NORMAL);
	}
	dem_file.close();

    pProgress->updateProgress("DEM text file written.", 100, NORMAL);
	pStep->finalize();
	return true;
}
Exemple #4
0
bool DeriveProduct::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "58FE5CAB-E941-4E60-BA55-B29D70715FC4");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "5E158F48-6089-4A88-ABD0-55C717BD13E2");
      return false;
   }
   View* pView = pInArgList->getPlugInArgValue<View>("View");
   if (pView == NULL)
   {
      std::vector<Window*> windows;
      Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
      if (!windows.empty())
      {
         pView = static_cast<SpatialDataWindow*>(windows.front())->getSpatialDataView();
      }
   }
   if (pView == NULL)
   {
      reportError("No view provided.", "852F585B-D239-4C0A-B993-70EE68EC8DEE");
      return false;
   }

   ProductWindow* pProductWindow = Service<DesktopServices>()->deriveProduct(pView);
   if (pProductWindow == NULL)
   {
      reportError("Unable to derive product", "E24BB5A5-A675-4897-9C48-A4E4109379DF");
      return false;
   }

   // Load a template if one is specified
   Filename* pTemplate = pInArgList->getPlugInArgValue<Filename>("Template");
   if (pTemplate != NULL)
   {
      if (!pProductWindow->getProductView()->loadTemplate(pTemplate->getFullPathAndName()))
      {
         reportError("Could not load the requested template!", "C99CE97E-3F0F-4CBB-8460-28D96D55596B");
         return false;
      }
   }

   // Set the output values
   if (!pOutArgList->setPlugInArgValue("Window", pProductWindow) ||
      !pOutArgList->setPlugInArgValue("View", pProductWindow->getProductView()))
   {
      reportError("Could not set the data set output value!", "3C53EDAE-DC70-4141-9759-ECD3EB9BE186");
      return false;
   }

   reportComplete();
   pStep->finalize(Message::Success);
   return true;
}
bool LiDAR_roof_segmentation::showGui()
{

	StepResource pStep( "Start gui", "app", "a520c744-1d6c-11e4-a3ec-b2227cce2b54" );
	
	Service<DesktopServices> pDesktop;

	mpGui = new Gui( pDesktop->getMainWidget(), "Gui", false);
	VERIFYNR(connect(mpGui, SIGNAL(finished(int)), this, SLOT(dialogClosed())));
	
	mpGui->show();
	//mpGui->exec(); // I should use this, as Trevor suggested
	pStep->finalize(Message::Success);
	return true;
}
bool SetDisplayMode::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "0B137CEF-B7AF-4999-95AC-2873C39279E5");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (extractInputArgs(pInArgList) == false)
   {
      return false;
   }

   mpRasterLayer->setDisplayMode(mDisplayMode);
   reportComplete();
   return true;
}
Exemple #7
0
bool ThresholdData::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   VERIFY(pInArgList != NULL);
   StepResource pStep("Execute Wizard Item", "app", "{2501975d-7cd5-49b0-a3e7-49f7106793c0}");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      return false;
   }

   const RasterDataDescriptor* pDesc = static_cast<const RasterDataDescriptor*>(mpInputElement->getDataDescriptor());
   VERIFY(pDesc);
   DimensionDescriptor band;
   if (mDisplayBandNumber > 0)
   {
      band = pDesc->getOriginalBand(mDisplayBandNumber - 1);
      if (band.isValid() == false)
      {
         reportError("The specified band is invalid.", "{a529538b-5b82-425d-af10-385a2581beec}");
         return false;
      }
   }
   else
   {
      band = pDesc->getActiveBand(mDisplayBandNumber);
   }
   FactoryResource<DataRequest> pReq;
   pReq->setInterleaveFormat(BSQ);
   pReq->setBands(band, band, 1);
   DataAccessor acc = mpInputElement->getDataAccessor(pReq.release());
   if (!acc.isValid())
   {
      reportError("Unable to access data element.", "{b5f1b7dd-7cf7-4cd5-b5bc-7b747d3561b9}");
      return false;
   }

   // If necessary, convert region units
   if (mRegionUnits != RAW_VALUE)
   {
      Statistics* pStatistics = mpInputElement->getStatistics(band);
      if (pStatistics == NULL)
      {
         reportError("Unable to calculate data statistics.", "{61a44ced-a4aa-4423-b379-5783137eb980}");
         return false;
      }
      mFirstThreshold = convertToRawUnits(pStatistics, mRegionUnits, mFirstThreshold);
      mSecondThreshold = convertToRawUnits(pStatistics, mRegionUnits, mSecondThreshold);
   }
   FactoryResource<BitMask> pBitmask;
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      reportProgress("Thresholding data", 100 * row / pDesc->getRowCount(),
         "{2fc3dbea-1307-471c-bba2-bf86032be518}");
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         VERIFY(acc.isValid());
         double val = ModelServices::getDataValue(pDesc->getDataType(), acc->getColumn(), 0);
         switch (mPassArea)
         {
         case UPPER:
            if (val >= mFirstThreshold)
            {
               pBitmask->setPixel(col, row, true);
            }
            break;
         case LOWER:
            if (val <= mFirstThreshold)
            {
               pBitmask->setPixel(col, row, true);
            }
            break;
         case MIDDLE:
            if (val >= mFirstThreshold && val <= mSecondThreshold)
            {
               pBitmask->setPixel(col, row, true);
            }
            break;
         case OUTSIDE:
            if (val <= mFirstThreshold || val >= mSecondThreshold)
            {
               pBitmask->setPixel(col, row, true);
            }
            break;
         default:
            reportError("Unknown or invalid pass area.", "{19c92b3b-52e9-442b-a01f-b545f819f200}");
            return false;
         }
         acc->nextColumn();
      }
      acc->nextRow();
   }
   std::string aoiName = pDesc->getName() + "_aoi";
   ModelResource<AoiElement> pAoi(aoiName, mpInputElement);
   if (pAoi.get() == NULL)
   {
      reportWarning("Overwriting existing AOI.", "{d953a030-dd63-43a1-98db-b0f491dee123}");
      Service<ModelServices>()->destroyElement(
         Service<ModelServices>()->getElement(aoiName, TypeConverter::toString<AoiElement>(), mpInputElement));
      pAoi = ModelResource<AoiElement>(aoiName, mpInputElement);
   }
   if (pAoi.get() == NULL)
   {
      reportError("Unable to create output AOI.", "{f76c2f4d-9a7f-4055-9383-022116cdcadb}");
      return false;
   }
   pAoi->addPoints(pBitmask.get());
   AoiLayer* pLayer = NULL;
   if (mpView != NULL)
   {
      if ((pLayer = static_cast<AoiLayer*>(mpView->createLayer(AOI_LAYER, pAoi.get()))) == NULL)
      {
         reportWarning("Unable to create AOI layer, continuing thresholding.",
            "{5eca6ea0-33c1-4b1a-b777-c8e1b86fd2fb}");
      }
   }
   if (pOutArgList != NULL)
   {
      pOutArgList->setPlugInArgValue("Result", pAoi.get());
      if (pLayer != NULL)
      {
         pOutArgList->setPlugInArgValue("Result Layer", pLayer);
      }
   }
   pAoi.release();

   reportComplete();
   return true;
}
bool SpectralLibraryManager::generateResampledLibrary(const RasterElement* pRaster)
{
    VERIFY(pRaster != NULL);

    // check that lib sigs are in same units as the raster element
    const RasterDataDescriptor* pDesc = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor());
    VERIFY(pDesc != NULL);
    const Units* pUnits = pDesc->getUnits();
    if (pDesc->getUnits()->getUnitType() != mLibraryUnitType)
    {
        if (Service<DesktopServices>()->showMessageBox("Mismatched Units", "The data are not in the "
                "same units as the spectral library.\n Do you want to continue anyway?", "Yes", "No") == 1)
        {
            return false;
        }
    }

    FactoryResource<Wavelengths> pWavelengths;
    pWavelengths->initializeFromDynamicObject(pRaster->getMetadata(), false);

    // populate the library with the resampled signatures
    PlugInResource pPlugIn("Resampler");
    Resampler* pResampler = dynamic_cast<Resampler*>(pPlugIn.get());
    VERIFY(pResampler != NULL);
    if (pWavelengths->getNumWavelengths() != pDesc->getBandCount())
    {
        mpProgress->updateProgress("Wavelength information in metadata does not match the number of bands "
                                   "in the raster element", 0, ERRORS);
        return false;
    }

    // get resample suitable signatures - leave out signatures that don't cover the spectral range of the data
    std::vector<std::vector<double> > resampledData;
    resampledData.reserve(mSignatures.size());
    std::vector<Signature*> resampledSignatures;
    resampledSignatures.reserve(mSignatures.size());
    std::vector<std::string> unsuitableSignatures;
    std::vector<double> sigValues;
    std::vector<double> sigWaves;
    std::vector<double> rasterWaves = pWavelengths->getCenterValues();
    std::vector<double> rasterFwhm = pWavelengths->getFwhm();
    std::vector<double> resampledValues;
    std::vector<int> bandIndex;
    DataVariant data;
    for (std::vector<Signature*>::const_iterator it = mSignatures.begin(); it != mSignatures.end(); ++it)
    {
        data = (*it)->getData(SpectralLibraryMatch::getNameSignatureWavelengthData());
        VERIFY(data.isValid());
        VERIFY(data.getValue(sigWaves));
        resampledValues.clear();
        data = (*it)->getData(SpectralLibraryMatch::getNameSignatureAmplitudeData());
        VERIFY(data.isValid());
        VERIFY(data.getValue(sigValues));
        double scaleFactor = (*it)->getUnits(
                                 SpectralLibraryMatch::getNameSignatureAmplitudeData())->getScaleFromStandard();
        for (std::vector<double>::iterator sit = sigValues.begin(); sit != sigValues.end(); ++sit)
        {
            *sit *= scaleFactor;
        }

        std::string msg;
        if (pResampler->execute(sigValues, resampledValues, sigWaves, rasterWaves, rasterFwhm, bandIndex, msg) == false
                || resampledValues.size() != rasterWaves.size())
        {
            unsuitableSignatures.push_back((*it)->getName());
            continue;
        }

        resampledData.push_back(resampledValues);
        resampledSignatures.push_back(*it);
    }

    if (resampledSignatures.empty())
    {
        std::string errMsg = "None of the signatures in the library cover the spectral range of the data.";
        if (mpProgress != NULL)
        {
            mpProgress->updateProgress(errMsg, 0, ERRORS);
            return false;
        }
    }
    if (unsuitableSignatures.empty() == false)
    {
        std::string warningMsg = "The following library signatures do not cover the spectral range of the data:\n";
        for (std::vector<std::string>::iterator it = unsuitableSignatures.begin();
                it != unsuitableSignatures.end(); ++it)
        {
            warningMsg += *it + "\n";
        }
        warningMsg += "These signatures will not be searched for in the data.";
        Service<DesktopServices>()->showMessageBox("SpectralLibraryManager", warningMsg);

        StepResource pStep("Spectral LibraryManager", "spectral", "64B6C87A-A6C3-4378-9B6E-221D89D8707B");
        pStep->finalize(Message::Unresolved, warningMsg);
    }

    std::string libName = "Resampled Spectral Library";

    // Try to get the resampled lib element in case session was restored. If NULL, create a new raster element with
    // num rows = num valid signatures, num cols = 1, num bands = pRaster num bands
    RasterElement* pLib = dynamic_cast<RasterElement*>(Service<ModelServices>()->getElement(libName,
                          TypeConverter::toString<RasterElement>(), pRaster));
    if (pLib != NULL)
    {
        // check that pLib has same number of sigs as SpectralLibraryManager
        RasterDataDescriptor* pLibDesc = dynamic_cast<RasterDataDescriptor*>(pLib->getDataDescriptor());
        VERIFY(pLibDesc != NULL);
        if (pLibDesc->getRowCount() != mSignatures.size())
        {
            mpProgress->updateProgress("An error occurred during session restore and some signatures were not restored."
                                       " Check the spectral library before using.", 0, ERRORS);
            Service<ModelServices>()->destroyElement(pLib);
            pLib = NULL;
        }
    }
    bool isNewElement(false);
    if (pLib == NULL)
    {
        pLib = RasterUtilities::createRasterElement(libName,
                static_cast<unsigned int>(resampledData.size()), 1, pDesc->getBandCount(), FLT8BYTES, BIP,
                true, const_cast<RasterElement*>(pRaster));
        isNewElement = true;
    }
    if (pLib == NULL)
    {
        mpProgress->updateProgress("Error occurred while trying to create the resampled spectral library", 0, ERRORS);
        return false;
    }

    RasterDataDescriptor* pLibDesc = dynamic_cast<RasterDataDescriptor*>(pLib->getDataDescriptor());
    VERIFY(pLibDesc != NULL);

    // copy resampled data into new element
    if (isNewElement)
    {
        FactoryResource<DataRequest> pRequest;
        pRequest->setWritable(true);
        pRequest->setRows(pLibDesc->getActiveRow(0), pLibDesc->getActiveRow(pLibDesc->getRowCount()-1), 1);
        DataAccessor acc = pLib->getDataAccessor(pRequest.release());
        for (std::vector<std::vector<double> >::iterator sit = resampledData.begin(); sit != resampledData.end(); ++sit)
        {
            VERIFY(acc->isValid());
            void* pData = acc->getColumn();
            memcpy(acc->getColumn(), &(sit->begin()[0]), pLibDesc->getBandCount() * sizeof(double));
            acc->nextRow();
        }

        // set wavelength info in resampled library
        pWavelengths->applyToDynamicObject(pLib->getMetadata());
        FactoryResource<Units> libUnits;
        libUnits->setUnitType(mLibraryUnitType);
        libUnits->setUnitName(StringUtilities::toDisplayString<UnitType>(mLibraryUnitType));
        pLibDesc->setUnits(libUnits.get());
    }

    pLib->attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &SpectralLibraryManager::resampledElementDeleted));
    mLibraries[pRaster] = pLib;
    mResampledSignatures[pLib] = resampledSignatures;

    const_cast<RasterElement*>(pRaster)->attach(SIGNAL_NAME(Subject, Deleted),
            Slot(this, &SpectralLibraryManager::elementDeleted));

    return true;
}
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;
   
}
Exemple #10
0
bool EdgeDetector::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Edge Detector", "app", "37C57772-DD49-4532-8BC6-9CFB8587D0C9");
   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() +
      "_Edge_Detect_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;
   EdgeRatioThresholdDlg dlg(pDesktop->getMainWidget(), SMALL_WINDOW_THRESHOLD, MEDIAN_WINDOW_THRESHOLD, LARGE_WINDOW_THRESHOLD);
   int stat = dlg.exec();
   if (stat == QDialog::Accepted)
   {
      for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("Edge detect ", row * 100 / pDesc->getRowCount(), 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;
         }
         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;
         }
         for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
         {
            switchOnEncoding(ResultType, EdgeDetectSAR, pDestAcc->getColumn(), pSrcAcc, row, col,
                             pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), 
			                 dlg.getSmallThreshold(), dlg.getMedianThreshold(), dlg.getLargeThreshold());
            pDestAcc->nextColumn();
         }

         pDestAcc->nextRow();
      }

      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("Edge detect compete.", 100, NORMAL);
      }

      pOutArgList->setPlugInArgValue("Edge detect result", pResultCube.release());

      pStep->finalize();
   }
   return true;
}
bool bilinear_bayer::execute(PlugInArgList * pInArgList,
							 PlugInArgList * pOutArgList)
{


	StepResource pStep("bilinear_bayer", "pratik",
					   "27170298-10CE-4E6C-AD7A-97E8058C29FF");
	if (pInArgList == NULL || pOutArgList == NULL)
	{
		return false;
	}

	Progress *pProgress =
		pInArgList->getPlugInArgValue < Progress > (Executable::ProgressArg());

	RasterElement *pCube = pInArgList->getPlugInArgValue < RasterElement > (Executable::DataElementArg());	// pCube

	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;
	}

	pProgress->updateProgress("Starting calculations", 10, NORMAL);
	RasterDataDescriptor *pDesc =
		static_cast < RasterDataDescriptor * >(pCube->getDataDescriptor());
	VERIFY(pDesc != NULL);


	std::string msg = "De-bayerize by bilinear interpolation \n";
	pProgress->updateProgress(msg, 20, NORMAL);	// show initial R,G and B
												// values

	RasterElement *dRas =
		RasterUtilities::createRasterElement(pCube->getName() + "RGB",
											 pDesc->getRowCount(),
											 pDesc->getColumnCount(), 3,
											 pDesc->getDataType(), BSQ);

	// request

	pProgress->updateProgress(msg, 50, NORMAL);

	copyImage(pCube, dRas, 0, pProgress);
	pProgress->updateProgress(msg + "RED complete", 60, NORMAL);

	copyImage(pCube, dRas, 1, pProgress);
	pProgress->updateProgress(msg + "GREEN complete", 70, NORMAL);

	copyImage(pCube, dRas, 2, pProgress);
	pProgress->updateProgress(msg + "BLUE complete", 80, NORMAL);



	// new model resource
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRas->getDataDescriptor());
	rDesc->setDisplayMode(RGB_MODE);	// enable color mode
	rDesc->setDisplayBand(RED, rDesc->getActiveBand(0));
	rDesc->setDisplayBand(GREEN, rDesc->getActiveBand(1));
	rDesc->setDisplayBand(BLUE, rDesc->getActiveBand(2));
	ModelResource < RasterElement > pResultCube(dRas);


	pProgress->updateProgress("Final", 100, NORMAL);

	// create window

	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());

	}
	pOutArgList->setPlugInArgValue("bilinear_bayer_Result", pResultCube.release());	// for 
																					// saving 
																					// data

	pStep->finalize();
	return true;
}
bool adaptive_median::execute(PlugInArgList * pInArgList,
							  PlugInArgList * pOutArgList)
{
	StepResource pStep("adap_median", "noise",
					   "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD55");
	if (pInArgList == NULL || pOutArgList == NULL)
	{
		return false;
	}

	std::string msg = "Noise Reduction by Adaptive Median Filter ";
	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);
	if (pDesc->getDataType() == INT4SCOMPLEX
		|| pDesc->getDataType() == FLT8COMPLEX)
	{
		std::string msg =
			"Noise Reduction cannot be performed on complex types.";
		pStep->finalize(Message::Failure, msg);
		if (pProgress != NULL)
		{
			pProgress->updateProgress(msg, 0, ERRORS);
		}
		return false;
	}

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

	RasterElement *dRas =
		RasterUtilities::createRasterElement(pCube->getName() +
											 "Noise_reduction_Median_filter",
											 pDesc->getRowCount(),
											 pDesc->getColumnCount(), 3,
											 pDesc->getDataType(), BSQ);

	pProgress->updateProgress(msg, 50, NORMAL);

	copyImage4(pCube, dRas, 0, pProgress);
	pProgress->updateProgress(msg + "RED complete", 60, NORMAL);

	copyImage4(pCube, dRas, 1, pProgress);
	pProgress->updateProgress(msg + "GREEN complete", 70, NORMAL);

	copyImage4(pCube, dRas, 2, pProgress);
	pProgress->updateProgress(msg + "BLUE complete", 80, NORMAL);

	// new model resource
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRas->getDataDescriptor());
	rDesc->setDisplayMode(RGB_MODE);	// enable color mode
	rDesc->setDisplayBand(RED, rDesc->getActiveBand(0));
	rDesc->setDisplayBand(GREEN, rDesc->getActiveBand(1));
	rDesc->setDisplayBand(BLUE, rDesc->getActiveBand(2));

	ModelResource < RasterElement > pResultCube(dRas);

	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;
	}

	pProgress->updateProgress("Final", 100, NORMAL);

	pProgress->updateProgress(msg, 100, NORMAL);

	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("adaptive_median is compete.", 100, NORMAL);
	}

	pOutArgList->setPlugInArgValue("adaptive_median_Result", pResultCube.release());	// saving 
																						// data

	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 Segmentation::Ransac_for_buildings(float dem_spacing, double ransac_threshold, cv::Mat original_tiles_merged)
{   
	StepResource pStep("Computing RANSAC on all the identified buildings", "app", "a2beb9b8-218e-11e4-969b-b2227cce2b54");
	   
	ProgressResource pResource("ProgressBar");
	Progress *pProgress = pResource.get(); 
	pProgress-> setSettingAutoClose(true);
	pProgress->updateProgress("Computing RANSAC on all buildings", 0, NORMAL);
	Ransac_buildings = Ransac(Segmentation::path);
	cv::Mat roof_image = cv::Mat::zeros(original_tiles_merged.size(), CV_8UC3);
		
	buildingS.resize(blobs.size());
	buildingS_inliers.resize(blobs.size());
	buildingS_outliers.resize(blobs.size());
	buildingS_plane_coefficients.resize(blobs.size());
	buldingS_number_inliers.resize(blobs.size());

	std::ofstream building_file;
	std::ofstream cont_file;
	cont_file.open (std::string(path) + "/Results/Number_of_RANSAC_applications.txt"); 
	for(int i = 0; i < blobs.size(); i++)
	{// i index is the building (blob) index
		pProgress->updateProgress("Computing RANSAC on all buildings\nBuilding "+ StringUtilities::toDisplayString(i) + " on "+ StringUtilities::toDisplayString(blobs.size()), static_cast<double>(static_cast<double>(i)/blobs.size()*100), NORMAL);
		building_file.open (std::string(path) + "/Results/Building_" + StringUtilities::toDisplayString(i)+".txt");
		building_file << 'i' << '\t' << 'j' << '\t' << 'X' << '\t' << 'Y' << '\t' << 'Z' << '\n'; 
		buildingS[i].setConstant(blobs[i].size(), 3, 0.0);
		
		// the j loop retrieves the  X, Y, Z coordinate for each pixel of all the buildings
		for(int j = 0; j < blobs[i].size(); j++) 
		{// j index is the pixel index for the single building
		 // loop on all the pixel of the SINGLE building
		    int pixel_column = blobs[i][j].x;
            int pixel_row = blobs[i][j].y;			

			double x_building =  pixel_column * dem_spacing;// xMin + pixel_column * dem_spacing // object coordinate 
			double y_building =  pixel_row * dem_spacing;// yMin + pixel_row * dem_spacing // object coordinate
			double z_building = original_tiles_merged.at<float>(pixel_row, pixel_column);//object coordinate
			
			buildingS[i](j,0) = x_building;
			buildingS[i](j,1) = y_building;
			buildingS[i](j,2) = z_building;
			 
			building_file << pixel_row+1 <<  '\t' << pixel_column+1 <<  '\t' << buildingS[i](j,0) << '\t' << buildingS[i](j,1) << '\t' << buildingS[i](j,2) << '\n'; //+1 on the imae coordinates to verify with opticks' rasters (origin is 1,1)
		}

		building_file.close();

		std::ofstream inliers_file;
		std::ofstream parameters_file;
		inliers_file.open (std::string(path) + "/Results/Inliers_building_" + StringUtilities::toDisplayString(i)+".txt");
		parameters_file.open (std::string(path) + "/Results/plane_parameters_building_" + StringUtilities::toDisplayString(i)+".txt");
		//parameters_file << "a\tb\tc\td\tmean_dist\tstd_dist\n";
		int cont = 0;
		Ransac_buildings.ransac_msg += "\n____________Building number " + StringUtilities::toDisplayString(i) +"____________\n";
		Ransac_buildings.ransac_msg += "\nITERATION NUMBER " + StringUtilities::toDisplayString(cont) +"\n";
		Ransac_buildings.ComputeModel(buildingS[i], ransac_threshold);
		
		buldingS_number_inliers[i]= Ransac_buildings.n_best_inliers_count;
		buildingS_inliers[i] = Ransac_buildings.final_inliers;
		buildingS_outliers[i] = Ransac_buildings.final_outliers;
		buildingS_plane_coefficients[i] = Ransac_buildings.final_model_coefficients;
		double inliers_percentage = static_cast<double>( (Ransac_buildings.n_best_inliers_count) ) / static_cast<double> (buildingS[i].rows());
		int inliers_so_far = Ransac_buildings.n_best_inliers_count;
		std::vector<int> old_final_outliers = Ransac_buildings.final_outliers;
		 

		// DRAWS THE ROOFS yellow
		for (int k = 0; k < Ransac_buildings.n_best_inliers_count; k++)
		{
			int pixel_row = static_cast<int>(buildingS[i](Ransac_buildings.final_inliers[k], 1) /  dem_spacing);
            int pixel_column = static_cast<int>(buildingS[i](Ransac_buildings.final_inliers[k], 0) /  dem_spacing);

			unsigned char r = 255;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
            unsigned char g = 255;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
            unsigned char b = 0;//unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
		
			roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[0] = b;
            roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[1] = g;
            roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[2] = r;
		}

		while (inliers_percentage < 0.90)
		{
			cont ++;
			Ransac_buildings.ransac_msg += "\nITERATION NUMBER " + StringUtilities::toDisplayString(cont) +"\n";
			Eigen::Matrix<double,  Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> building_outliers;
			building_outliers.setConstant(buildingS[i].rows() - inliers_so_far, 3, 0.0);
			
		   	//* forse il metodo va già bene così, perchè riempio la matrice deglio outlier in maniera ordinata,
			//* solo che gli indici degli inlier/outlier non sono più indicativi rispetto alla matrice di building originale, ma rispetto alla matrice di innput
			//* devo riporatre gli ID degli indici alla loro posizione originale
			for (int w = 0; w <building_outliers.rows(); w++)
			{
				building_outliers(w, 0) = buildingS[i](old_final_outliers[w], 0);
			    building_outliers(w, 1) = buildingS[i](old_final_outliers[w], 1);
			    building_outliers(w, 2) = buildingS[i](old_final_outliers[w], 2);
				
				//Ransac_buildings.ransac_msg += "\n" + StringUtilities::toDisplayString(pixel_row+1) + "\t" + StringUtilities::toDisplayString(pixel_column+1) + "\t" + StringUtilities::toDisplayString(final_outliers[w]) + "\t" + StringUtilities::toDisplayString(building_outliers(w, 0))+ "\t"+ StringUtilities::toDisplayString(building_outliers(w, 1)) + "\t" + StringUtilities::toDisplayString(building_outliers(w, 2))+"\n"; // needed for tesing (test passed at first iteration)
			}
			

			Ransac_buildings.ransac_msg += "\n";
			//Ransac_buildings.ransac_msg += "\nprova "+ StringUtilities::toDisplayString(inliers_percentage*100)+"\n";
			Ransac_buildings.ComputeModel(building_outliers, ransac_threshold);
			//inliers_percentage = inliers_percentage + static_cast<double>( (n_best_inliers_count) ) / static_cast<double> (building_outliers.rows());
			inliers_percentage = inliers_percentage + static_cast<double>( (Ransac_buildings.n_best_inliers_count) ) / static_cast<double> (buildingS[i].rows());

			Ransac_buildings.ransac_msg += "\nINLIERS IN RELATION TO GLOBAL INDEX ("+ StringUtilities::toDisplayString(Ransac_buildings.n_best_inliers_count) + ")\n";
	        for(size_t i = 0; i < Ransac_buildings.n_best_inliers_count; i++)
	        {
		       Ransac_buildings.ransac_msg +=  StringUtilities::toDisplayString(old_final_outliers[Ransac_buildings.final_inliers[i]])+" ";
			   inliers_file << old_final_outliers[Ransac_buildings.final_inliers[i]] << "\t";
	        }
			Ransac_buildings.ransac_msg += "\n";
			inliers_file << "\n";

			//old_final_outliers.resize(building_outliers.rows() - Ransac_buildings.n_best_inliers_count);
			Ransac_buildings.ransac_msg += "\nOUTLIERS IN RELATION TO GLOBAL INDEX("+ StringUtilities::toDisplayString(building_outliers.rows() - Ransac_buildings.n_best_inliers_count) + ")\n";
			for(size_t i = 0; i < building_outliers.rows() - Ransac_buildings.n_best_inliers_count; i++)
			{
				Ransac_buildings.ransac_msg +=  StringUtilities::toDisplayString(old_final_outliers[Ransac_buildings.final_outliers[i]])+" ";
				old_final_outliers[i] = old_final_outliers[Ransac_buildings.final_outliers[i]];// in this way I refer the outliers indexes to the global indexes (those referred to the original eigen matrix)
			}
			
			//parameters_file << Ransac_buildings.final_model_coefficients[0] << "\t" << Ransac_buildings.final_model_coefficients[1] << "\t" << Ransac_buildings.final_model_coefficients[2] << "\t" << Ransac_buildings.final_model_coefficients[3] << "\t" << Ransac_buildings.mean_distances << "\t"<< Ransac_buildings.std_distances << "\n";
			parameters_file << Ransac_buildings.final_model_coefficients[0] << "\t" << Ransac_buildings.final_model_coefficients[1] << "\t" << Ransac_buildings.final_model_coefficients[2] << "\t" << Ransac_buildings.final_model_coefficients[3] << "\n";


			if (cont == 1)
			{
				// DRAWS THE ROOFS blue
			   for (int k = 0; k < Ransac_buildings.n_best_inliers_count; k++)
			   {
					int pixel_row = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 1) /  dem_spacing);
					int pixel_column = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 0) /  dem_spacing);

					unsigned char r = 0;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char g = 0;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char b = 255;//unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
		
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[0] = b;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[1] = g;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[2] = r;
				}
			}

			if (cont ==2)
			{
				// DRAWS THE ROOFS green
			   for (int k = 0; k < Ransac_buildings.n_best_inliers_count; k++)
			   {
					int pixel_row = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 1) /  dem_spacing);
					int pixel_column = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 0) /  dem_spacing);

					unsigned char r = 0;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char g = 255;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char b = 0;//unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
		
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[0] = b;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[1] = g;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[2] = r;
				}
			}

			if (cont ==3)
			{
				// DRAWS THE ROOFS brown
			   for (int k = 0; k < Ransac_buildings.n_best_inliers_count; k++)
			   {
					int pixel_row = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 1) /  dem_spacing);
					int pixel_column = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 0) /  dem_spacing);

					unsigned char r = 128;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char g = 0;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
					unsigned char b = 0;//unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
		
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[0] = b;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[1] = g;
					roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[2] = r;
				}
			}

			//if (cont == 4)
			//{
			//	// DRAWS THE ROOFS white
			//   for (int k = 0; k < Ransac_buildings.n_best_inliers_count; k++)
			//   {
			//		int pixel_row = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 1) /  dem_spacing);
			//		int pixel_column = static_cast<int>(buildingS[i](old_final_outliers[Ransac_buildings.final_inliers[k]], 0) /  dem_spacing);

			//		unsigned char r = 255;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
			//		unsigned char g = 255;// unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
			//		unsigned char b = 255;//unsigned char(255 * (rand()/(1.0 + RAND_MAX)));
		
			//		roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[0] = b;
			//		roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[1] = g;
			//		roof_image.at<cv::Vec3b>(pixel_row, pixel_column)[2] = r;
			//	}
			//}


			Ransac_buildings.ransac_msg += "\n"; 
			inliers_so_far += Ransac_buildings.n_best_inliers_count;  
			
		    
		}// fine while
		Ransac_buildings.ransac_msg += "__________________________________________________________________\n";
		//boh_file.close();

		cont_file << i << "\t" << cont << "\n";
	}
	building_file.close();
	cont_file.close();
	cv::imshow("roofs", roof_image);
	
	cv::imwrite(path + "/Results/building_roofs.png", roof_image);
	cv::waitKey(0);
	
	pProgress->updateProgress("All buildings have been processed with RANSAC.", 100, NORMAL);
    pStep->finalize();
	return true;
}
bool conservative_filter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Conservative", "Filter", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD55"); //what is this?
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }

   Service <DesktopServices> pDesktop;
   conservative_filter_ui dialog(pDesktop->getMainWidget());
   int status = dialog.exec();
   if (status == QDialog::Accepted)
   {
	   int radius = dialog.getRadiusValue();

   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);

   if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX)
   {
      std::string msg = "Conservative Filter cannot be performed on complex types.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Conservative_Filter_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());

   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Applying Conservative Filter", row * 100 / pDesc->getRowCount(), 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;
      }
      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;
      }
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), verifyRange, pDestAcc->getColumn(), pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), radius);
         pDestAcc->nextColumn();
      }
      pDestAcc->nextRow();
   }

   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("COnservative Filter is complete", 100, NORMAL);
   }

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

   pStep->finalize();
   }
   return true;
}
bool pagauss::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Tutorial 5", "app", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD54");
   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);
   if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX)
   {
      std::string msg = "Edge detection cannot be performed on complex types.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }

   


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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Edge_Detection_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());
   

   for (long signed int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Calculating result", row * 100 / pDesc->getRowCount(), 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;
      }
      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;
      }
      for (long signed int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), gauss, pDestAcc->getColumn(), pSrcAcc, row, col,
            pDesc->getRowCount(), pDesc->getColumnCount());
         pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
   }

   

   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("pagauss is compete.", 100, NORMAL);
   }

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

   pStep->finalize();
   return true;
}
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Interpolation::generate_DEM(PointCloudElement* pElement, float post_spacing) 
{
	   StepResource pStep("Generating DEM", "app", "ffe16048-1e58-11e4-b4be-b2227cce2b54");
	   
	   ProgressResource pResource("ProgressBar");
	   Progress *pProgress = pResource.get(); 
	   pProgress-> setSettingAutoClose(true);

	   Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> demRM;// dem stored in a Row major eigen matrix

	   /* Main processing loop */
	   FactoryResource<PointCloudDataRequest> req;
	   req->setWritable(true);
	   PointCloudAccessor acc(pElement->getPointCloudAccessor(req.release()));
	   if (!acc.isValid())
	   {
		   interpolation_msg += "Unable to write to point cloud for generating DEM.\n";
		   pProgress->updateProgress("Unable to write to point cloud for generating DEM.", 0, ERRORS);
		   pStep->finalize(Message::Abort, interpolation_msg);
		   return demRM.matrix(); // in this way it should return NULL matrix, see http://eigen.tuxfamily.org/dox/classEigen_1_1Matrix.html: Matrix(): For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix is called a null matrix. This constructor is the unique way to create null matrices: resizing a matrix to 0 is not supported.
	   }
	   const PointCloudDataDescriptor* pDesc = static_cast<const PointCloudDataDescriptor*>(pElement->getDataDescriptor());
	   double xMin = pDesc->getXMin() * pDesc->getXScale() + pDesc->getXOffset();
	   double xMax = pDesc->getXMax() * pDesc->getXScale() + pDesc->getXOffset();
	   double yMin = pDesc->getYMin() * pDesc->getYScale() + pDesc->getYOffset();
	   double yMax = pDesc->getYMax() * pDesc->getYScale() + pDesc->getYOffset();

	   int mDim = static_cast<int>(std::ceil((xMax - xMin) / post_spacing));  //columns
	   int nDim = static_cast<int>(std::ceil((yMax - yMin) / post_spacing)); //rows
	   xMax = xMin + mDim * post_spacing;
	   yMin = yMax - nDim * post_spacing;

	   const float badVal = -9999.f;
	   demRM.setConstant(nDim, mDim, badVal);

	   int prog = 0;
	   uint32_t adv = pDesc->getPointCount() / 100;
	   for (size_t idx = 0; idx < pDesc->getPointCount(); ++idx)
	   {
		  if (!acc.isValid())
		  {
			  interpolation_msg += "Unable to access data for generating DEM.\n";
			  pProgress->updateProgress("Unable to access data for generating DEM.", 0, ERRORS);
			  pStep->finalize(Message::Abort, interpolation_msg);
			  return demRM.matrix();// in this way it should return NULL matrix, see http://eigen.tuxfamily.org/dox/classEigen_1_1Matrix.html: Matrix(): For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix is called a null matrix. This constructor is the unique way to create null matrices: resizing a matrix to 0 is not supported.
		  }
		  if (idx % adv == 0)
		  {
			  pProgress->updateProgress("Generating DEM", ++prog, NORMAL);
		  }
		  if (!acc->isPointValid())
		  {
			 acc->nextValidPoint();
			 continue;
		  }
		  double x = acc->getXAsDouble(true);
		  double y = acc->getYAsDouble(true);
		  float z = static_cast<float>(acc->getZAsDouble(true));
		  
		  // calculate nearest DEM point
		  int xIndex = std::max(0, static_cast<int>(std::floor((x - xMin) / post_spacing)));
		  int yIndex = std::max(0, static_cast<int>(std::floor((yMax - y) / post_spacing)));
		  
		  float demVal = demRM(yIndex, xIndex);
		  if (demVal == badVal || demVal < z)
		  {
			 demRM(yIndex, xIndex) = z; 
		  }

		  acc->nextValidPoint();
	   }
	   pProgress->updateProgress("DEM generation is complete.", 100, NORMAL);
	   pStep->finalize();
	   return demRM;
}
Exemple #18
0
bool Tutorial3::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Tutorial 3", "app", "27170298-10CE-4E6C-AD7A-97E8058C29FF");
   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;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());
   double min = std::numeric_limits<double>::max();
   double max = -min;
   double total = 0.0;
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++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 (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), updateStatistics, pAcc->getColumn(), min, max, total);
         pAcc->nextColumn();
      }
      pAcc->nextRow();
   }
   unsigned int count = pDesc->getColumnCount() * pDesc->getRowCount();
   double mean = total / count;

   if (pProgress != NULL)
   {
      std::string msg = "Minimum value: " + StringUtilities::toDisplayString(min) + "\n"
                      + "Maximum value: " + StringUtilities::toDisplayString(max) + "\n"
                      + "Number of pixels: " + StringUtilities::toDisplayString(count) + "\n"
                      + "Average: " + StringUtilities::toDisplayString(mean);
      pProgress->updateProgress(msg, 100, NORMAL);
   }
   pStep->addProperty("Minimum", min);
   pStep->addProperty("Maximum", max);
   pStep->addProperty("Count", count);
   pStep->addProperty("Mean", mean);
   
   pOutArgList->setPlugInArgValue("Minimum", &min);
   pOutArgList->setPlugInArgValue("Maximum", &max);
   pOutArgList->setPlugInArgValue("Count", &count);
   pOutArgList->setPlugInArgValue("Mean", &mean);

   pStep->finalize();
   return true;
}
bool SampleGeoref::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
    // Do any kind of setup we need before converting coordinates.
    // In this case, get our X and Y factors.

    StepResource pStep("Run Sample Georef", "app", "CFCB8AA9-D504-42e9-86F0-547DF9B4798A");
    Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());

    FAIL_IF(!isBatch(), "Interactive mode is not supported.", return false);

    // Default values
    bool animated = false;

    // get factors from pInArgList
    pInArgList->getPlugInArgValue("XSize", mXSize);
    pInArgList->getPlugInArgValue("YSize", mYSize);
    pInArgList->getPlugInArgValue("Extrapolate", mExtrapolate);
    pInArgList->getPlugInArgValue("Animated", animated);
    pInArgList->getPlugInArgValue("Rotate", mRotate);

    View* pView = pInArgList->getPlugInArgValue<View>(Executable::ViewArg());
    mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
    FAIL_IF(mpRaster == NULL, "Could not find raster element", return false);

    if (mpGui != NULL)
    {
        mXSize = mpGui->getXSize();
        mYSize = mpGui->getYSize();
        animated = mpGui->getAnimated();
        mRotate = mpGui->getRotate();
        mExtrapolate = mpGui->getExtrapolate();
    }

    if (animated)
    {
        SpatialDataView* pSpatialView = dynamic_cast<SpatialDataView*>(pView);
        FAIL_IF(pSpatialView == NULL, "Could not find spatial data view.", return false);

        LayerList* pLayerList = pSpatialView->getLayerList();
        FAIL_IF(pLayerList == NULL, "Could not find layer list.", return false);

        RasterLayer* pLayer = dynamic_cast<RasterLayer*>(pLayerList->getLayer(RASTER, mpRaster));
        FAIL_IF(pLayer == NULL, "Could not find raster layer", return false);

        Animation* pAnim = pLayer->getAnimation();
        FAIL_IF(pAnim == NULL, "Could not find animation", return false);

        const std::vector<AnimationFrame>& frames = pAnim->getFrames();
        FAIL_IF(frames.empty(), "No frames in animation.", return false);

        mpAnimation.reset(pAnim);
        mFrames = frames.size();
        mCurrentFrame = 0;
    }

    RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor());
    FAIL_IF(pDescriptor == NULL, "Could not get data descriptor.", return false);

    unsigned int rows = pDescriptor->getRowCount();
    unsigned int cols = pDescriptor->getColumnCount();
    unsigned int bands = pDescriptor->getBandCount();

    mXScale = static_cast<double>(mXSize) / rows;
    mYScale = static_cast<double>(mYSize) / cols;

    mpRaster->setGeoreferencePlugin(this);

    mpGui = NULL; // Pointer not guaranteed to be valid after execute() is called
    return true;
}
bool LocalSharpening::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Local Sharpening", "app", "08BB9B79-5D24-4AB0-9F35-92DE77CED8E7");
   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() +
      "_Local_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;
   LocalSharpeningDlg dlg(pDesktop->getMainWidget());
   int stat = dlg.exec();
   if (stat != QDialog::Accepted)
   {
	   return true;
   }
   double contrastVal = dlg.getContrastValue();
   int nFilterType = dlg.getCurrentFilterType();
   int windowSize = dlg.getCurrentWindowSize();
   windowSize = (windowSize-1)/2;

   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Local sharpening", row * 100 / pDesc->getRowCount(), 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;
      }
      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;
      }
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
		  if (nFilterType == 0)
		  {
			  switchOnEncoding(ResultType, localAdaptiveSharpening, pDestAcc->getColumn(), pSrcAcc, row, col,
                               pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, contrastVal);
		  }
		  else
		  {
           
			  switchOnEncoding(ResultType, localExtremeSharpening, pDestAcc->getColumn(), pSrcAcc, row, col,
                               pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize);
		  }
		  pDestAcc->nextColumn();
      }

      pDestAcc->nextRow();
   }


   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("Local sharpening is compete.", 100, NORMAL);
   }

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

   pStep->finalize();


   return true;
}
Exemple #21
0
bool MetadataExporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Progress* pProgress = NULL;
   FileDescriptor* pFileDescriptor = NULL;
   DataElement* pElement = NULL;

   StepResource pStep("Export metadata", "app", "{08701b89-565c-4e0a-92ef-9bf22395f902}");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "{5e921da0-6470-44f1-a910-ed12af1e5ebc}");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));

      pFileDescriptor = pInArgList->getPlugInArgValue<FileDescriptor>(Exporter::ExportDescriptorArg());
      if (pFileDescriptor == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No file specified", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No file specified");
         return false;
      }
      pMsg->addProperty("Destination", pFileDescriptor->getFilename());

      pElement = pInArgList->getPlugInArgValue<DataElement>(Exporter::ExportItemArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element specified", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element specified");
         return false;
      }
      pMsg->addProperty("Name", pElement->getName());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Open output file", 10, NORMAL);
   }
   FILE* pFile = fopen(pFileDescriptor->getFilename().getFullPathAndName().c_str(), "w");
   if (pFile == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("File can not be created", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "File can not be created");
      return false;
   }

   const DynamicObject* pMetadata = pElement->getMetadata();
   VERIFY(pMetadata);
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Save metadata", 20, NORMAL);
   }
   if (pMetadata->getNumAttributes() == 0)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Metadata is empty. A file will be created anyway.", 20, WARNING);
      }
      pStep->addMessage("Metadata is empty. A file will be created anyway.", "app", "{29274eb3-c899-4778-ae1e-d267ea0dd346}", true);
   }
   XMLWriter xml("Metadata", Service<MessageLogMgr>()->getLog());
   xml.pushAddPoint(NULL);
   if (!pMetadata->toXml(&xml))
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Error saving metadata", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Error saving metadata");
      return false;
   }
   xml.popAddPoint();
   xml.writeToFile(pFile);
   fclose(pFile);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Finished saving the metadata", 100, NORMAL);
   }
   pStep->finalize(Message::Success);
   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;
}
Exemple #23
0
bool SampleGeoref::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   // Do any kind of setup we need before converting coordinates.
   // In this case, get our X and Y factors.

   StepResource pStep("Run Sample Georef", "app", "CFCB8AA9-D504-42e9-86F0-547DF9B4798A");
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());

   FAIL_IF(!isBatch(), "Interactive mode is not supported.", return false);

   mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   FAIL_IF(mpRaster == NULL, "Could not find the raster element", return false);

   // Get the values from the input args
   bool xSizeArgSet = pInArgList->getPlugInArgValue("XSize", mXSize);
   bool ySizeArgSet = pInArgList->getPlugInArgValue("YSize", mYSize);
   bool extrapolateArgSet = pInArgList->getPlugInArgValue("Extrapolate", mExtrapolate);

   // If the arg values are not set, get the values from the georeference descriptor;
   // otherwise update the georeference descriptor with the arg values
   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor());
   FAIL_IF(pDescriptor == NULL, "Could not get the data descriptor.", return false);

   GeoreferenceDescriptor* pGeorefDescriptor = pDescriptor->getGeoreferenceDescriptor();
   if (pGeorefDescriptor != NULL)
   {
      if (xSizeArgSet == false)
      {
         mXSize = dv_cast<int>(pGeorefDescriptor->getAttributeByPath("SampleGeoref/XSize"), mXSize);
      }

      if (ySizeArgSet == false)
      {
         mYSize = dv_cast<int>(pGeorefDescriptor->getAttributeByPath("SampleGeoref/YSize"), mYSize);
      }

      if (extrapolateArgSet == false)
      {
         mExtrapolate = dv_cast<bool>(pGeorefDescriptor->getAttributeByPath("SampleGeoref/Extrapolate"), mExtrapolate);
      }
   }

   // Calculate the scale for the georeference
   unsigned int rows = pDescriptor->getRowCount();
   unsigned int cols = pDescriptor->getColumnCount();

   mXScale = static_cast<double>(mXSize) / rows;
   mYScale = static_cast<double>(mYSize) / cols;

   // Set the georeference plug-in into the raster element
   mpRaster->setGeoreferencePlugin(this);

   // Update the georeference descriptor with the current georeference parameters if necessary
   if (pGeorefDescriptor != NULL)
   {
      // Georeference plug-in
      const std::string& plugInName = getName();
      pGeorefDescriptor->setGeoreferencePlugInName(plugInName);

      // X-size
      if (xSizeArgSet == true)
      {
         pGeorefDescriptor->setAttributeByPath("SampleGeoref/XSize", mXSize);
      }

      // Y-size
      if (ySizeArgSet == true)
      {
         pGeorefDescriptor->setAttributeByPath("SampleGeoref/YSize", mYSize);
      }

      // Extrapolate
      if (extrapolateArgSet == true)
      {
         pGeorefDescriptor->setAttributeByPath("SampleGeoref/Extrapolate", mExtrapolate);
      }
   }

   pStep->finalize(Message::Success);
   return true;
}
Exemple #24
0
bool GetSessionItemBase<T>::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "{234E6866-C61D-4ca8-9152-8CA3DCEFC3C0}");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      reportError("Invalid arguments.", "{0012BA62-EE8E-451e-B725-26D7335436AC}");
      return false;
   }

   if (extractInputArgs(pInArgList) == false)
   {
      reportError("Unable to extract input arguments.", "{365B8383-651C-421f-87D4-01238F4E3398}");
      return false;
   }

   // Create the dialog.
   QDialog dialog(Service<DesktopServices>()->getMainWidget());

   // Tree view containing available session items.
   QStringList columnNames;
   columnNames << "Name" << "Type";

   QTreeWidget* pTree = new QTreeWidget(&dialog);
   pTree->setColumnCount(columnNames.count());
   pTree->setHeaderLabels(columnNames);

   std::auto_ptr<QTreeWidgetItem> pRoot(new QTreeWidgetItem);
   pRoot->setFlags(Qt::NoItemFlags);
   pRoot->setText(GetSessionItemBase<T>::NameColumn, "No items available");
   pRoot->setData(GetSessionItemBase<T>::NameColumn,
      GetSessionItemBase<T>::SessionItemRole, QVariant::fromValue<void*>(NULL));
   populateTreeWidgetItem(pRoot.get());

   if (pRoot->childCount() > 0)
   {
      pTree->addTopLevelItems(pRoot->takeChildren());
   }
   else
   {
      pTree->addTopLevelItem(pRoot.release());
   }

   pTree->expandAll();
   pTree->resizeColumnToContents(0);

   // Buttons.
   QFrame* pLine = new QFrame(&dialog);
   pLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);
   QDialogButtonBox* pButtonBox = new QDialogButtonBox(
      QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);

   // Layout.
   QVBoxLayout* pLayout = new QVBoxLayout(&dialog);
   pLayout->setMargin(10);
   pLayout->setSpacing(10);
   pLayout->addWidget(pTree);
   pLayout->addWidget(pLine);
   pLayout->addWidget(pButtonBox);
   dialog.setWindowTitle(QString::fromStdString(mDialogCaption));
   dialog.resize(400, 400);

   // Connections.
   VERIFY(QObject::connect(pButtonBox, SIGNAL(accepted()), &dialog, SLOT(accept())));
   VERIFY(QObject::connect(pButtonBox, SIGNAL(rejected()), &dialog, SLOT(reject())));
   if (dialog.exec() != QDialog::Accepted)
   {
      reportError("User cancelled.", "{27E33A95-0DFB-486b-ABAE-BFC849418201}");
      return false;
   }

   QTreeWidgetItem* pItem = pTree->currentItem();
   if (pItem == NULL)
   {
      reportError("No item selected.", "{27B21666-19BB-4932-BF08-A81E340F1A54}");
      return false;
   }

   QVariant value = pItem->data(GetSessionItemBase<T>::NameColumn, GetSessionItemBase<T>::SessionItemRole);
   SessionItem* pSessionItem = reinterpret_cast<SessionItem*>(value.value<void*>());
   mpSessionItem = dynamic_cast<T*>(pSessionItem);
   if (mpSessionItem == NULL)
   {
      reportError("Wrong item type selected.", "{E6D3E131-4E71-4989-9D34-BC9A1157AB8E}");
      return false;
   }

   if (populateOutputArgs(pOutArgList) == false)
   {
      reportError("Unable to populate the output argument list.", "{C3AB6771-50C4-4091-BA39-3D44C82C93A8}");
      return false;
   }

   reportComplete();
   return true;
}
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;
}
bool ImageRegistration::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Image Registration", "app", "A2E0FC44-2A31-41EE-90F8-805773D01FCA");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   //RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());

   std::vector<Window*> windows;
   Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
   std::vector<RasterElement*> elements;
   for (unsigned int i = 0; i < windows.size(); ++i)
   {
       SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(windows[i]);
       if (pWindow == NULL)
       {
           continue;
       }
       LayerList* pList = pWindow->getSpatialDataView()->getLayerList();
       elements.push_back(pList->getPrimaryRasterElement());
   }

   RasterElement* pCube = elements[0];
   RasterElement* pCubeRef = elements[1];
   if ((pCube == NULL) || (pCubeRef == 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());

   FactoryResource<DataRequest> pRequestRef;
   pRequestRef->setInterleaveFormat(BSQ);
   DataAccessor pSrcAccRef = pCubeRef->getDataAccessor(pRequestRef.release());

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "_Image_Registration_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;
   }

   std::vector<int> badValues = pDesc->getBadValues();
   //badValues.push_back(0);
   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pResultCube->getDataDescriptor());
   Statistics* pStatistics = pResultCube->getStatistics(pDescriptor->getActiveBand(0));
   pStatistics->setBadValues(badValues);

   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setWritable(true);
   DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release());
   
   nCountMas = 0;
   nCountRef = 0;
   int windowSize = 6;
   double *pBuffer = (double *)calloc(pDesc->getRowCount()*pDesc->getColumnCount(), sizeof(double));

   GetGrayScale(pDesc->getDataType());

   
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
	   if (pProgress != NULL)
       {
           pProgress->updateProgress("Image registration", row * 100 / pDesc->getRowCount(), 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;
       }
       for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
       {
	       locateAllStarPosition(pSrcAcc, pSrcAccRef, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, pBuffer);
       }
   }

   ModifyCenter(pSrcAcc, pDesc->getDataType(), windowSize, nCountMas, nStarPositionsMas);
   ModifyCenter(pSrcAccRef, pDesc->getDataType(), windowSize, nCountRef, nStarPositionsRef);

   GetAllNeighborStars();
   GetMatchingStars();
   
   GetParameters(pDesc->getRowCount(), pDesc->getColumnCount());
  
   DrawStars(pBuffer, pSrcAccRef, pDesc->getDataType(), matrixT, pDesc->getRowCount(), pDesc->getColumnCount());

   //Output the value 
      for (unsigned int m = 0; m < pDesc->getRowCount(); m++)
      {
	      for (unsigned int n = 0; n < pDesc->getColumnCount(); n++)
	      {
		      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 (!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;
               }

				       
			  switchOnEncoding(ResultType, updatePixel, pDestAcc->getColumn(), pBuffer, m, n, pDesc->getRowCount(), pDesc->getColumnCount());       
			  pDestAcc->nextColumn();
				   
		  }
				   
		  pDestAcc->nextRow();
		  
	  }
   free(pBuffer);
   


   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());
   }

   double theta = std::acos(matrixT[0][0])*180.0/3.1415926;

   std::string msg = "Image Registration is complete.\n Translation x = " +  StringUtilities::toDisplayString(round(shiftX)) + ", y = " + 
	                 StringUtilities::toDisplayString(round(shiftY)) + ", rotation = " + StringUtilities::toDisplayString(round(theta)) + " degree";
   if (pProgress != NULL)
   {
	   
       pProgress->updateProgress(msg, 100, NORMAL);
   }

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

   pStep->finalize();


   return true;
}