bool SpectralLibraryManager::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
    mpProgress = Service<PlugInManagerServices>()->getProgress(this);
    if (mpProgress != NULL)
    {
        Service<DesktopServices>()->createProgressDialog(getName(), mpProgress);
    }

    // Create edit library action
    if (isBatch() == false)
    {
        QPixmap pixEditLib(EditSpectralLibraryIcon);
        mpEditSpectralLibraryAction = new QAction(QIcon(pixEditLib),
                "&Edit Spectral Library", this);
        mpEditSpectralLibraryAction->setAutoRepeat(false);
        mpEditSpectralLibraryAction->setStatusTip("Display the editor for adding and removing "
                "signatures used by the Spectral Library Match algorithm plug-ins.");
        VERIFYNR(connect(mpEditSpectralLibraryAction, SIGNAL(triggered()), this, SLOT(editSpectralLibrary())));

        ToolBar* pToolBar = static_cast<ToolBar*>(Service<DesktopServices>()->getWindow("Spectral", TOOLBAR));
        if (pToolBar != NULL)
        {
            pToolBar->addSeparator();
            pToolBar->addButton(mpEditSpectralLibraryAction);
        }
    }

    return true;
}
bool ConnectedComponents::createPseudocolor(unsigned short maxLabel) const
{
   if (isBatch() || mpView == NULL)
   {
      return true;
   }
   if (maxLabel > 50)
   {
      mProgress.report("More than 50 blobs exist, colors will be repeated.", 100, WARNING, true);
   }
   PseudocolorLayer* pOutLayer = static_cast<PseudocolorLayer*>(
      mpView->createLayer(PSEUDOCOLOR, mpLabels));
   VERIFY(pOutLayer);
   pOutLayer->setXOffset(mXOffset);
   pOutLayer->setYOffset(mYOffset);
   if (pOutLayer != NULL)
   {
      std::vector<ColorType> colors;
      std::vector<ColorType> excluded;
      excluded.push_back(ColorType(0, 0, 0));
      excluded.push_back(ColorType(255, 255, 255));
      ColorType::getUniqueColors(std::min<unsigned short>(maxLabel, 50), colors, excluded);
      for (int cl = 1; cl <= maxLabel; ++cl)
      {
         pOutLayer->addInitializedClass(StringUtilities::toDisplayString(cl), cl, colors[(cl - 1) % 50]);
      }
   }
   return true;
}
Example #3
0
bool NormalizeData::displayResult()
{
   if (isBatch())
   {
      return true;
   }
   if (mInput.mpResult == NULL)
   {
      return false;
   }
   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(
      Service<DesktopServices>()->createWindow(mInput.mpResult->getName(), SPATIAL_DATA_WINDOW));
   SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
   if (pView == NULL)
   {
      mProgress.report("Unable to create view.", 0, ERRORS, true);
      return false;
   }
   pView->setPrimaryRasterElement(mInput.mpResult);
   
   UndoLock lock(pView);
   RasterLayer* pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, mInput.mpResult));
   if (pLayer == NULL)
   {
      mProgress.report("Unable to create view.", 0, ERRORS, true);
      return false;
   }

   return true;
}
Example #4
0
bool ChangeUpDirection::getInputSpecification(PlugInArgList*& pInArgList)
{
   pInArgList = Service<PlugInManagerServices>()->getPlugInArgList();
   VERIFY(pInArgList != NULL);
   VERIFY(pInArgList->addArg<Progress>(Executable::ProgressArg(), NULL, Executable::ProgressArgDescription()));
   VERIFY(pInArgList->addArg<RasterElement>(Executable::DataElementArg(), "Element to perform rotation on."));
   bool res = !isBatch();
   VERIFY(pInArgList->addArg<bool>("Display Results", res, "Should a view be created for the results?"));
   if (isBatch())
   {
      VERIFY(pInArgList->addArg<double>("Rotation", "The amount to rotate the data in radians."));
   }
   else
   {
      VERIFY(pInArgList->addArg<SpatialDataView>(Executable::ViewArg(), "View on which the rotation will be performed."));
   }
   return true;
}
Example #5
0
bool VideoImporter::getOutputSpecification(PlugInArgList*& pArgList)
{
   VERIFY((pArgList = Service<PlugInManagerServices>()->getPlugInArgList()) != NULL);
   if (!isBatch())
   {
      VERIFY(pArgList->addArg<SpatialDataView>("View"));
   }
   return true;
}
Example #6
0
bool ChangeUpDirection::getOutputSpecification(PlugInArgList*& pOutArgList)
{
   pOutArgList = Service<PlugInManagerServices>()->getPlugInArgList();
   VERIFY(pOutArgList != NULL);
   VERIFY(pOutArgList->addArg<RasterElement>("Rotated Element", "The new raster element with the rotated data."));
   if (!isBatch())
   {
      VERIFY(pOutArgList->addArg<SpatialDataView>("View", "The newly created view."));
   }
   return true;
}
bool BackgroundSuppressionShell::getInputSpecification(PlugInArgList *&pArgList)
{
   VERIFY(pArgList = Service<PlugInManagerServices>()->getPlugInArgList());
   VERIFY(pArgList->addArg<Progress>(Executable::ProgressArg(), NULL));
   VERIFY(pArgList->addArg<RasterElement>(Executable::DataElementArg()));
   VERIFY(pArgList->addArg<SpatialDataView>(Executable::ViewArg()));
   if(!isBatch())
   {
      VERIFY(pArgList->addArg<Animation>("animation", NULL));
   }
   return true;
}
Example #8
0
SpatialDataView* VideoImporter::createView() const
{
   if ((isBatch()) || (mpRasterElement == NULL))
   {
      return NULL;
   }

   mProgress.report("Creating view...", 85, NORMAL);

   // Get the data set name
   std::string name = mpRasterElement->getName();
   if (name.empty())
   {
      mProgress.report("The data set name is invalid!  A view cannot be created.", 0, ERRORS, true);
      return NULL;
   }

   // Create the spatial data window
   SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(Service<DesktopServices>()->createWindow(name, SPATIAL_DATA_WINDOW));
   SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
   if (pView == NULL)
   {
      mProgress.report("Could not create the view window!", 0, ERRORS, true);
      return NULL;
   }

   // Set the spatial data in the view
   pView->setPrimaryRasterElement(mpRasterElement);

   // Block undo actions when creating the layers
   UndoLock lock(pView);

   // Add the cube layer
   RasterLayer* pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, mpRasterElement));
   if (pLayer == NULL)
   {
      mProgress.report("Could not create the cube layer!", 0, ERRORS, true);
      return NULL;
   }
   pLayer->setStretchUnits(RED, RAW_VALUE);
   pLayer->setStretchUnits(GREEN, RAW_VALUE);
   pLayer->setStretchUnits(BLUE, RAW_VALUE);
   pLayer->setStretchValues(RED, 0, 255);
   pLayer->setStretchValues(GREEN, 0, 255);
   pLayer->setStretchValues(BLUE, 0, 255);
   if (pLayer->isGpuImageSupported())
   {
      pLayer->enableGpuImage(true);
   }
   return pView;
}
Example #9
0
bool AoiLogical::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
    if (pInArgList == NULL || pOutArgList == NULL)
    {
        return false;
    }
    if (!extractInputArgs(pInArgList))
    {
        return false;
    }

    mProgress.report("Begin AOI set operation.", 1, NORMAL);

    if (isBatch())
    {
        mProgress.report("Batch mode is not supported.", 0, ERRORS, true);
        return false;
    }

    FactoryResource<BitMask> pResultMask;
    if (pResultMask.get() == NULL)
    {
        mProgress.report("Unable to create result AOI.", 0, ERRORS, true);
        return false;
    }
    mpResult = pResultMask.get();

    if (mOperation == "Union")
    {
        mpResult->merge(*mpSet1);
        mpResult->merge(*mpSet2);
    }
    else if (mOperation == "Intersection")
    {
        mpResult->merge(*mpSet1);
        mpResult->intersect(*mpSet2);
    }
    else
    {
        mProgress.report("Invalid operation: " + mOperation, 0, ERRORS, true);
        return false;
    }
    if (!displayResult())
    {
        return false;
    }
    mProgress.upALevel();
    return true;
}
bool ResamplerPlugIn::getInputSpecification(PlugInArgList*& pArgList)
{
   pArgList = Service<PlugInManagerServices>()->getPlugInArgList();
   VERIFY(pArgList != NULL);
   VERIFY(pArgList->addArg<Progress>(Executable::ProgressArg(), NULL, Executable::ProgressArgDescription()));
   VERIFY(pArgList->addArg<SpatialDataView>(Executable::ViewArg(), NULL,
      "If the current active view is a spatial data\n"
      "view, the wavelengths from the primary raster\n"
      "element of this view will be used as the default\n"
      "set of wavelengths for the resampling."));

   if (isBatch())
   {
      VERIFY(pArgList->addArg<std::vector<Signature*> >("Signatures to resample", NULL,
         "The signatures to be resampled"));
      VERIFY(pArgList->addArg<Signature>("Signature to resample", NULL,
         "The signature to be resampled. If arg \"Signatures to resample\" is provided, this arg will be ignored."));
      VERIFY(pArgList->addArg<DataElement>("Data element wavelength source", NULL,
         "The signatures will be resampled to the wavelengths from this data element."));
      VERIFY(pArgList->addArg<Filename>("Wavelengths Filename", NULL,
         "The signatures will be resampled to the wavelengths from this wavelengths file.\n This arg will "
         "be ignored if arg \"Data element wavelength source\" is provided"));
      VERIFY(pArgList->addArg<std::string>("Resampling Method", NULL,
         "The name of the resampling method. The accepted values are \n"
         + ResamplerOptions::LinearMethod() + ", " + ResamplerOptions::CubicSplineMethod() + " and "
         + ResamplerOptions::GaussianMethod() + ".\n"));
      VERIFY(pArgList->addArg<double>("Drop out window", NULL,
         "The drop out window to use during resampling.\n"));
      VERIFY(pArgList->addArg<double>("FWHM", NULL,
         "The full width half max to use during gaussian resampling.\n"
         "This arg is ignored for other methods.\n"));
      VERIFY(pArgList->addArg<bool>("Use fill value", NULL,
         "If true, resampled signatures will have values for all the target wavelengths regardless \n"
         "of whether or not the input signatures have spectral coverage for all the wavelengths.\n"
         "Any wavelengths that would normally not be in the resampled signature will be assigned the fill value."));
      VERIFY(pArgList->addArg<double>("Fill value", NULL,
         "The value to be assigned to wavelengths in the resampled signature for which the input signature\n"
         "does not have spectral coverage.\n"
         "This arg is ignored if arg \"Use fill value\" is false."));
   }

   return true;
}
Example #11
0
void loadg4libs() 
{
/// The function to unload Geant4 libraries

  // CLHEP
  gSystem->Load("libCLHEP");
  
  // xerces-c library if GDML is activated
  if ( isSet("G4LIB_BUILD_GDML") ) {
    gSystem->Load("libxerces-c");
  }  

  // Get the string with the list of libraries
  string all_lines;
  GetLinkLine(all_lines);
  
  // Load Geant4 libraries
  cout << "Loading Geant4 libraries (using liblist) ..." << endl;
  HandleLinkLine(all_lines.c_str(),"l");

  // VGM librares
  vgmlibs();
  
  // G4Root library (if available)
  if ( isLibrary("libg4root") ) {
    cout << "Loading g4root library ..." << endl;
    gSystem->Load("libg4root");
  }
    
  // Geant4 VMC library
  cout << "Loading geant4vmc library ..." << endl;
  gSystem->Load("libgeant4vmc");

  // Geant4 VMC GUI library 
  // (if available and Root is not running in batch mode)
  if ( isLibrary("libgeant4vmc_gui") && ! isBatch() ) {
    cout << "Loading geant4vmc_gui library ... " << endl;
    gSystem->Load("libgeant4vmc_gui");
  }  
}
bool SpectralLibraryManager::deserialize(SessionItemDeserializer& deserializer)
{
    if (isBatch() == true)
    {
        setInteractive();
    }

    bool success = execute(NULL, NULL);

    if (success)
    {

        std::vector<Signature*> signatures;
        Service<SessionManager> pSessionManager;
        XmlReader reader(NULL, false);
        DOMElement* pRootElement = deserializer.deserialize(reader, "SpectralLibraryManager");
        for (DOMNode* pChild = pRootElement->getFirstChild(); pChild != NULL; pChild = pChild->getNextSibling())
        {
            DOMElement* pElement = static_cast<DOMElement*>(pChild);
            if (XMLString::equals(pElement->getNodeName(), X("Signature")))
            {
                std::string signatureId = A(pElement->getAttribute(X("signatureId")));
                Signature* pSignature = dynamic_cast<Signature*>(pSessionManager->getSessionItem(signatureId));
                if (pSignature != NULL)
                {
                    signatures.push_back(pSignature);
                }
            }
        }

        clearLibrary();
        addSignatures(signatures);
    }

    return success;
}
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 ResamplerPlugIn::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   VERIFY(pInArgList != NULL && pOutArgList != NULL);
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Executing Spectral Resampler.", "spectral", "{88CD3E49-A522-431A-AE2A-96A6B2EB4012}");

   Service<DesktopServices> pDesktop;

   const DataElement* pElement(NULL);
   std::string waveFilename;

   // get default resampling options from user config
   std::string resampleMethod = ResamplerOptions::getSettingResamplerMethod();
   double dropOutWindow = ResamplerOptions::getSettingDropOutWindow();
   double fwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   bool useFillValue = ResamplerOptions::getSettingUseFillValue();
   double fillValue = ResamplerOptions::getSettingSignatureFillValue();

   std::vector<Signature*> originalSignatures;
   std::auto_ptr<std::vector<Signature*> > pResampledSignatures(new std::vector<Signature*>);
   std::string errorMsg;

   if (isBatch())
   {
      VERIFY(pInArgList->getPlugInArgValue("Signatures to resample", originalSignatures));
      if (originalSignatures.empty())
      {
         Signature* pSignature = pInArgList->getPlugInArgValue<Signature>("Signature to resample");
         if (pSignature != NULL)
         {
            originalSignatures.push_back(pSignature);
         }
      }
      if (originalSignatures.empty())
      {
         progress.report("No signatures are available to be resampled.", 0, ERRORS, true);
         return false;
      }
      pElement = pInArgList->getPlugInArgValue<DataElement>("Data element wavelength source");
      Filename* pWaveFilename = pInArgList->getPlugInArgValue<Filename>("Wavelengths Filename");
      if (pWaveFilename != NULL)
      {
         waveFilename = pWaveFilename->getFullPathAndName();
      }
      VERIFY(pInArgList->getPlugInArgValue("Resampling Method", resampleMethod));
      VERIFY(pInArgList->getPlugInArgValue("Drop out window", dropOutWindow));
      VERIFY(pInArgList->getPlugInArgValue("FWHM", fwhm));
      VERIFY(pInArgList->getPlugInArgValue("Use fill value", useFillValue));
      VERIFY(pInArgList->getPlugInArgValue("Fill value", fillValue));
   }
   else
   {
      ResamplerPlugInDlg dlg(pDesktop->getMainWidget());
      if (dlg.exec() == QDialog::Rejected)
      {
         progress.report("User canceled resampling.", 0, ABORT, true);
         progress.upALevel();
         return false;
      }
      originalSignatures = dlg.getSignaturesToResample();
      resampleMethod = dlg.getResamplingMethod();
      dropOutWindow = dlg.getDropOutWindow();
      fwhm = dlg.getFWHM();
      useFillValue = dlg.getUseFillValue();
      fillValue = dlg.getFillValue();
      pElement = dlg.getWavelengthsElement();
      waveFilename = dlg.getWavelengthsFilename();
   }

   std::string resampledTo;
   FactoryResource<Wavelengths> pWavelengths;
   if (pElement != NULL)  // try loading wavelengths from user specified data element
   {
      if (getWavelengthsFromElement(pElement, pWavelengths.get(), errorMsg) == false)
      {
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = pElement->getName();
   }
   else if (waveFilename.empty() == false)  // if no user provided raster, look for a wavelengths file
   {
      if (QFile::exists(QString::fromStdString(waveFilename)))
      {
         if (getWavelengthsFromFile(waveFilename, pWavelengths.get(), errorMsg) == false)
         {
            progress.report(errorMsg, 0, ERRORS, true);
            return false;
         }
      }
      else
      {
         errorMsg = "The wavelengths file \"" + waveFilename + "\" could not be found.";
         progress.report(errorMsg, 0, ERRORS, true);
         return false;
      }
      resampledTo = waveFilename;
   }
   else  // if no wavelength source provided, look for raster in current active spatial data view
   {
      SpatialDataView* pView = dynamic_cast<SpatialDataView*>(pDesktop->getCurrentWorkspaceWindowView());
      if (pView != NULL)
      {
         LayerList* pLayerList = pView->getLayerList();
         if (pLayerList != NULL)
         {
            pElement = pLayerList->getPrimaryRasterElement();
            pWavelengths->initializeFromDynamicObject(pElement->getMetadata(), false);
            if (pWavelengths->isEmpty())
            {
               progress.report("No target wavelengths are available for resampling the signatures.", 0, ERRORS, true);
               return false;
            }
            resampledTo = pElement->getName();
         }
      }
   }

   PlugInResource pPlugIn("Resampler");
   Resampler* pResampler = dynamic_cast<Resampler*>(pPlugIn.get());
   if (pResampler == NULL)
   {
      progress.report("The \"Resampler\" plug-in is not available so the signatures can not be resampled.",
         0, ERRORS, true);
      return false;
   }
   std::string dataName("Reflectance");
   std::string wavelengthName("Wavelength");

   // save user config settings - Resampler doesn't have interface to set them separately from user config
   std::string configMethod = ResamplerOptions::getSettingResamplerMethod();
   ResamplerOptions::setSettingResamplerMethod(resampleMethod);
   double configDropout = ResamplerOptions::getSettingDropOutWindow();
   ResamplerOptions::setSettingDropOutWindow(dropOutWindow);
   double configFwhm = ResamplerOptions::getSettingFullWidthHalfMax();
   ResamplerOptions::setSettingFullWidthHalfMax(fwhm);

   std::vector<double> toWavelengths = pWavelengths->getCenterValues();
   std::vector<double> toFwhm = pWavelengths->getFwhm();
   if (toFwhm.size() != toWavelengths.size())
   {
      toFwhm.clear();  // Resampler will use the default config setting fwhm if this vector is empty
   }

   unsigned int numSigs = originalSignatures.size();
   unsigned int numSigsResampled(0);
   progress.report("Begin resampling signatures...", 0, NORMAL);
   for (unsigned int index = 0; index < numSigs; ++index)
   {
      if (isAborted())
      {
         progress.report("Resampling aborted by user", 100 * index / numSigs, ABORT, true);
         return false;
      }
      if (originalSignatures[index] == NULL)
      {
         continue;
      }

      // check if signature has target wavelength centers and doesn't need to be resampled
      if (needToResample(originalSignatures[index], pWavelengths.get()) == false)
      {
         pResampledSignatures->push_back(originalSignatures[index]);
         ++numSigsResampled;
         continue;
      }

      DataVariant var = originalSignatures[index]->getData(dataName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromData;
      if (!var.getValue(fromData))
      {
         continue;
      }
      var = originalSignatures[index]->getData(wavelengthName);
      if (var.isValid() == false)
      {
         continue;
      }
      std::vector<double> fromWavelengths;
      if (!var.getValue(fromWavelengths))
      {
         continue;
      }
      std::string resampledSigName = originalSignatures[index]->getName() + "_resampled";
      int suffix(2);
      ModelResource<Signature> pSignature(resampledSigName, NULL);

      // probably not needed but just in case resampled name already used
      while (pSignature.get() == NULL)
      {
         pSignature = ModelResource<Signature>(resampledSigName + StringUtilities::toDisplayString(suffix), NULL);
         ++suffix;
      }
      if (resampledTo.empty() == false)
      {
         DynamicObject* pMetaData = pSignature->getMetadata();
         if (pMetaData != NULL)
         {
            pMetaData->setAttribute(CommonSignatureMetadataKeys::ResampledTo(), resampledTo);
         }
      }
      std::vector<double> toData;
      std::vector<int> toBands;
      if (pResampler->execute(fromData, toData, fromWavelengths, toWavelengths, toFwhm, toBands, errorMsg))
      {
         if (toWavelengths.size() != toBands.size())
         {
            if (toBands.size() < 2)  // no need to try if only one point
            {
               continue;
            }

            if (useFillValue)
            {
               std::vector<double> values(toWavelengths.size(), fillValue);
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  values[static_cast<unsigned int>(toBands[i])] = toData[i];
               }
               toData.swap(values);
               DynamicObject* pMetaData = pSignature->getMetadata();
               if (pMetaData != NULL)
               {
                  pMetaData->setAttribute(CommonSignatureMetadataKeys::FillValue(), fillValue);
               }
            }
            else
            {
               std::vector<double> wavelengths(toBands.size());
               for (unsigned int i = 0; i < toBands.size(); ++i)
               {
                  wavelengths[i] = toWavelengths[static_cast<unsigned int>(toBands[i])];
               }
               toWavelengths.swap(wavelengths);
            }
         }
         pSignature->setData(dataName, toData);
         pSignature->setData(wavelengthName, toWavelengths);
         SignatureDataDescriptor* pDesc = dynamic_cast<SignatureDataDescriptor*>(pSignature->getDataDescriptor());
         if (pDesc == NULL)
         {
            continue;
         }
         pDesc->setUnits(dataName, originalSignatures[index]->getUnits(dataName));
         pResampledSignatures->push_back(pSignature.release());
         ++numSigsResampled;
      }
      std::string progressStr =
         QString("Resampled signature %1 of %2 signatures").arg(index + 1).arg(numSigs).toStdString();
      progress.report(progressStr, (index + 1) * 100 / numSigs, NORMAL);
   }

   // reset config options
   ResamplerOptions::setSettingResamplerMethod(configMethod);
   ResamplerOptions::setSettingDropOutWindow(configDropout);
   ResamplerOptions::setSettingFullWidthHalfMax(configFwhm);

   if (numSigsResampled == numSigs)
   {
      progress.report("Complete", 100, NORMAL);
      progress.upALevel();
   }
   else
   {
      errorMsg = QString("Only %1 of the %2 signatures were successfully resampled.").arg(
         numSigsResampled).arg(numSigs).toStdString();
      progress.report(errorMsg, 100, WARNING, true);
   }

   VERIFY(pOutArgList->setPlugInArgValue("Resampled signatures", pResampledSignatures.release()));
   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;
}
bool ConnectedComponents::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL)
   {
      return false;
   }
   mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Labeling connected components", "app", "{aa2169d0-9c0a-4d41-9f1d-9a9e83ecf32b}");
   mpView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
   AoiElement* pAoi = pInArgList->getPlugInArgValue<AoiElement>("AOI");
   if (pAoi == NULL && mpView != NULL)
   {
      Layer* pLayer = mpView->getActiveLayer();
      if (pLayer == NULL)
      {
         std::vector<Layer*> layers;
         mpView->getLayerList()->getLayers(AOI_LAYER, layers);
         if (!layers.empty())
         {
            pLayer = layers.front();
         }
      }
      pAoi = pLayer == NULL ? NULL : dynamic_cast<AoiElement*>(pLayer->getDataElement());
   }
   const BitMask* mpBitmask = (pAoi == NULL) ? NULL : pAoi->getSelectedPoints();
   if (mpBitmask == NULL)
   {
      mProgress.report("Must specify an AOI.", 0, ERRORS, true);
      return false;
   }
   if (mpBitmask->isOutsideSelected())
   {
      mProgress.report("Infinite AOIs can not be processed.", 0, ERRORS, true);
      return false;
   }

   // Get the extents and create the output element
   int x1 = 0;
   int x2 = 0;
   int y1 = 0;
   int y2 = 0;
   mpBitmask->getMinimalBoundingBox(x1, y1, x2, y2);
   if (x1 > x2)
   {
      std::swap(x1, x2);
   }
   if (y1 > y2)
   {
      std::swap(y1, y2);
   }
   if (x1 < 0 || y1 < 0)
   {
      mProgress.report("Negative pixel locations are not supported and will be ignored.", 1, WARNING, true);
      x1 = std::max(x1, 0);
      y1 = std::max(y1, 0);
      x2 = std::max(x2, 0);
      y2 = std::max(y2, 0);
   }
   // Include a 1 pixel border so we include the edge pixels
   x1--;
   x2++;
   y1--;
   y2++;
   unsigned int width = x2 - x1 + 1;
   unsigned int height = y2 - y1 + 1;

   mXOffset = x1;
   mYOffset = y1;

   mpLabels = static_cast<RasterElement*>(
      Service<ModelServices>()->getElement("Blobs", TypeConverter::toString<RasterElement>(), pAoi));
   if (mpLabels != NULL)
   {
      if (!isBatch())
      {
         Service<DesktopServices>()->showSuppressibleMsgDlg(
            getName(), "The \"Blobs\" element exists and will be deleted.", MESSAGE_INFO,
            "ConnectedComponents::DeleteExisting");
      }
      Service<ModelServices>()->destroyElement(mpLabels);
      mpLabels = NULL;
   }
   mpLabels = RasterUtilities::createRasterElement("Blobs", height, width, INT2UBYTES, true, pAoi);
   if (mpLabels == NULL)
   {
      mProgress.report("Unable to create label element.", 0, ERRORS, true);
      return false;
   }
   ModelResource<RasterElement> pLabels(mpLabels);

   try
   {
      cv::Mat data(height, width, CV_8UC1, cv::Scalar(0));
      for (unsigned int y = 0; y < height; ++y)
      {
         mProgress.report("Reading AOI data", 10 * y / height, NORMAL);
         for (unsigned int x = 0; x < width; ++x)
         {
            if (mpBitmask->getPixel(x + mXOffset, y + mYOffset))
            {
               data.at<unsigned char>(y, x) = 255;
            }
         }
      }
      mProgress.report("Finding contours", 15, NORMAL);
      std::vector<std::vector<cv::Point> > contours;
      std::vector<cv::Vec4i> hierarchy;
      cv::findContours(data, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
      cv::Mat labels(height, width, CV_16UC1, mpLabels->getRawData());
      mProgress.report("Filling blobs", 50, NORMAL);
      unsigned short lastLabel = 0;
      fillContours(labels, contours, hierarchy, lastLabel, 0, 0);

      // create a pseudocolor layer for display
      mProgress.report("Displaying results", 90, NORMAL);
      mpLabels->updateData();
      if (!createPseudocolor(lastLabel))
      {
         mProgress.report("Unable to create blob layer", 0, ERRORS, true);
         return false;
      }

      // add blob count to the metadata
      DynamicObject* pMeta = pLabels->getMetadata();
      VERIFY(pMeta);
      unsigned int numBlobs = static_cast<unsigned int>(lastLabel);
      pMeta->setAttribute("BlobCount", numBlobs);
      if (numBlobs == 0 && !isBatch())
      {
         // Inform the user that there were no blobs so they don't think there was an
         // error running the algorithm. No need to do this in batch since this is
         // represented in the metadata already.
         mProgress.report("No blobs were found.", 95, WARNING);
      }
      // update the output arg list
      if (pOutArgList != NULL)
      {
         pOutArgList->setPlugInArgValue("Blobs", pLabels.get());
         pOutArgList->setPlugInArgValue("Number of Blobs", &numBlobs);
      }
   }
   catch(const cv::Exception& exc)
   {
      mProgress.report(exc.what(), 0, ERRORS, true);
      return false;
   }

   pLabels.release();
   mProgress.report("Labeling connected components", 100, NORMAL);
   mProgress.upALevel();
   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 BackgroundSuppressionShell::execute(PlugInArgList *pInArgList, PlugInArgList *pOutArgList)
{
   if(pInArgList == NULL)
   {
      return false;
   }
   mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Suppressing background", "temporal", "{01F54B12-0323-4ac4-8C04-C89F1C45EAD9}");
   mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if(mpRaster == NULL)
   {
      mProgress.report("No raster element specified.", 0, ERRORS, true);
      return false;
   }
   mpView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
   RasterDataDescriptor *pDescriptor = static_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor());
   VERIFY(pDescriptor != NULL);
   mIsStreaming = !isBatch();

   if(!isBatch())
   {
      BackgroundSuppressionDialog dlg;
      if(dlg.exec() == QDialog::Rejected)
      {
         mProgress.report("Suppression canceled by user.", 0, ABORT, true);
         return false;
      }
      mIsStreaming = dlg.isStreaming();
      mpAnimation.reset(dlg.animation());
   }

   unsigned int totalFrames = pDescriptor->getBandCount();
   mCurrentFrame = 0;
   mProgressStep = 25.0 / (totalFrames - mCurrentFrame);
   mCurrentProgress = mProgressStep;
   if(!mIsStreaming)
   {
      for(InitializeReturnType rval = INIT_CONTINUE; rval == INIT_CONTINUE; mCurrentFrame++)
      {
         rval = initializeModel();
         if(rval == INIT_ERROR)
         {
            return false;
         }
      }
      for(; mCurrentFrame < totalFrames; mCurrentFrame++)
      {
         if(isAborted())
         {
            try
            {
               mProgress.abort();
            }
            catch(const AlgorithmAbort&)
            {
            }
            cleanup(false);
            return false;
         }
         if(!processFrame())
         {
            cleanup(false);
            return false;
         }
      }
      if(!displayResults())
      {
         cleanup(false);
         mProgress.report("Unable to display results.", 0, ERRORS, true);
         return false;
      }
      cleanup(true);
      mProgress.report("Extraction complete", 100, NORMAL);
      mProgress.upALevel();
   }
   else
   {
      for(InitializeReturnType rval = INIT_CONTINUE; rval == INIT_CONTINUE; mCurrentFrame++)
      {
         rval = initializeModel();
         if(rval == INIT_ERROR)
         {
            return false;
         }
      }
      if(mpAnimation.get() == NULL)
      {
         mProgress.report("No animation specified, unable to perform streaming execution. Provide and animation or run in batch mode.",
            0, ERRORS, true);
         return false;
      }
      mCurrentFrame = 0;
      const AnimationFrame *pFrame = mpAnimation->getCurrentFrame();
      if(pFrame != NULL)
      {
         mCurrentFrame = pFrame->mFrameNumber;
      }
      if(!processFrame() || !displayResults())
      {
         mProgress.report("Unable to initialize streaming mode.", 0, ERRORS, true);
         return false;
      }
      mProgress.report("Streaming mode setup complete.", 100, NORMAL);
      mProgress.upALevel();
      mProgress.initialize(NULL, "Suppressing background", "temporal", "{01F54B12-0323-4ac4-8C04-C89F1C45EAD9}");
      destroyAfterExecute(false);
   }
   return true;
}
Example #19
0
bool ChangeUpDirection::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Rotating data.", "app", "{11adadb9-c133-49de-8cf5-a16372da2578}");

   RasterElement* pData = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pData == NULL)
   {
      progress.report("No data element specified.", 0, ERRORS, true);
      return false;
   }
   bool display = false;
   if (!pInArgList->getPlugInArgValue("Display Results", display))
   {
      progress.report("Unsure if results should be displayed. Invalid argument.", 0, ERRORS, true);
      return false;
   }
   double rotation = 0.0;
   SpatialDataView* pOrigView = NULL;
   if (isBatch())
   {
      if (!pInArgList->getPlugInArgValue("Rotation", rotation))
      {
         progress.report("No rotation specified.", 0, ERRORS, true);
         return false;
      }
   }
   else
   {
      pOrigView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pOrigView == NULL)
      {
         progress.report("No view specified.", 0, ERRORS, true);
         return false;
      }
      GraphicLayer* pLayer = dynamic_cast<GraphicLayer*>(pOrigView->getActiveLayer());
      if (pLayer == NULL)
      {
         pLayer = dynamic_cast<GraphicLayer*>(pOrigView->getTopMostLayer(ANNOTATION));
      }
      GraphicObject* pArrow = NULL;
      if (pLayer != NULL)
      {
         std::list<GraphicObject*> objects;
         pLayer->getObjects(ARROW_OBJECT, objects);
         if (!objects.empty())
         {
            pArrow = objects.back();
         }
         if (objects.size() > 1)
         {
            progress.report("Multiple arrow objects found. Using the most recently added one.", 0, WARNING, true);
         }
      }
      if (pArrow == NULL)
      {
         progress.report("Unable to locate up direction. Add an arrow annotation and re-run this plugin.",
            0, ERRORS, true);
         return false;
      }
      LocationType ur = pArrow->getUrCorner();
      LocationType ll = pArrow->getLlCorner();
      double xlen = ur.mX - ll.mX;
      double ylen = ur.mY - ll.mY;

      // Initial rotatation value. The 90 degrees is due to the difference
      // in the "0 point" (right vs. up). Also account for explicit rotation
      // of the annotation object. Convert this to radians.
      rotation = GeoConversions::convertDegToRad(90 + pArrow->getRotation());

      // Determine a rotation adjustment based on the bounding box
      rotation += atan2(ylen, xlen);
   }

   progress.report("Rotating data.", 10, NORMAL);
   ModelResource<RasterElement> pRotated(pData->copyShallow(pData->getName() + "_rotated", pData->getParent()));
   if (pRotated.get() == NULL)
   {
      progress.report("Unable to create destination raster element.", 0, ERRORS, true);
      return false;
   }

   int defaultBadValue(0);  // the rotate method will handle setting the default bad values into the rotated raster
   if (!RasterUtilities::rotate(pRotated.get(), pData, rotation, defaultBadValue,
      INTERP_NEAREST_NEIGHBOR, progress.getCurrentProgress(), &mAbort))
   {
      // error message already reported by rotate()
      return false;
   }
   pOutArgList->setPlugInArgValue("Rotated Element", pRotated.get());

   if (display)
   {
      SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(
         Service<DesktopServices>()->createWindow(pRotated->getName(), SPATIAL_DATA_WINDOW));
      SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
      if (pView == NULL)
      {
         Service<DesktopServices>()->deleteWindow(pWindow);
         progress.report("Unable to create view.", 0, ERRORS, true);
         return false;
      }
      pView->setPrimaryRasterElement(pRotated.get());

      RasterLayer* pLayer = NULL;
      { // scope
         UndoLock lock(pView);
         pLayer = static_cast<RasterLayer*>(pView->createLayer(RASTER, pRotated.get()));
      }
      if (pLayer == NULL)
      {
//#pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : This would be cleaner with a WindowResource. If one " \
//                                              "becomes available, use it instead. (tclarke)")
         Service<DesktopServices>()->deleteWindow(pWindow);
         progress.report("Unable to create layer.", 0, ERRORS, true);
         return false;
      }
      pOutArgList->setPlugInArgValue("View", pView);
   }

   pRotated.release();
   progress.report("Rotation complete.", 100, NORMAL);
   progress.upALevel();
   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;
}
Example #21
0
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;
}
bool ConvolutionFilterShell::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   if (!extractInputArgs(pInArgList))
   {
      return false;
   }
   if (!populateKernel() || mInput.mKernel.Nrows() % 2 == 0 || mInput.mKernel.Ncols() % 2 == 0)
   {
      mProgress.report("Invalid kernel.", 0, ERRORS, true);
      return false;
   }
   BitMaskIterator iterChecker((mpAoi == NULL) ? NULL : mpAoi->getSelectedPoints(), 0, 0,
      mInput.mpDescriptor->getColumnCount() - 1, mInput.mpDescriptor->getRowCount() - 1);
   EncodingType resultType = mInput.mForceFloat ? EncodingType(FLT8BYTES) : mInput.mpDescriptor->getDataType();
   if (resultType == INT4SCOMPLEX)
   {
      resultType = INT4SBYTES;
   }
   else if (resultType == FLT8COMPLEX)
   {
      resultType = FLT8BYTES;
   }
   if (!isBatch())
   {
      RasterElement* pResult = static_cast<RasterElement*>(
         Service<ModelServices>()->getElement(mResultName, TypeConverter::toString<RasterElement>(), NULL));
      if (pResult != NULL)
      {
         if (QMessageBox::question(Service<DesktopServices>()->getMainWidget(), "Result data set exists",
            "The result data set already exists. Would you like to replace it?",
            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
         {
            return false;
         }
         Service<ModelServices>()->destroyElement(pResult);
      }
   }
   mProgress.report("Begin convolution matrix execution.", 0, NORMAL);

   ModelResource<RasterElement> pResult(RasterUtilities::createRasterElement(
      mResultName, iterChecker.getNumSelectedRows(), iterChecker.getNumSelectedColumns(),
      mInput.mBands.size(), resultType, mInput.mpDescriptor->getInterleaveFormat(),
      mInput.mpDescriptor->getProcessingLocation() == IN_MEMORY));
   pResult->copyClassification(mInput.mpRaster);
   pResult->getMetadata()->merge(mInput.mpDescriptor->getMetadata()); //copy original metadata
   //chip metadata by bands
   vector<DimensionDescriptor> orgBands = mInput.mpDescriptor->getBands();
   vector<DimensionDescriptor> newBands;
   newBands.reserve(mInput.mBands.size());
   for (unsigned int index = 0; index < mInput.mBands.size(); ++index)
   {
      unsigned int selectedBand = mInput.mBands[index];
      if (selectedBand < orgBands.size())
      {
         newBands.push_back(orgBands[selectedBand]);
      }
   }
   RasterUtilities::chipMetadata(pResult->getMetadata(), mInput.mpDescriptor->getRows(),
      mInput.mpDescriptor->getColumns(), newBands);
   mInput.mpResult = pResult.get();
   if (mInput.mpResult == NULL)
   {
      mProgress.report("Unable to create result data set.", 0, ERRORS, true);
      return false;
   }
   mInput.mpAbortFlag = &mAborted;
   mInput.mpIterCheck = &iterChecker;
   ConvolutionFilterThreadOutput outputData;
   mta::ProgressObjectReporter reporter("Convolving", mProgress.getCurrentProgress());
   mta::MultiThreadedAlgorithm<ConvolutionFilterThreadInput,
                               ConvolutionFilterThreadOutput,
                               ConvolutionFilterThread>
          alg(mta::getNumRequiredThreads(iterChecker.getNumSelectedRows()), mInput, outputData, &reporter);
   switch(alg.run())
   {
   case mta::SUCCESS:
      if (!isAborted())
      {
         mProgress.report("Convolution filter complete.", 100, NORMAL);
         SpatialDataView* pView = displayResult();
         if (Service<ApplicationServices>()->isInteractive() && pView == NULL)
         {
            return false;
         }
         pOutArgList->setPlugInArgValue("View", pView);

         pResult.release();
         mProgress.upALevel();
         return true;
      }
      // fall through
   case mta::ABORT:
      mProgress.report("Convolution filter aborted.", 0, ABORT, true);
      return false;
   case mta::FAILURE:
      mProgress.report("Convolution filter failed.", 0, ERRORS, true);
      return false;
   default:
      VERIFY(false); // can't happen
   }
}
Example #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;
}
Example #24
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 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 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 ConvolutionFilterShell::extractInputArgs(PlugInArgList* pInArgList)
{
   VERIFY(pInArgList);
   mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Executing " + getName(), "app", "{64097F31-84D0-41bf-BBAF-F60DAF212836}");
   if ((mInput.mpRaster = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg())) == NULL)
   {
      mProgress.report("No raster element.", 0, ERRORS, true);
      return false;
   }
   mInput.mpDescriptor = static_cast<const RasterDataDescriptor*>(mInput.mpRaster->getDataDescriptor());
   mpAoi = pInArgList->getPlugInArgValue<AoiElement>("AOI");
   if (mpAoi == NULL && !isBatch())
   {
      SpatialDataView* pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pView != NULL)
      {
         std::vector<Layer*> layers;
         pView->getLayerList()->getLayers(AOI_LAYER, layers);
         if (!layers.empty())
         {
            QStringList layerNames;
            layerNames << "<none>";
            for (std::vector<Layer*>::const_iterator layer = layers.begin(); layer != layers.end(); ++layer)
            {
               layerNames << QString::fromStdString((*layer)->getName());
            }
            bool ok = true;
            std::string selectedLayer = QInputDialog::getItem(
               Service<DesktopServices>()->getMainWidget(), "Choose an AOI",
               "Select an AOI or <none> to process the entire image", layerNames, 0, false, &ok).toStdString();
            if (!ok)
            {
               mProgress.report("User cancelled " + getName(), 0, ABORT, true);
               return false;
            }
            for (std::vector<Layer*>::const_iterator layer = layers.begin(); layer != layers.end(); ++layer)
            {
               if ((*layer)->getName() == selectedLayer)
               {
                  mpAoi = static_cast<AoiElement*>((*layer)->getDataElement());
                  break;
               }
            }
         }
      }
   }
   std::vector<unsigned int> bandNumbers;
   if (!pInArgList->getPlugInArgValue("Band Numbers", bandNumbers))
   {
      mProgress.report("Error getting band numbers.", 0, ERRORS, true);
      return false;
   }
   if (!bandNumbers.empty())
   {
      mInput.mBands = bandNumbers;
   }
   pInArgList->getPlugInArgValue("Result Name", mResultName);
   if (mResultName.empty())
   {
      mResultName = mInput.mpRaster->getName() + " Convolved";
      if (!isBatch())
      {
         bool ok = true;
         mResultName = QInputDialog::getText(Service<DesktopServices>()->getMainWidget(), "Output data name",
            "Choose a name for the output data cube", QLineEdit::Normal,
            QString::fromStdString(mResultName), &ok).toStdString();
         if (!ok)
         {
            mProgress.report("User cancelled " + getName(), 0, ABORT, true);
         }
      }
   }

   if (!pInArgList->getPlugInArgValue("Offset", mInput.mOffset))
   {
      mProgress.report("Error getting offset.", 0, ERRORS, true);
      return false;
   }

   if (!pInArgList->getPlugInArgValue("Force Float", mInput.mForceFloat))
   {
      mProgress.report("Error getting float output.", 0, ERRORS, true);
      return false;
   }
   return true;
}
Example #28
0
bool VideoImporter::execute(PlugInArgList *pInArgList, PlugInArgList *pOutArgList)
{
   if(pInArgList == NULL)
   {
      return false;
   }
   // Create a message log step
   mProgress = ProgressTracker(pInArgList->getPlugInArgValue<Progress>(ProgressArg()),
      "Execute video importer", "coan", "{6385aa93-ff7f-4ee7-9308-b3476aca544b}");

   DataElement* pElmnt = pInArgList->getPlugInArgValue<DataElement>(ImportElementArg());
   mpRasterElement = dynamic_cast<RasterElement*>(pElmnt);
   mpStreamElement = dynamic_cast<Any*>(pElmnt);
   if (mpRasterElement == NULL && mpStreamElement == NULL)
   {
      mProgress.report("The data element input value is invalid.", 0, ERRORS, true);
      return false;
   }

   if (mpRasterElement != NULL)
   {
      mProgress.report("Initialize display.", 1, NORMAL);
      if (!mpRasterElement->createDefaultPager())
      {
         //return checkAbortOrError("Could not allocate resources for new RasterElement", pStep.get());
         return false;
      }
      // schedule load of first frame
      Any* pParent = dynamic_cast<Any*>(mpRasterElement->getParent());
      VERIFY(pParent != NULL);
      VideoStream* pStream = dynamic_cast<VideoStream*>(pParent->getData());
      VERIFY(pStream != NULL);
      if (!pStream->setDisplay(mpRasterElement))
      {
         mProgress.report("Unable to display the stream.", 0, ERRORS, true);
         return false;
      }

      // Create the view
      if(!isBatch() && !Service<SessionManager>()->isSessionLoading())
      {
         SpatialDataView *pView = createView();
         if(pView == NULL)
         {
            mProgress.report("The view could not be created.", 0, ERRORS, true);
            return false;
         }

         // Add the view to the output arg list
         if(pOutArgList != NULL)
         {
            pOutArgList->setPlugInArgValue("View", pView);
         }
      }
      mProgress.report("Display initialization complete.", 100, NORMAL);
   }
   else if (mpStreamElement != NULL)
   {
      mProgress.report("Initialize video stream.", 1, NORMAL);
      // initialize the stream data
      VideoStream* pStream = NULL;
      std::vector<PlugIn*> instances = Service<PlugInManagerServices>()->getPlugInInstances("Video Stream Manager");
      StreamManager* pStreamManager = instances.empty() ? NULL : dynamic_cast<StreamManager*>(instances.front());
      if (pStreamManager != NULL)
      {
         if (pStreamManager->initializeStream(mpStreamElement))
         {
            pStream = dynamic_cast<VideoStream*>(mpStreamElement->getData());
         }
      }
      if (pStream == NULL)
      {
         mProgress.report("Unable to initialize the video stream.", 0, ERRORS, true);
         return false;
      }
      
      // create animation
      AnimationController* pController = Service<AnimationServices>()->getAnimationController(mpStreamElement->getName());
      if (pController == NULL)
      {
         pController = Service<AnimationServices>()->createAnimationController(mpStreamElement->getName(), FRAME_TIME);
      }
      if (pController == NULL)
      {
         mProgress.report("Unable to create animation.", 0, ERRORS, true);
         return false;
      }
      if (!isBatch())
      {
         AnimationToolBar* pToolBar = static_cast<AnimationToolBar*>(Service<DesktopServices>()->getWindow("Animation", TOOLBAR));
         VERIFY(pToolBar);
         pToolBar->setAnimationController(pController);
      }
      Animation* pAnim = pController->createAnimation(mpStreamElement->getName());
      VERIFY(pAnim != NULL);
      if (!pStream->setAnimation(pAnim, pController))
      {
         mProgress.report("Unable to create animation.", 0, ERRORS, true);
         return false;
      }

      mProgress.report("Video stream initialization complete.", 100, NORMAL);
   }

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