bool bilinear_bayer::copyImage(RasterElement * pRaster,
							   RasterElement * dRaster, int i,
							   Progress * pProgress)
{
	VERIFY(pRaster != NULL);
	RasterDataDescriptor *pDesc =
		dynamic_cast < RasterDataDescriptor * >(pRaster->getDataDescriptor());
	VERIFY(dRaster != NULL);
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRaster->getDataDescriptor());



	DimensionDescriptor thirdBand = pDesc->getActiveBand(i);	// get active
																// band

	// source
	FactoryResource < DataRequest > pRequest;
	pRequest->setInterleaveFormat(BSQ);
	pRequest->setBands(thirdBand, thirdBand);
	DataAccessor thirdBandDa = pRaster->getDataAccessor(pRequest.release());
	thirdBand = rDesc->getActiveBand(i);

	// destination
	FactoryResource < DataRequest > pResultRequest;
	pResultRequest->setWritable(true);
	pRequest->setInterleaveFormat(BSQ);
	pResultRequest->setBands(thirdBand, thirdBand);
	DataAccessor pDestAcc = dRaster->getDataAccessor(pResultRequest.release());






	VERIFY(thirdBandDa.isValid());
	VERIFY(pDestAcc.isValid());


	for (unsigned int curRow = 0; curRow < pDesc->getRowCount(); ++curRow)

	{
		for (unsigned int curCol = 0; curCol < pDesc->getColumnCount();
			 ++curCol)
		{

			switchOnEncoding(pDesc->getDataType(), bilinear,
							 pDestAcc->getColumn(), thirdBandDa, curRow,
							 curCol, pDesc->getRowCount(),
							 pDesc->getColumnCount(), i, pRaster);
			pDestAcc->nextColumn();
		}

		pDestAcc->nextRow();

	}

	return true;
}
Beispiel #2
0
   DataAccessorImpl* createDataAccessor(DataElement* pElement, DataAccessorArgs* pArgs)
   {
      RasterElement* pRasterElement = dynamic_cast<RasterElement*>(pElement);
      if (pRasterElement == NULL)
      {
         setLastError(SIMPLE_BAD_PARAMS);
         return NULL;
      }

      FactoryResource<DataRequest> pRequest;
      RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pRasterElement->getDataDescriptor());
      if (pArgs != NULL)
      {
         pRequest->setRows(pDescriptor->getActiveRow(pArgs->rowStart),
            pDescriptor->getActiveRow(pArgs->rowEnd),pArgs->concurrentRows);
         pRequest->setColumns(pDescriptor->getActiveColumn(pArgs->columnStart),
            pDescriptor->getActiveColumn(pArgs->columnEnd),pArgs->concurrentColumns);
         pRequest->setBands(pDescriptor->getActiveBand(pArgs->bandStart),
            pDescriptor->getActiveBand(pArgs->bandEnd),pArgs->concurrentBands);
         pRequest->setInterleaveFormat(static_cast<InterleaveFormatTypeEnum>(pArgs->interleaveFormat));
         pRequest->setWritable(pArgs->writable != 0);
      }

      DataAccessor dataAccessor(pRasterElement->getDataAccessor(pRequest.release()));
      if (!dataAccessor.isValid())
      {
         setLastError(SIMPLE_BAD_PARAMS);
         return NULL;
      }
      DataAccessorImpl* pRval = dataAccessor.operator->();
      pRval->incrementRefCount();

      setLastError(SIMPLE_NO_ERROR);
      return pRval;
   }
DataAccessor BackgroundSuppressionShell::getCurrentFrameAccessor() const
{
   if(mpRaster == NULL)
   {
      return DataAccessor(NULL, NULL);
   }
   RasterDataDescriptor *pDesc = static_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor());
   VERIFYRV(pDesc != NULL, DataAccessor(NULL, NULL));
   FactoryResource<DataRequest> request;
   VERIFYRV(request.get() != NULL, DataAccessor(NULL, NULL));
   request->setInterleaveFormat(BSQ);
   DimensionDescriptor band = pDesc->getBands()[mCurrentFrame];
   request->setBands(band, band, 1);
   return mpRaster->getDataAccessor(request.release());
}
Beispiel #4
0
const double *SignatureLibraryImp::getOrdinateData(unsigned int index) const
{
   if (mNeedToResample || mResampledData.empty())
   {
      const_cast<SignatureLibraryImp*>(this)->resample(mAbscissa);
   }

   if (index < mSignatures.size() && (!mAbscissa.empty() || mpOdre.get() != NULL))
   {
      if (mAbscissa.empty())
      {
         const RasterDataDescriptor* pDesc =
            dynamic_cast<const RasterDataDescriptor*>(mpOdre.get()->getDataDescriptor());
         if (pDesc != NULL)
         {
            FactoryResource<DataRequest> pRequest;
            pRequest->setInterleaveFormat(BIP);
            pRequest->setBands(pDesc->getActiveBand(0),
               pDesc->getActiveBand(pDesc->getBandCount() - 1), pDesc->getBandCount());
            pRequest->setRows(pDesc->getActiveRow(index), pDesc->getActiveRow(index), 1);
            DataAccessor da = mpOdre->getDataAccessor(pRequest.release());
            if (da.isValid())
            {
               static vector<double> sOriginalOrdinateData;
               sOriginalOrdinateData.resize(mOriginalAbscissa.size());
               switchOnEncoding(pDesc->getDataType(), getOriginalAsDouble, da->getRow(), mOriginalAbscissa.size(),
                  sOriginalOrdinateData);
               return &sOriginalOrdinateData[0];
            }
         }

         return NULL;
      }

      return &mResampledData[index * getAbscissa().size()];
   }

   return NULL;
}
bool SpectralLibraryManager::getResampledSignatureValues(const RasterElement* pRaster, const Signature* pSignature,
        std::vector<double>& values)
{
    values.clear();
    if (pRaster == NULL || pSignature == NULL)
    {
        return false;
    }

    const RasterElement* pLibData = getResampledLibraryData(pRaster);
    if (pLibData == NULL)
    {
        return false;
    }

    int index = getSignatureIndex(pSignature);
    if (index < 0)
    {
        return false;
    }
    const RasterDataDescriptor* pLibDesc = dynamic_cast<const RasterDataDescriptor*>(pLibData->getDataDescriptor());
    VERIFY(pLibDesc != NULL);
    unsigned int numBands = pLibDesc->getBandCount();
    values.reserve(numBands);
    FactoryResource<DataRequest> pRqt;
    unsigned int row = static_cast<unsigned int>(index);
    pRqt->setInterleaveFormat(BIP);
    pRqt->setRows(pLibDesc->getActiveRow(row), pLibDesc->getActiveRow(row), 1);
    DataAccessor acc = pLibData->getDataAccessor(pRqt.release());
    VERIFY(acc.isValid());
    double* pDbl = reinterpret_cast<double*>(acc->getColumn());
    for (unsigned int band = 0; band < numBands; ++band)
    {
        values.push_back(*pDbl);
        ++pDbl;
    }

    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;
}
Beispiel #7
0
bool DataMergeGui::mergeData() 
{
//	Service<ModelServices> pModel;
	StepResource pStep("Data Merge Begin", "app", "5E4BCD48-E662-408b-93AF-F9127CE56C66");	
	if (mergeList->count() == 0)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement to merge", "OK");
		pStep->finalize(Message::Failure, "No RasterElement to merge");
		return false;
	}

//	pProgress = new Progress(this, "Progress Reporter");
//	std::vector<DataElement*> cubes = pModel->getElements("RasterElement");
/*	if (mergeElementList.size() == 0)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement input found!", "OK");
		pStep->finalize(Message::Failure, "No RasterElement input found!");
		return false;
	} */
	//QListWidgetItem *tmpItem = mergeList->item(i0);
	//QString tmpItemText = tmpItem->text();
	RasterElement* pInitData = extractRasterElement(mergeList->item(0)->text());

//	vector<RasterElement*>::iterator initIter = mergeElementList.begin();
//	RasterElement* pInitData = model_cast<RasterElement*>(*initIter);

	if (pInitData == NULL)
	{
		pStep->finalize(Message::Failure, "Cube Data error!");
		QMessageBox::critical(this, "Error", "pInitData Error");
		return false;
	}

	RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pInitData->getDataDescriptor());
	EncodingType type = pDesc->getDataType();
	int rowCount = pDesc->getRowCount();
	int colCount = pDesc->getColumnCount();
	int bandCount = mergeList->count();

	RasterElement* pDesRaster = RasterUtilities::createRasterElement("DataMergeCube", rowCount,
      colCount, bandCount, type, BIP, true, NULL);
	
	if (pDesRaster == NULL)
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "Create RasterElement failed, Please close the previous merge result!", "OK");
		pStep->finalize(Message::Failure, "No RasterElement input found!");
		return false;
	}

	FactoryResource<DataRequest> pRequest;
	pRequest->setInterleaveFormat(BIP);
	DataAccessor pDesAcc = pDesRaster->getDataAccessor(pRequest.release());
	
	if (!pDesAcc.isValid())
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "pDesRaster Data Accessor Error!", "OK");
		pStep->finalize(Message::Failure, "pDesRaster Data Accessor Error!");
		return false;
	} 

	if (pProgress == NULL) 
	{
		QMessageBox::critical(NULL, "Spectral Data Merge", "pProgress Initialize Error!", "OK");
		pStep->finalize(Message::Failure, "pProgress Error!");
		return false;
	}
//	progressDialog = new QProgressDialog();
//	progressDialog->setRange(0, rowCount);
	
	//int index = 0;
	for (int i = 0; i < mergeList->count(); i++)
	{
		QListWidgetItem *tmpItem = mergeList->item(i);
		QString tmpItemText = tmpItem->text();
		RasterElement* pData = extractRasterElement(tmpItemText);
		int band = extractMergeBand(tmpItemText);

		if (pData != NULL)
		{
			RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pData->getDataDescriptor());
			if (rowCount != pDesc->getRowCount())
			{
				QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
				pStep->finalize(Message::Failure, "Merge Data Row Format Error!");
				return false;			
			}
					
			if (colCount != pDesc->getColumnCount())
			{
				QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
				pStep->finalize(Message::Failure, "Merge Data Column Format Error!");
				return false;			
			}
	//		QMessageBox::about(this, "Test", "Here2");
			FactoryResource<DataRequest> pRequest;
			pRequest->setInterleaveFormat(BIP);
		//	pRequest->setWritable(true);
			DataAccessor pSrcAcc = pData->getDataAccessor(pRequest.release());	
			switchOnEncoding(pDesc->getDataType(), mergeElement, NULL, rowCount, 
				colCount, pSrcAcc, pDesAcc, i, band, pProgress, mergeList->count());
	//		QMessageBox::about(this, "Test", "Here5");
		}
		else {
			QMessageBox::critical(this, "Error", "pData is NULL");
			return false;
		}

	//	mergeElementList.push_back(filenameMap[tmpItemText.toStdString()]);
	}

	Service<DesktopServices> pDesktop;
	SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow("DataMergeResult",
	   SPATIAL_DATA_WINDOW));

    SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
    if (pView == NULL)
    {
		pStep->finalize(Message::Failure, "SpatialDataView error!");
	    return false;
    }

	pView->setPrimaryRasterElement(pDesRaster);
    pView->createLayer(RASTER, pDesRaster);
	

	if (pDesc != NULL)
    {
		const RasterFileDescriptor* pFileDescriptor = dynamic_cast<const RasterFileDescriptor*>(pDesc->getFileDescriptor());
        if (pFileDescriptor != NULL)
        {
			Service<ModelServices> pModel;
            if (pModel.get() != NULL)
            {
				list<GcpPoint> gcps;             
                gcps = pFileDescriptor->getGcps();           
                if (gcps.empty() == true)
                {
					if (pInitData->isGeoreferenced())
                    {
						GcpPoint gcp;

                        // Lower left
                        gcp.mPixel.mX = 0.0;
                        gcp.mPixel.mY = 0.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Lower right
                        gcp.mPixel.mX = colCount - 1;
                        gcp.mPixel.mY = 0.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Upper left
                        gcp.mPixel.mX = 0.0;
                        gcp.mPixel.mY = rowCount - 1;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Upper right
                        gcp.mPixel.mX = colCount - 1;
                        gcp.mPixel.mY = rowCount - 1;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);

                        // Center
                        gcp.mPixel.mX = colCount / 2.0;
                        gcp.mPixel.mY = rowCount / 2.0;
                        gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
                        gcps.push_back(gcp);
                     }
                  }

                  if (gcps.empty() == false)
                  {
                     DataDescriptor* pGcpDescriptor = pModel->createDataDescriptor("Corner Coordinates",
                        "GcpList", pDesRaster);
                     if (pGcpDescriptor != NULL)
                     {
                        GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement(pGcpDescriptor));
                        if (pGcpList != NULL)
                        {
                           // Add the GCPs to the GCP list
                           pGcpList->addPoints(gcps);

                           // Create the GCP list layer
                           pView->createLayer(GCP_LAYER, pGcpList);
                        }
                     }
                  }
               }
		}
	}

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

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

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

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

   reportComplete();
   return true;
}
bool 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;
}
Beispiel #10
0
vector<ImportDescriptor*> SioImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;
   if (filename.empty() == false)
   {
      // Read the header values
      FileResource pFile(filename.c_str(), "rb");

      SioFile sioFile;
      bool bSuccess = sioFile.deserialize(pFile.get());
      if (bSuccess == false)
      {
         return descriptors;
      }

      if (sioFile.mOriginalVersion == 9)
      {
         mVersion9Sio = true;
      }


      // Create the import descriptor
      ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "RasterElement", NULL);
      if (pImportDescriptor != NULL)
      {
         RasterDataDescriptor* pDescriptor =
            dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
         if (pDescriptor != NULL)
         {
            FactoryResource<RasterFileDescriptor> pFileDescriptor;
            if (pFileDescriptor.get() != NULL)
            {
               // Filename
               pFileDescriptor->setFilename(filename);

               // Endian
               pFileDescriptor->setEndian(sioFile.mEndian);

               // Rows
               vector<DimensionDescriptor> rows;
               for (int i = 0; i < sioFile.mRows; ++i)
               {
                  DimensionDescriptor rowDim;

                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigRowNumbers.size())
                  {
                     rowDim.setOriginalNumber(sioFile.mOrigRowNumbers[i]);
                  }
                  else
                  {
                     rowDim.setOriginalNumber(i);
                  }

                  rowDim.setOnDiskNumber(i);
                  rows.push_back(rowDim);
               }

               pDescriptor->setRows(rows);
               pFileDescriptor->setRows(rows);

               // Columns
               vector<DimensionDescriptor> columns;
               for (int i = 0; i < sioFile.mColumns; ++i)
               {
                  DimensionDescriptor columnDim;

                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigColumnNumbers.size())
                  {
                     columnDim.setOriginalNumber(sioFile.mOrigColumnNumbers[i]);
                  }
                  else
                  {
                     columnDim.setOriginalNumber(i);
                  }

                  columnDim.setOnDiskNumber(i);
                  columns.push_back(columnDim);
               }

               pDescriptor->setColumns(columns);
               pFileDescriptor->setColumns(columns);

               // Bands
               vector<DimensionDescriptor> bands;
               for (int i = 0; i < (sioFile.mBands - sioFile.mBadBands); ++i)
               {
                  DimensionDescriptor bandDim;
                  // Do not set an active number since the user has not selected the rows to load
                  if (static_cast<unsigned int>(i) < sioFile.mOrigBandNumbers.size())
                  {
                     bandDim.setOriginalNumber(sioFile.mOrigBandNumbers[i]);
                  }
                  else
                  {
                     bandDim.setOriginalNumber(i);
                  }

                  bandDim.setOnDiskNumber(i);
                  bands.push_back(bandDim);
               }

               pDescriptor->setBands(bands);
               pFileDescriptor->setBands(bands);

               // Bits per pixel
               pFileDescriptor->setBitsPerElement(sioFile.mBitsPerElement);

               // Data type
               pDescriptor->setDataType(sioFile.mDataType);
               pDescriptor->setValidDataTypes(vector<EncodingType>(1, sioFile.mDataType));

               // Interleave format
               pDescriptor->setInterleaveFormat(BIP);
               pFileDescriptor->setInterleaveFormat(BIP);

               // Bad values
               if (sioFile.mBadValues.empty() == true)
               {
                  if ((sioFile.mDataType != FLT4BYTES) && (sioFile.mDataType != FLT8COMPLEX) &&
                     (sioFile.mDataType != FLT8BYTES))
                  {
                     vector<int> badValues;
                     badValues.push_back(0);

                     pDescriptor->setBadValues(badValues);
                  }
               }

               // Header bytes
               pFileDescriptor->setHeaderBytes(28);

               // Trailer bytes
               struct stat statBuffer;
               if (stat(filename.c_str(), &statBuffer) == 0)
               {
                  double dataBytes = 28 + (sioFile.mRows * sioFile.mColumns * (sioFile.mBands - sioFile.mBadBands) *
                     (sioFile.mBitsPerElement / 8));
                  pFileDescriptor->setTrailerBytes(static_cast<unsigned int>(statBuffer.st_size - dataBytes));
               }

               // Units
               FactoryResource<Units> pUnits;
               pUnits->setUnitType(sioFile.mUnitType);
               pUnits->setUnitName(sioFile.mUnitName);
               pUnits->setRangeMin(sioFile.mRangeMin);
               pUnits->setRangeMax(sioFile.mRangeMax);
               pUnits->setScaleFromStandard(sioFile.mScale);

               pDescriptor->setUnits(pUnits.get());
               pFileDescriptor->setUnits(pUnits.get());

               // GCPs
               GcpPoint gcpLowerLeft;
               gcpLowerLeft.mPixel.mX = 0.0;
               gcpLowerLeft.mPixel.mY = 0.0;

               GcpPoint gcpLowerRight;
               gcpLowerRight.mPixel.mX = sioFile.mColumns - 1.0;
               gcpLowerRight.mPixel.mY = 0.0;

               GcpPoint gcpUpperLeft;
               gcpUpperLeft.mPixel.mX = 0.0;
               gcpUpperLeft.mPixel.mY = sioFile.mRows - 1.0;

               GcpPoint gcpUpperRight;
               gcpUpperRight.mPixel.mX = sioFile.mColumns - 1.0;
               gcpUpperRight.mPixel.mY = sioFile.mRows - 1.0;

               GcpPoint gcpCenter;
               gcpCenter.mPixel.mX = sioFile.mColumns / 2.0 - 0.5;
               gcpCenter.mPixel.mY = sioFile.mRows / 2.0 - 0.5;

               bool bValidGcps = false;
               for (int i = ORIGINAL_SENSOR; i < INVALID_LAST_ENUM_ITEM_FLAG; ++i)
               {
                  if (sioFile.mParameters[i].eParameter_Initialized == true)
                  {
                     switch (i)
                     {
                        case UPPER_LEFT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_LEFT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_LEFT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_LEFT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerLeft.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerLeft.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_RIGHT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case UPPER_RIGHT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpUpperRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpUpperRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_RIGHT_CORNER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case LOWER_RIGHT_CORNER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpLowerRight.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpLowerRight.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case CENTER_LAT:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpCenter.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpCenter.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        case CENTER_LONG:
                           if ((sioFile.mVersion == 5) || (sioFile.mVersion == 6))
                           {
                              gcpCenter.mCoordinate.mX = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           else if ((sioFile.mVersion == 7) || (sioFile.mVersion == 8))
                           {
                              gcpCenter.mCoordinate.mY = sioFile.mParameters[i].uParameter_Value.dData;
                           }
                           bValidGcps = true;
                           break;

                        default:
                           break;
                     }
                  }
               }

               if (bValidGcps == true)
               {
                  list<GcpPoint> gcps;
                  gcps.push_back(gcpLowerLeft);
                  gcps.push_back(gcpLowerRight);
                  gcps.push_back(gcpUpperLeft);
                  gcps.push_back(gcpUpperRight);
                  gcps.push_back(gcpCenter);

                  pFileDescriptor->setGcps(gcps);
               }

               // Classification
               pDescriptor->setClassification(sioFile.mpClassification.get());

               // Metadata
               pDescriptor->setMetadata(sioFile.mpMetadata.get());

               DynamicObject* pMetadata = pDescriptor->getMetadata();
               if (pMetadata != NULL)
               {
                  vector<double> startWavelengths(sioFile.mStartWavelengths.size());
                  copy(sioFile.mStartWavelengths.begin(), sioFile.mStartWavelengths.end(), startWavelengths.begin());
                  vector<double> endWavelengths(sioFile.mEndWavelengths.size());
                  copy(sioFile.mEndWavelengths.begin(), sioFile.mEndWavelengths.end(), endWavelengths.begin());
                  vector<double> centerWavelengths(sioFile.mCenterWavelengths.size());
                  copy(sioFile.mCenterWavelengths.begin(), sioFile.mCenterWavelengths.end(), centerWavelengths.begin());

                  string pStartPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     START_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pStartPath, startWavelengths);
                  string pEndPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     END_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pEndPath, endWavelengths);
                  string pCenterPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                     CENTER_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                  pMetadata->setAttributeByPath(pCenterPath, centerWavelengths);
               }

               // File descriptor
               pDescriptor->setFileDescriptor(pFileDescriptor.get());
            }
         }

         descriptors.push_back(pImportDescriptor);
      }
   }

   return descriptors;
}
bool NefImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
    
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   //setting up mpRasterElement
   parseInputArgList(pInArgList);
   RasterElement* pRaster = getRasterElement();
   
   VERIFY(pRaster != NULL);
   RasterDataDescriptor *pDescriptor = dynamic_cast<RasterDataDescriptor*>(pRaster->getDataDescriptor());

   VERIFY(pDescriptor != NULL);
   FileDescriptor *pFileDescriptor = pDescriptor->getFileDescriptor();
   VERIFY(pFileDescriptor != NULL);

   //data accessor
   //RED
   DimensionDescriptor firstBand = pDescriptor->getActiveBand(0);
   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   pRequest->setBands(firstBand, firstBand);
   pRequest->setWritable(true);
   DataAccessor firstBandDa = pRaster->getDataAccessor(pRequest.release());

   
   //GREEN
   DimensionDescriptor secondBand = pDescriptor->getActiveBand(1);
   FactoryResource<DataRequest> qRequest;
   qRequest->setInterleaveFormat(BSQ);
   qRequest->setBands(secondBand, secondBand);
   qRequest->setWritable(true);
   DataAccessor secondBandDa = pRaster->getDataAccessor(qRequest.release());

   //BLUE
   DimensionDescriptor thirdBand = pDescriptor->getActiveBand(2);
   FactoryResource<DataRequest> rRequest;
   rRequest->setInterleaveFormat(BSQ);
   rRequest->setBands(thirdBand, thirdBand);
   rRequest->setWritable(true);
   DataAccessor thirdBandDa = pRaster->getDataAccessor(rRequest.release());

   

   std::string filename = pRaster->getFilename();
   Progress *pProgress = getProgress();
   
   FactoryResource<Filename> pFilename;
   pFilename->setFullPathAndName(filename);

   LibRaw RawProcessor;
   putenv ((char*)"TZ=UTC"); 

	#define P1  RawProcessor.imgdata.idata
#define S   RawProcessor.imgdata.sizes
#define C   RawProcessor.imgdata.color
#define T   RawProcessor.imgdata.thumbnail
#define P2  RawProcessor.imgdata.other
#define OUT RawProcessor.imgdata.params

   const char *fname=filename.c_str();
    RawProcessor.open_file(fname);

	// Let us unpack the image
        if (RawProcessor.unpack() != LIBRAW_SUCCESS)
   {
      return false;
   }
    
    /*
	unsigned int *r=NULL;
	unsigned int *g=NULL;
	unsigned int *b=NULL;
	unsigned int *h=NULL;
	*/
    unsigned int *zero=0;
	int row=0,col=0,r=0,c=0;
	
		   
		   /*
		   r=(unsigned int*)(&RawProcessor.imgdata.image[i][0]);
           g=(unsigned int*)(&RawProcessor.imgdata.image[i][1]);
           b=(unsigned int*)(&RawProcessor.imgdata.image[i][2]);
           h=(unsigned int*)(&RawProcessor.imgdata.image[i][3]);
		   */
		   //secondBandDa->toPixel(row,col);
		   //thirdBandDa->toPixel(row,col);

		   
		unsigned short *pData=reinterpret_cast<unsigned short*>(pRaster->getRawData());
		if (pData == NULL)
		{
      return NULL;
		}

		memcpy(pData, RawProcessor.imgdata.rawdata.raw_image, sizeof(unsigned short) * RawProcessor.imgdata.sizes.raw_height * RawProcessor.imgdata.sizes.raw_width);


		 /*  
		   if(i%2==0) //RG1
		       {memcpy(firstBandDa->getColumn(),(unsigned int*)RawProcessor.imgdata.image[i][0],sizeof(unsigned int));
				memcpy(thirdBandDa->getColumn(),(unsigned int*)RawProcessor.imgdata.image[i][2],sizeof(unsigned int));
				memcpy(secondBandDa->getColumn(),zero,sizeof(unsigned int));
			    }
		   else{
			   //G2B
			   memcpy(thirdBandDa->getColumn(),(unsigned int*)RawProcessor.imgdata.image[i][3],sizeof(unsigned int));
			   memcpy(secondBandDa->getColumn(),(unsigned int*)RawProcessor.imgdata.image[i][1],sizeof(unsigned int));
			   memcpy(firstBandDa->getColumn(),zero,sizeof(unsigned int));
				}

		*/
		unsigned short *ptr=NULL;

		//band 0 Red
		for(row=0,r=0;row<S.iheight;row++,r++)
		{
			for(col=0,c=0;col<S.iwidth;col++,c++)
			{
			   if(row%2==0)  //RG row
			   {
			    if(col%2==0) //Red pixel
				{
					ptr=reinterpret_cast<unsigned short*>(firstBandDa->getColumn());
				    *ptr=pData[c+(r*S.iwidth)+(0*S.iheight*S.iwidth)];
			     }
			    else
			    {
				   *ptr=0;
				   c--;
			    }
			   }
			   else  //GB row
			   {
				   *ptr=0;
			   }
			    firstBandDa->nextColumn();
			   
			}
			if(row%2!=0)
			   r--;
			firstBandDa->nextRow();
		}
		

		//band 2 Blue
		for(row=0,r=0;row<S.iheight;row++,r++)
		{
			for(col=0,c=0;col<S.iwidth;col++,c++)
			{
			   if(row%2!=0)  //GB row
			   {
			    if(col%2!=0) //Blue pixel
				{
					ptr=reinterpret_cast<unsigned short*>(secondBandDa->getColumn());
				    *ptr=pData[c+(r*S.iwidth)+(2*S.iheight*S.iwidth)];
			     }
			    else
			    {
				   *ptr=0;
				   c--;
			    }
			   }
			   else  //RG row
			   {
				   *ptr=0;
			   }
			    secondBandDa->nextColumn();
			   
			}
			if(row%2==0)
			   r--;
			secondBandDa->nextRow();
		}


		//band 1 Green
		for(row=0,r=0;row<S.iheight;row++,r++)
		{
			for(col=0,c=0;col<S.iwidth;col++,c++)
			{
			   if(row%2==0)  //RG row
			   {
			    if(col%2!=0) //Green pixel
				{
					ptr=reinterpret_cast<unsigned short*>(thirdBandDa->getColumn());
				    *ptr=pData[c+(r*S.iwidth)+(1*S.iheight*S.iwidth)]; //g1
			     }
			    else
			    {
				   *ptr=0;
				   c--;
			    }
			   }
			   else  //GB row
			   {
				   if(col%2==0) //Green pixel
				{
					ptr=reinterpret_cast<unsigned short*>(thirdBandDa->getColumn());
				    *ptr=pData[c+(r*S.iwidth)+(3*S.iheight*S.iwidth)]; //g2
			     }
			    else
			    {
				   *ptr=0;
				   c--;
			    }
				   
			   }
			    thirdBandDa->nextColumn();
			   
			}
			
			thirdBandDa->nextRow();
		}


			
	if (createView() == NULL)
    {
      return false;
    }
	

	RawProcessor.recycle();
   
   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;
}
Beispiel #13
0
void SamThread::ComputeSam(const T* pDummyData)
{
   int reSamBan_index = 0, row_index = 0, col_index = 0;
   float* pResultsData = NULL;
   int oldPercentDone = -1;
   double spectrumMag = 0.0;
   const T* pData=NULL;
   const RasterDataDescriptor* pDescriptor = static_cast<const RasterDataDescriptor*>(
      mInput.mpCube->getDataDescriptor());
   unsigned int numCols = pDescriptor->getColumnCount();
   unsigned int numBands = pDescriptor->getBandCount();
   unsigned int numRows = (mRowRange.mLast - mRowRange.mFirst + 1);

   int numResultsCols = 0;
   //Sets area to apply the SAM algortihm to. Either
   //the entire cube, or a selected ROI.
   if (mInput.mIterCheck.useAllPixels())
   {
      //Total number of Columns in cube.
      numResultsCols = numCols;
   }
   else
   {
      numResultsCols = mInput.mIterCheck.getNumSelectedColumns();
   }

   if (mInput.mpResultsMatrix == NULL)
   {
      return;
   }

   const RasterDataDescriptor* pResultDescriptor = static_cast<const RasterDataDescriptor*>(
      mInput.mpResultsMatrix->getDataDescriptor());
   // Gets results matrix that was initialized in ProcessAll()
   mRowRange.mFirst = std::max(0, mRowRange.mFirst);
   mRowRange.mLast = std::min(mRowRange.mLast, static_cast<int>(pDescriptor->getRowCount()) - 1);
   FactoryResource<DataRequest> pResultRequest;
   pResultRequest->setRows(pResultDescriptor->getActiveRow(mRowRange.mFirst),
      pResultDescriptor->getActiveRow(mRowRange.mLast));
   pResultRequest->setColumns(pResultDescriptor->getActiveColumn(0),
      pResultDescriptor->getActiveColumn(numResultsCols - 1));
   pResultRequest->setWritable(true);
   DataAccessor resultAccessor = mInput.mpResultsMatrix->getDataAccessor(pResultRequest.release());
   if (!resultAccessor.isValid())
   {
      return;
   }

   // Resamples and sets search signature 
   for (reSamBan_index = 0; reSamBan_index < (int) mInput.mResampledBands.size(); ++reSamBan_index)
   {
      spectrumMag += mInput.mSpectrum[reSamBan_index] * mInput.mSpectrum[reSamBan_index];
   }

   spectrumMag = sqrt(spectrumMag);
   int rowOffset = mInput.mIterCheck.getOffset().mY;
   int startRow = (mRowRange.mFirst + rowOffset);
   int stopRow = (mRowRange.mLast + rowOffset);

   int columnOffset = mInput.mIterCheck.getOffset().mX;
   int startColumn = columnOffset;
   int stopColumn = (numResultsCols + columnOffset - 1);

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BIP);
   pRequest->setRows(pDescriptor->getActiveRow(startRow), pDescriptor->getActiveRow(stopRow));
   pRequest->setColumns(pDescriptor->getActiveColumn(startColumn), pDescriptor->getActiveColumn(stopColumn));
   DataAccessor accessor = mInput.mpCube->getDataAccessor(pRequest.release());
   if (!accessor.isValid())
   {
      return;
   }

   for (row_index = startRow; row_index <= stopRow; ++row_index)
   {
      int percentDone = mRowRange.computePercent(row_index-rowOffset);
      if (percentDone > oldPercentDone)
      {
         oldPercentDone = percentDone;
         getReporter().reportProgress(getThreadIndex(), percentDone);
      }
      if (mInput.mpAbortFlag != NULL && *mInput.mpAbortFlag)
      {
         break;
      }

      for (col_index = startColumn; col_index <= stopColumn; ++col_index)
      {  
         VERIFYNRV(resultAccessor.isValid());
         VERIFYNRV(accessor.isValid());
         // Pointer to results data
         pResultsData = reinterpret_cast<float*>(resultAccessor->getColumn());
         if (pResultsData == NULL)
         {
            return;
         }
         if (mInput.mIterCheck.getPixel(col_index, row_index))
         {
            //Pointer to cube/sensor data
            pData = reinterpret_cast<T*>(accessor->getColumn());
            VERIFYNRV(pData != NULL);
            *pResultsData = 0.0f;
            double pixelMag = 0.0;
            double angle =0.0;

            //Calculates Spectral Angle and Magnitude at current location
            for (unsigned int reSam_index = 0; 
               reSam_index < mInput.mResampledBands.size(); ++reSam_index)
            {
               int resampledBand = mInput.mResampledBands[reSam_index];
               double cubeVal = pData[resampledBand];
               angle += cubeVal * mInput.mSpectrum[reSam_index];
               pixelMag += cubeVal * cubeVal;
            }
            pixelMag = sqrt(pixelMag);
            if (pixelMag != 0.0 && spectrumMag != 0.0)
            {
               angle /= (pixelMag * spectrumMag);
               if (angle < -1.0)
               {
                  angle = -1.0;
               }
               if (angle > 1.0)
               {
                  angle = 1.0;
               }

               angle = (180.0 / 3.141592654) * acos(angle);
               *pResultsData = angle;
            }
            else
            {
               *pResultsData = 181.0;
            }
         }
         else
         {
            *pResultsData = 181.0;
         }
         //Increment Columns
         resultAccessor->nextColumn();
         accessor->nextColumn();
      }
      //Increment Rows
      resultAccessor->nextRow();
      accessor->nextRow();
   }
}
bool conservative_filter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Conservative", "Filter", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD55"); //what is this?
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }

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

   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   
	VERIFY(pDesc != NULL);

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

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

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

   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Applying Conservative Filter", row * 100 / pDesc->getRowCount(), NORMAL);
      }
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }
         return false;
      }
      if (!pDestAcc.isValid())
      {
         std::string msg = "Unable to access the cube data.";
         pStep->finalize(Message::Failure, msg);
         if (pProgress != NULL) 
         {
            pProgress->updateProgress(msg, 0, ERRORS);
         }
         return false;
      }
      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), verifyRange, pDestAcc->getColumn(), pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), radius);
         pDestAcc->nextColumn();
      }
      pDestAcc->nextRow();
   }

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

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

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

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

   if (pProgress != NULL)
   {
      pProgress->updateProgress("COnservative Filter is complete", 100, NORMAL);
   }

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

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

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

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

   

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


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

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


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


   double look_table1[24][6];

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


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

   

   if (PFA==0.0000001)
   {
	    

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

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

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

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

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

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

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

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

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

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

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

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

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

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

         return false;
      }

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

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

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

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

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


					pAcc2->nextColumn();

				}

				pAcc2->nextRow();
			}

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

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

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

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

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

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

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

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


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

			if(zstatistic>threshold)
			{

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

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

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



			pAcc->nextColumn();
	  }

      pAcc->nextRow();

   }



      // Create a GCP layer

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

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


      Service<DesktopServices> pDesktop;

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

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

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


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


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

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

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

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

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

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

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

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

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

            pGcpList->addPoints(gcps);

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

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

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

   pStep->finalize();
   return true;
   
}
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;
}
void PseudocolorLayerImp::draw()
{
   RasterElement* pRasterElement = dynamic_cast<RasterElement*>(getDataElement());
   if (pRasterElement != NULL)
   {
      if (canRenderAsImage())
      {
         generateImage();
         VERIFYNRV(mpImage != NULL);

         mpImage->draw(GL_NEAREST);
      }
      else
      {
         DataAccessor accessor(NULL, NULL);
         bool usingRawData = false;

         int columns = 0;
         int rows = 0;
         EncodingType eType;
         void* pData = NULL;

         const RasterDataDescriptor* pDescriptor =
            dynamic_cast<const RasterDataDescriptor*>(pRasterElement->getDataDescriptor());
         if (pDescriptor != NULL)
         {
            columns = static_cast<int>(pDescriptor->getColumnCount());
            rows = static_cast<int>(pDescriptor->getRowCount());
            eType = pDescriptor->getDataType();
         }

         // There is an optimization when the full scene can be processed at once.
         // Check for if it can be done
         if (pDescriptor->getBandCount() == 1 || pDescriptor->getInterleaveFormat() == BSQ)
         {
            usingRawData = true;
            pData = pRasterElement->getRawData();
         }
         if (pData == NULL)
         {
            FactoryResource<DataRequest> pRequest;
            pRequest->setInterleaveFormat(BSQ);
            accessor = pRasterElement->getDataAccessor(pRequest.release());
         }

         SymbolType eSymbol = getSymbol();

         int visStartColumn = 0;
         int visEndColumn = columns - 1;
         int visStartRow = 0;
         int visEndRow = rows - 1;
         DrawUtil::restrictToViewport(visStartColumn, visStartRow, visEndColumn, visEndRow);

         QMap<int, PseudocolorClass*>::Iterator iter = mClasses.begin();
         while (iter != mClasses.end())
         {
            PseudocolorClass* pClass = iter.value();
            if (pClass != NULL)
            {
               if (pClass->isDisplayed())
               {
                  QColor clrMarker = pClass->getColor();

                  if (usingRawData) // all data in memory
                  {
                     switchOnEncoding(eType, drawPseudocolorMarkers, pData, columns - 1, rows - 1, visStartColumn,
                        visStartRow, visEndColumn, visEndRow, eSymbol, clrMarker, pClass->getValue());
                  }
                  else
                  {
                     for (int row = 0; row < rows; ++row)
                     {
                        if (!accessor.isValid())
                        {
                           break;
                        }

                        pData = accessor->getColumn();
                        switchOnEncoding(eType, drawPseudocolorMarkers, pData, columns - 1, row, visStartColumn,
                           row, visEndColumn, row, eSymbol, clrMarker, pClass->getValue(), row);
                        accessor->nextRow();
                     }
                     accessor->toPixel(0, 0);
                  }
               }
            }

            iter++;
         }
      }
   }
}
Beispiel #18
0
vector<ImportDescriptor*> EnviImporter::getImportDescriptors(const string& filename)
{
   string headerFile = filename;
   string dataFile;
   bool bSuccess = parseHeader(headerFile);
   if (bSuccess == false)
   {
      dataFile = filename;           // was passed data file name instead of header file name
      headerFile = findHeaderFile(headerFile);
      if (headerFile.empty() == false)
      {
         bSuccess = parseHeader(headerFile);
      }
   }

   EnviField* pField = NULL;
   vector<ImportDescriptor*> descriptors;
   if (bSuccess == true)
   {
      if (dataFile.empty() == true)  // was passed header file name and now need to find the data file name
      {
         dataFile = findDataFile(headerFile);
      }

      if (dataFile.empty() == false)
      {
         ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(dataFile, "RasterElement", NULL);
         if (pImportDescriptor != NULL)
         {
            RasterDataDescriptor* pDescriptor =
               dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
            if (pDescriptor != NULL)
            {
               FactoryResource<RasterFileDescriptor> pFileDescriptor;
               if (pFileDescriptor.get() != NULL)
               {
                  // Filename
                  pFileDescriptor->setFilename(dataFile);

                  // Coordinate offset
                  int columnOffset = 0;
                  int rowOffset = 0;

                  pField = mFields.find("x start");
                  if (pField != NULL)
                  {
                     // ENVI numbers are 1 based vs Opticks being 0 based
                     columnOffset = atoi(pField->mValue.c_str()) - 1;
                  }

                  pField = mFields.find("y start");
                  if (pField != NULL)
                  {
                     rowOffset = atoi(pField->mValue.c_str()) - 1; // ENVI numbers are 1 based vs Opticks being 0 based
                  }

                  // Rows
                  vector<DimensionDescriptor> rows;
                  pField = mFields.find("lines");
                  if (pField != NULL)
                  {
                     int numRows = atoi(pField->mValue.c_str());
                     for (int i = 0; i < numRows; ++i)
                     {
                        DimensionDescriptor rowDim;
                        rowDim.setOriginalNumber(static_cast<unsigned int>(rowOffset + i));
                        rowDim.setOnDiskNumber(static_cast<unsigned int>(i));
                        rows.push_back(rowDim);
                     }

                     pDescriptor->setRows(rows);
                     pFileDescriptor->setRows(rows);
                  }

                  string samplesStr = "samples";
                  string bandsStr = "bands";

                  // Special case: if the file type is an ENVI Spectral Library, then swap samples with bands
                  // If no file type field exists, assume this is a normal ENVI header (not a Spectral Library)
                  EnviField* pFileTypeField = mFields.find("file type");
                  if (pFileTypeField != NULL && (pFileTypeField->mValue ==
                     "ENVI Spectral Library" || pFileTypeField->mValue == "Spectral Library"))
                  {
                     samplesStr = "bands";
                     bandsStr = "samples";

                     // Since bands and samples are swapped, force the interleave to BIP
                     pField = mFields.find("interleave");
                     if (pField != NULL)
                     {
                        pField->mValue = "bip";
                     }
                  }

                  // Columns
                  vector<DimensionDescriptor> columns;
                  pField = mFields.find(samplesStr);
                  if (pField != NULL)
                  {
                     int numColumns = atoi(pField->mValue.c_str());
                     for (int i = 0; i < numColumns; ++i)
                     {
                        DimensionDescriptor columnDim;
                        columnDim.setOriginalNumber(static_cast<unsigned int>(columnOffset + i));
                        columnDim.setOnDiskNumber(static_cast<unsigned int>(i));
                        columns.push_back(columnDim);
                     }

                     pDescriptor->setColumns(columns);
                     pFileDescriptor->setColumns(columns);
                  }

                  // Bands
                  vector<DimensionDescriptor> bands;
                  pField = mFields.find(bandsStr);
                  if (pField != NULL)
                  {
                     int numBands = atoi(pField->mValue.c_str());
                     bands = RasterUtilities::generateDimensionVector(numBands, true, false, true);
                     pDescriptor->setBands(bands);
                     pFileDescriptor->setBands(bands);
                  }

                  // Description
                  list<GcpPoint> gcps;

                  pField = mFields.find("description");
                  if (pField != NULL)
                  {
                     // Metadata
                     if (pField->mChildren.empty() == false)
                     {
                        FactoryResource<DynamicObject> pMetadata;
                        for (unsigned int i = 0; i < pField->mChildren.size(); ++i)
                        {
                           EnviField* pChild = pField->mChildren[i];
                           if (pChild != NULL)
                           {
                              if (pChild->mTag == "classification")
                              {
                                 // Classification
                                 FactoryResource<Classification> pClassification;
                                 if (pClassification.get() != NULL)
                                 {
                                    string classLevel;
                                    classLevel.append(1, *(pChild->mValue.data()));
                                    pClassification->setLevel(classLevel);

                                    pDescriptor->setClassification(pClassification.get());
                                 }
                              }
                              else if ((pChild->mTag == "ll") || (pChild->mTag == "lr") || (pChild->mTag == "ul") ||
                                 (pChild->mTag == "ur") || (pChild->mTag == "center"))
                              {
                                 GcpPoint gcp;
                                 bool dmsFormat = false;
                                 char ns;
                                 char ew;

                                 sscanf(pChild->mValue.c_str(), "%lg%c %lg%c", &gcp.mCoordinate.mY, &ew,
                                    &gcp.mCoordinate.mX, &ns);
                                 if (fabs(gcp.mCoordinate.mY) > 180.0 || fabs(gcp.mCoordinate.mX) > 90.0)
                                 {
                                    dmsFormat = true;
                                 }

                                 double deg;
                                 double min;
                                 double sec;
                                 if (dmsFormat == true)
                                 {
                                    deg = static_cast<int>(gcp.mCoordinate.mY / 10000.0);
                                    min = static_cast<int>((gcp.mCoordinate.mY - 10000.0 * deg) / 100.0);
                                    sec = gcp.mCoordinate.mY - 10000.0 * deg - 100.0 * min;
                                    gcp.mCoordinate.mY = deg + (min / 60.0) + (sec / 3600.0);
                                 }

                                 if (ew == 'W' || ew == 'w')
                                 {
                                    gcp.mCoordinate.mY = -gcp.mCoordinate.mY;
                                 }

                                 if (dmsFormat)
                                 {
                                    deg = static_cast<int>(gcp.mCoordinate.mX / 10000.0);
                                    min = static_cast<int>((gcp.mCoordinate.mX - 10000.0 * deg) / 100.0);
                                    sec = gcp.mCoordinate.mX - 10000.0 * deg - 100.0 * min;
                                    gcp.mCoordinate.mX = deg + (min / 60.0) + (sec / 3600.0);
                                 }

                                 if (ns == 'S' || ns == 's')
                                 {
                                    gcp.mCoordinate.mX = -gcp.mCoordinate.mX;
                                 }

                                 // ENVI uses a 1-based pixel coordinate system, with each coordinate referring
                                 // to the top-left corner of the pixel, e.g. (1,1) is the top-left
                                 // corner of the pixel in the top-left of the raster cube
                                 // The ENVI pixel coordinate format is described on p. 1126 of the ENVI 4.2 User's Guide
                                 if (pChild->mTag == "ll")
                                 {
                                    gcp.mPixel.mX = 0.0;
                                    gcp.mPixel.mY = 0.0;
                                 }
                                 else if (pChild->mTag == "lr")
                                 {
                                    gcp.mPixel.mX = columns.size() - 1.0;
                                    gcp.mPixel.mY = 0.0;
                                 }
                                 else if (pChild->mTag == "ul")
                                 {
                                    gcp.mPixel.mX = 0.0;
                                    gcp.mPixel.mY = rows.size() - 1.0;
                                 }
                                 else if (pChild->mTag == "ur")
                                 {
                                    gcp.mPixel.mX = columns.size() - 1.0;
                                    gcp.mPixel.mY = rows.size() - 1.0;
                                 }
                                 else if (pChild->mTag == "center")
                                 {
                                    gcp.mPixel.mX = floor((columns.size() - 1.0) / 2.0);
                                    gcp.mPixel.mY = floor((rows.size() - 1.0) / 2.0);
                                 }

                                 gcps.push_back(gcp);
                              }
                              else if (pChild->mTag.empty() == false)
                              {
                                 pMetadata->setAttribute(pChild->mTag, pChild->mValue);
                              }
                           }
                        }

                        if (pMetadata->getNumAttributes() > 0)
                        {
                           pDescriptor->setMetadata(pMetadata.get());
                        }
                     }
                  }

                  if (gcps.empty())  // not in description, check for geo points keyword
                  {
                     pField = mFields.find("geo points");
                     if (pField != NULL)
                     {
                        vector<double> geoValues;
                        const int expectedNumValues = 16;  // 4 values for each of the 4 corners
                        geoValues.reserve(expectedNumValues);
                        for (unsigned int i = 0; i < pField->mChildren.size(); i++)
                        {
                           vectorFromField(pField->mChildren.at(i), geoValues, "%lf");
                        }

                        if (geoValues.size() == expectedNumValues)
                        {
                           vector<double>::iterator iter = geoValues.begin();
                           GcpPoint gcp;
                           while (iter != geoValues.end())
                           {
                              gcp.mPixel.mX = *iter++ - 1.0;  // adjust ref point for ENVI's use of
                              gcp.mPixel.mY = *iter++ - 1.0;  // upper left corner and one-based first pixel
                              gcp.mCoordinate.mX = *iter++;   // GcpPoint has lat as mX and Lon as mY 
                              gcp.mCoordinate.mY = *iter++;   // geo point field has lat then lon value
                              gcps.push_back(gcp);
                           }
                        }
                     }
                  }

                  // GCPs
                  if (gcps.empty() == false)
                  {
                     pFileDescriptor->setGcps(gcps);
                  }

                  // Header bytes
                  pField = mFields.find("header offset");
                  if (pField != NULL)
                  {
                     int headerBytes = atoi(pField->mValue.c_str());
                     pFileDescriptor->setHeaderBytes(static_cast<unsigned int>(headerBytes));
                  }

                  // Data type
                  pField = mFields.find("data type");
                  if (pField != NULL)
                  {
                     vector<EncodingType> validDataTypes;
                     switch (atoi(pField->mValue.c_str()))
                     {
                        case 1:     // char
                           pDescriptor->setDataType(INT1UBYTE);
                           pFileDescriptor->setBitsPerElement(8);
                           
                           // signed char cannot be represented in ENVI header so use the closest thing
                           validDataTypes.push_back(INT1SBYTE);
                           break;

                        case 2:     // short
                           pDescriptor->setDataType(INT2SBYTES);
                           pFileDescriptor->setBitsPerElement(16);
                           break;

                        case 3:     // int
                           pDescriptor->setDataType(INT4SBYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 4:     // float
                           pDescriptor->setDataType(FLT4BYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 5:     // double
                           pDescriptor->setDataType(FLT8BYTES);
                           pFileDescriptor->setBitsPerElement(64);
                           break;

                        case 6:     // float complex
                           pDescriptor->setDataType(FLT8COMPLEX);
                           pFileDescriptor->setBitsPerElement(64);
                           break;

                        case 9:     // double complex
                           // not supported
                           break;

                        case 12:    // unsigned short
                           pDescriptor->setDataType(INT2UBYTES);
                           pFileDescriptor->setBitsPerElement(16);
                           break;

                        case 13:    // unsigned int
                           pDescriptor->setDataType(INT4UBYTES);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        case 14:    // 64-bit int
                        case 15:    // unsigned 64-bit int
                           // not supported
                           break;

                        case 99:    // integer complex (recognized only by this application)
                           pDescriptor->setDataType(INT4SCOMPLEX);
                           pFileDescriptor->setBitsPerElement(32);
                           break;

                        default:
                           break;
                     }

                     // Bad values
                     EncodingType dataType = pDescriptor->getDataType();
                     if ((dataType != FLT4BYTES) && (dataType != FLT8COMPLEX) && (dataType != FLT8BYTES))
                     {
                        vector<int> badValues;
                        badValues.push_back(0);

                        pDescriptor->setBadValues(badValues);
                     }

                     validDataTypes.push_back(dataType);
                     pDescriptor->setValidDataTypes(validDataTypes);
                  }

                  // Interleave format
                  pField = mFields.find("interleave");
                  if (pField != NULL)
                  {
                     string interleave = StringUtilities::toLower(pField->mValue);
                     if (interleave == "bip")
                     {
                        pDescriptor->setInterleaveFormat(BIP);
                        pFileDescriptor->setInterleaveFormat(BIP);
                     }
                     else if (interleave == "bil")
                     {
                        pDescriptor->setInterleaveFormat(BIL);
                        pFileDescriptor->setInterleaveFormat(BIL);
                     }
                     else if (interleave == "bsq")
                     {
                        pDescriptor->setInterleaveFormat(BSQ);
                        pFileDescriptor->setInterleaveFormat(BSQ);
                     }
                  }

                  // Endian
                  pField = mFields.find("byte order");
                  if (pField != NULL)
                  {
                     int byteOrder = atoi(pField->mValue.c_str());
                     if (byteOrder == 0)
                     {
                        pFileDescriptor->setEndian(LITTLE_ENDIAN_ORDER);
                     }
                     else if (byteOrder == 1)
                     {
                        pFileDescriptor->setEndian(BIG_ENDIAN_ORDER);
                     }
                  }

                  // check for scaling factor
                  pField = mFields.find("reflectance scale factor");
                  if (pField != NULL)
                  {
                     double scalingFactor = 0.0;
                     stringstream scaleStream(pField->mValue);
                     scaleStream >> scalingFactor;
                     if (!scaleStream.fail() && scalingFactor != 0.0)
                     {
                        Units* pUnits = pDescriptor->getUnits();
                        if (pUnits != NULL)
                        {
                           pUnits->setScaleFromStandard(1.0 / scalingFactor);
                           pUnits->setUnitName("Reflectance");
                           pUnits->setUnitType(REFLECTANCE);
                        }
                     }
                  }

                  // Pixel size
                  pField = mFields.find("pixel size");
                  if (pField != NULL)
                  {
                     if (pField->mChildren.size() == 2)
                     {
                        pField = pField->mChildren[0];
                        if (pField != NULL)
                        {
                           double pixelSize = 1.0;
                           if (sscanf(pField->mValue.c_str(), "%g", &pixelSize) == 1)
                           {
                              pDescriptor->setXPixelSize(pixelSize);
                              pFileDescriptor->setXPixelSize(pixelSize);
                           }
                        }

                        pField = pField->mChildren[1];
                        if (pField != NULL)
                        {
                           double pixelSize = 1.0;
                           if (sscanf(pField->mValue.c_str(), "%g", &pixelSize) == 1)
                           {
                              pDescriptor->setYPixelSize(pixelSize);
                              pFileDescriptor->setYPixelSize(pixelSize);
                           }
                        }
                     }
                  }

                  // Default bands
                  pField = mFields.find("default bands");
                  if (pField != NULL)
                  {
                     vector<unsigned int> displayBands;
                     parseDefaultBands(pField, &displayBands);

                     if (displayBands.size() == 1)
                     {
                        DimensionDescriptor grayBand = pFileDescriptor->getOriginalBand(displayBands[0]);

                        pDescriptor->setDisplayBand(GRAY, grayBand);
                        pDescriptor->setDisplayMode(GRAYSCALE_MODE);
                     }
                     else if (displayBands.size() == 3)
                     {
                        DimensionDescriptor redBand = pFileDescriptor->getOriginalBand(displayBands[0]);
                        DimensionDescriptor greenBand = pFileDescriptor->getOriginalBand(displayBands[1]);
                        DimensionDescriptor blueBand = pFileDescriptor->getOriginalBand(displayBands[2]);

                        pDescriptor->setDisplayBand(RED, redBand);
                        pDescriptor->setDisplayBand(GREEN, greenBand);
                        pDescriptor->setDisplayBand(BLUE, blueBand);
                        pDescriptor->setDisplayMode(RGB_MODE);
                     }
                  }

                  // Bad bands
                  pField = mFields.find("bbl");
                  if (pField != NULL)
                  {
                     vector<unsigned int> validBands;
                     parseBbl(pField, validBands);

                     vector<DimensionDescriptor> bandsToLoad;
                     for (vector<unsigned int>::const_iterator iter = validBands.begin();
                        iter != validBands.end();
                        ++iter)
                     {
                        const unsigned int onDiskNumber = *iter;
                        const DimensionDescriptor dim = pFileDescriptor->getOnDiskBand(onDiskNumber);
                        if (dim.isValid())
                        {
                           bandsToLoad.push_back(dim);
                        }
                     }

                     pDescriptor->setBands(bandsToLoad);
                  }

                  DynamicObject* pMetadata = pDescriptor->getMetadata();

                  // Band names
                  pField = mFields.find("band names");
                  if (pField != NULL)
                  {
                     vector<string> bandNames;
                     bandNames.reserve(bands.size());
                     vector<string> strNames;
                     for (vector<EnviField*>::size_type i = 0; i < pField->mChildren.size(); ++i)
                     {
                        strNames = StringUtilities::split(pField->mChildren[i]->mValue, ',');
                        copy(strNames.begin(), strNames.end(), back_inserter(bandNames));
                     }
                     vector<string>::iterator it;
                     for (it = bandNames.begin(); it != bandNames.end(); ++it)
                     {
                        *it = StringUtilities::stripWhitespace(*it);
                     }

                     if (pMetadata != NULL)
                     {
                        string pNamesPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           NAMES_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pNamesPath, bandNames);
                     }
                  }

                  // wavelength units
                  pField = mFields.find("wavelength units");
                  if (pField != NULL)
                  {
                     mWavelengthUnits = strToType(pField->mValue);
                  }

                  // Wavelengths
                  vector<double> centerWavelengths;
                  pField = mFields.find("wavelength");
                  if (pField != NULL)
                  {
                     if ((parseWavelengths(pField, &centerWavelengths) == true) && (pMetadata != NULL))
                     {
                        string pCenterPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           CENTER_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pCenterPath, centerWavelengths);
                     }
                  }

                  // FWHM
                  pField = mFields.find("fwhm");
                  if (pField != NULL)
                  {
                     vector<double> startWavelengths;
                     vector<double> endWavelengths;

                     if ((parseFwhm(pField, &startWavelengths, &centerWavelengths, &endWavelengths) == true) &&
                        (pMetadata != NULL))
                     {
                        string pStartPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           START_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pStartPath, startWavelengths);
                        string pEndPath[] = { SPECIAL_METADATA_NAME, BAND_METADATA_NAME,
                           END_WAVELENGTHS_METADATA_NAME, END_METADATA_NAME };
                        pMetadata->setAttributeByPath(pEndPath, endWavelengths);
                     }
                  }

                  // File descriptor
                  pDescriptor->setFileDescriptor(pFileDescriptor.get());
               }
Beispiel #19
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;
}
vector<ImportDescriptor*> SampleHdf4Importer::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;

   Hdf4File parsedFile(filename);
   bool bSuccess = getFileData(parsedFile);
   if (bSuccess == true)
   {
      const Hdf4Dataset* pDataset =
         dynamic_cast<const Hdf4Dataset*>(parsedFile.getRootGroup()->getElement("EV_500_RefSB"));
      if ((pDataset != NULL) && (mpModel.get() != NULL))
      {
         Hdf4FileResource pFile(filename.c_str());
         if (pFile.get() != NULL)
         {
            ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "RasterElement", NULL);
            if (pImportDescriptor != NULL)
            {
               RasterDataDescriptor* pDescriptor =
                  dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
               if (pDescriptor != NULL)
               {
                  FactoryResource<RasterFileDescriptor> pFileDescriptor;
                  if (pFileDescriptor.get() != NULL)
                  {
                     int32 numDims = 0;
                     int32 dataType = 0;
                     int32 numAttr = 0;

                     pFileDescriptor->setFilename(filename);

                     Hdf4DatasetResource pDataHandle(*pFile, pDataset->getName().c_str());
                     int32 dimSizes[MAX_VAR_DIMS] = {0};
                     if (pDataHandle != NULL && *pDataHandle != FAIL)
                     {
                        pFileDescriptor->setDatasetLocation(pDataset->getName());

                        int32 success = SDgetinfo(*pDataHandle, const_cast<char*>(pDataset->getName().c_str()),
                                                  &numDims, dimSizes, &dataType, &numAttr);
                        // find out what type this Dataset is
                        string strDataType = hdf4TypeToString(dataType, 1);
                        if (success == SUCCEED && numDims == 3 && strDataType == "unsigned short")
                        {
                           // Bands
                           vector<DimensionDescriptor> bands =
                              RasterUtilities::generateDimensionVector(dimSizes[0], true, false, true);

                           pDescriptor->setBands(bands);
                           pFileDescriptor->setBands(bands);

                           // Rows
                           vector<DimensionDescriptor> rows =
                              RasterUtilities::generateDimensionVector(dimSizes[1], true, false, true);

                           pDescriptor->setRows(rows);
                           pFileDescriptor->setRows(rows);

                           // Columns
                           vector<DimensionDescriptor> columns =
                              RasterUtilities::generateDimensionVector(dimSizes[2], true, false, true);

                           pDescriptor->setColumns(columns);
                           pFileDescriptor->setColumns(columns);
                        }
                     }

                     // Data type
                     EncodingType e;
                     pDataset->getDataEncoding(e);
                     pDescriptor->setDataType(e);
                     pFileDescriptor->setBitsPerElement(pDescriptor->getBytesPerElement() * 8);

                     // Interleave format
                     pDescriptor->setInterleaveFormat(BSQ);
                     pFileDescriptor->setInterleaveFormat(BSQ);

                     // Metadata
                     FactoryResource<DynamicObject> pMetadata;
                     if (pMetadata.get() != NULL)
                     {
                        const Hdf4Dataset::AttributeContainer& attributes = pDataset->getAttributes();
                        for (Hdf4Dataset::AttributeContainer::const_iterator it = attributes.begin();
                           it != attributes.end(); ++it)
                        {
                           Hdf4Attribute* pAttribute = it->second;
                           if (pAttribute != NULL)
                           {
                              const string& name = pAttribute->getName();
                              const DataVariant& var = pAttribute->getVariant();
                              const unsigned short* pValue = var.getPointerToValue<unsigned short>();
                              if (name == "_FillValue" && pValue != NULL)
                              {
                                 // Bad values
                                 vector<int> badValues;
                                 badValues.push_back(*pValue);

                                 pDescriptor->setBadValues(badValues);
                              }
                              else
                              {
                                 pMetadata->setAttribute(name, var);
                              }
                           }
                        }

                        pDescriptor->setMetadata(pMetadata.get());
                     }
                     pDescriptor->setFileDescriptor(pFileDescriptor.get());
                  }
               }

               descriptors.push_back(pImportDescriptor);
            }
         }
      }
   }

   return descriptors;
}
Beispiel #21
0
bool Tutorial3::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Tutorial 3", "app", "27170298-10CE-4E6C-AD7A-97E8058C29FF");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL)
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }

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

   FactoryResource<DataRequest> pRequest;
   pRequest->setInterleaveFormat(BSQ);
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());
   double min = std::numeric_limits<double>::max();
   double max = -min;
   double total = 0.0;
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
      if (isAborted())
      {
         std::string msg = getName() + " has been aborted.";
         pStep->finalize(Message::Abort, msg);
         if (pProgress != NULL)
         {
            pProgress->updateProgress(msg, 0, ABORT);
         }

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

         return false;
      }

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

      for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
         switchOnEncoding(pDesc->getDataType(), updateStatistics, pAcc->getColumn(), min, max, total);
         pAcc->nextColumn();
      }
      pAcc->nextRow();
   }
   unsigned int count = pDesc->getColumnCount() * pDesc->getRowCount();
   double mean = total / count;

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

   pStep->finalize();
   return true;
}
Beispiel #22
0
bool BandMath::execute(PlugInArgList* pInputArgList, PlugInArgList* pOutputArgList)
{
   StepResource pStep("Start BandMath", "app", "02E18066-1355-4a5f-ABC5-0366D9890C1C");
   mpStep = pStep.get();

   // Initilize variables
   initialize();

   // Get pointers
   // parse arg in list
   if (!parse(pInputArgList, pOutputArgList))
   {
      meGabbiness = ERRORS;
      displayErrorMessage();
      return false;
   }

   // Get important stuff
   pStep->addProperty("Dataset", mpCube->getFilename());

   const RasterDataDescriptor* pDescriptor = dynamic_cast<const RasterDataDescriptor*>(mpCube->getDataDescriptor());
   if (pDescriptor != NULL)
   {
      mCubeRows = pDescriptor->getRowCount();
      mCubeColumns = pDescriptor->getColumnCount();
      mCubeBands = pDescriptor->getBandCount();
   }

   std::string tmpResultName;

   vector<DataElement*> elements = mpDataModel->getElements("RasterElement");

   vector<DataElement*>::iterator iter;
   for (iter = elements.begin(); iter != elements.end(); ++iter)
   {
      RasterElement* pRaster = static_cast<RasterElement*>(*iter);
      if (pRaster != NULL)
      {
         const RasterDataDescriptor* pCurrentDescriptor =
            dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor());
         if (pCurrentDescriptor != NULL)
         {
            if ((mCubeRows == static_cast<int>(pCurrentDescriptor->getRowCount())) &&
               (mCubeColumns == static_cast<int>(pCurrentDescriptor->getColumnCount())) &&
               (mCubeBands == static_cast<int>(pCurrentDescriptor->getBandCount())))
            {
               mCubesList.push_back(pRaster);
            }
         }
      }
   }

   char errorVal[80];
   int errorCode = -1;  

   if (mbInteractive)
   {
      QWidget* pParent = mpDesktop->getMainWidget();

      FrmBM frmASIT(pDescriptor, mCubesList, pParent);

      if (frmASIT.exec() == QDialog::Rejected)
      {
         pStep->finalize(Message::Abort);
         return false;
      }

      mExpression = frmASIT.getExpression(true).toStdString();
      mbDegrees = frmASIT.isDegrees();
      mbCubeMath = frmASIT.isMultiCube();
      mbAsLayerOnExistingView = frmASIT.isResultsMatrix();
   }
   else
   {
      mbCubeMath = false;

      //check for cube math
      unsigned int pos = mExpression.find_first_of(string("cC"));
      if ((pos >= 0) && (pos < (mExpression.length() - 1)) && ((mExpression[pos + 1] > '0') &&
                                                              (mExpression[pos + 1] < '9')))
      {
         mbCubeMath = true;
      }
   }
   if (!createReturnValue(mExpression))
   {
      mstrProgressString = "Could not allocate space for results.";
      meGabbiness = ERRORS;
      displayErrorMessage();
      return false;
   }
   {
      StepResource pResultStep("Compute result", "app", "CDCC12AC-32DD-4831-BC6B-225538C92053");
      mpStep = pResultStep.get();
      pResultStep->addProperty("Expression", mExpression);

      FactoryResource<DataRequest> pReturnRequest;
      pReturnRequest->setInterleaveFormat(BIP);
      pReturnRequest->setWritable(true);
      DataAccessor returnDa = mpResultData->getDataAccessor(pReturnRequest.release());
      if (!returnDa.isValid())
      {
         mstrProgressString = "Could not access the result data.";
         meGabbiness = ERRORS;
         displayErrorMessage();
         return false;
      }

      if (!mbCubeMath)
      {
         FactoryResource<DataRequest> pCubeRequest;
         pCubeRequest->setInterleaveFormat(BIP);
         DataAccessor cubeDa = mpCube->getDataAccessor(pCubeRequest.release());
         if (!cubeDa.isValid())
         {
            mstrProgressString = "Reading this cube format is not supported.";
            meGabbiness = ERRORS;
            displayErrorMessage();
            return false;
         }

         vector<DataAccessor> accessors(1, cubeDa);
         vector<EncodingType> types(1, pDescriptor->getDataType());

         char* mutableExpression = new char[mExpression.size() + 1];
         strcpy(mutableExpression, mExpression.c_str());

         errorCode = eval(mpProgress, accessors, types, mCubeRows, mCubeColumns,
            mCubeBands, mutableExpression, returnDa, mbDegrees, errorVal, mbCubeMath, mbInteractive);

         delete [] mutableExpression;
      }
      else // cube math
      {
         EncodingType type = pDescriptor->getDataType();

         vector<DataAccessor> accessors;
         vector<EncodingType> dataTypes;
         for (unsigned int i = 0; i < mCubesList.size(); ++i)
         {
            FactoryResource<DataRequest> pRequest;
            pRequest->setInterleaveFormat(BIP);
            DataAccessor daCube = mCubesList[i]->getDataAccessor(pRequest.release());
            accessors.push_back(daCube);
            const RasterDataDescriptor* pDdCube = dynamic_cast<RasterDataDescriptor*>(mCubesList.at(i)->
               getDataDescriptor());
            if (pDdCube != NULL)
            {
               dataTypes.push_back(pDdCube->getDataType());
            }
            else
            {
               mstrProgressString = "Could not get data description for cube.";
               meGabbiness = ERRORS;
               displayErrorMessage();
               return false;
            }
         }

         char* mutableExpression = new char[mExpression.size() + 1];
         strcpy(mutableExpression, mExpression.c_str());

         errorCode = eval(mpProgress, accessors, dataTypes, mCubeRows,
            mCubeColumns, mCubeBands, mutableExpression, returnDa,
            mbDegrees, errorVal, mbCubeMath, mbInteractive);

         delete [] mutableExpression;
      }

      if (errorCode != 0)
      {
         mbError = true;
         if (errorCode == -1)
         {
            mstrProgressString = errorVal;
            meGabbiness = ERRORS;
         }
         else if (errorCode == -2)
         {
            mstrProgressString = "BandMath was cancelled due to an error in the input expression.";
            meGabbiness = ABORT;
         }
         else
         {
            mstrProgressString = "Unknown error has occured while executing BandMath.";
            meGabbiness = ERRORS;
         }
         displayErrorMessage();
         return false;
      }

      pResultStep->finalize(Message::Success);
   }
   mpStep = pStep.get();

   if (!createReturnGuiElement())
   {
      mstrProgressString = "Could not create GUI element.";
      meGabbiness = ERRORS;
      displayErrorMessage();
      return false;
   }     

   // Fill output arg list
   if (pOutputArgList != NULL)
   {
      PlugInArg* pArg = NULL;
      pOutputArgList->getArg("Band Math Result", pArg);

      VERIFY(pArg != NULL);
      pArg->setActualValue(mpResultData);
   }

   mpResultData->updateData();

   if (mpProgress != NULL)
   {
      mpProgress->updateProgress("Algorithm completed successfully", 100, meGabbiness);
   }

   pStep->finalize(Message::Success);
   mpStep = NULL;
   return true;
}
Beispiel #23
0
bool GeoTIFFExporter::writeCube(TIFF* pOut)
{
    if (pOut == NULL)
    {
        return false;
    }

    VERIFY(mpRaster != NULL);
    VERIFY(mpFileDescriptor != NULL);

    const RasterDataDescriptor* pDescriptor = dynamic_cast<const RasterDataDescriptor*>(mpRaster->getDataDescriptor());
    if (pDescriptor == NULL)
    {
        return false;
    }

    int size = 0;
    int row = 0;
    unsigned char* pTempPtr = NULL;
    unsigned char* pBuffer = NULL;
    unsigned char* pDataCubePtr = NULL;
    unsigned short numRows = pDescriptor->getRowCount();
    unsigned short numCols = pDescriptor->getColumnCount();
    unsigned short numBands = pDescriptor->getBandCount();
    unsigned short scols = mpFileDescriptor->getColumnCount();
    unsigned short srows = mpFileDescriptor->getRowCount();
    unsigned short sbands = mpFileDescriptor->getBandCount();

    FactoryResource<DataRequest> pRequest;
    pRequest->setInterleaveFormat(BIP);
    DataAccessor accessor = mpRaster->getDataAccessor(pRequest.release());
    if (!accessor.isValid())
    {
        mMessage = "Could not get a valid BIP accessor for this dataset.";
        if (mpProgress != NULL)
        {
            mpProgress->updateProgress(mMessage, 0, ERRORS);
        }

        return false;
    }

    InterleaveFormatType eInterleave = pDescriptor->getInterleaveFormat();
    if (eInterleave != BIP)
    {
        mMessage = "Data will be saved in BIP format.";
        if (mpProgress != NULL)
        {
            mpProgress->updateProgress(mMessage, 0, WARNING);
        }
    }

    unsigned int bytesPerElement(pDescriptor->getBytesPerElement());
    size = scols * sbands * bytesPerElement;

    TIFFSetField(pOut, TIFFTAG_IMAGEWIDTH, scols);
    TIFFSetField(pOut, TIFFTAG_IMAGELENGTH, srows);
    TIFFSetField(pOut, TIFFTAG_SAMPLESPERPIXEL, sbands);

    //for this tag, must multiply by # of bytes per data type
    TIFFSetField(pOut, TIFFTAG_BITSPERSAMPLE, static_cast<unsigned short>(bytesPerElement * 8));
    TIFFSetField(pOut, TIFFTAG_SAMPLEFORMAT, static_cast<unsigned short>(
                     getTiffSampleFormat(pDescriptor->getDataType())));

    bool packBits = OptionsTiffExporter::getSettingPackBitsCompression();
    if (mpOptionWidget.get() != NULL)
    {
        mpOptionWidget->applyChanges();
        packBits = mpOptionWidget->getPackBitsCompression();
    }
    ttag_t compOpt = (packBits ? COMPRESSION_PACKBITS : COMPRESSION_NONE);

    TIFFSetField(pOut, TIFFTAG_COMPRESSION, compOpt);
    TIFFSetField(pOut, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
    TIFFSetField(pOut, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    TIFFSetField(pOut, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);      //????
    TIFFSetField(pOut, TIFFTAG_ROWSPERSTRIP, mRowsPerStrip);

    //ready to test write
    mMessage = "Writing out GeoTIFF file...";
    if (mpProgress)
    {
        mpProgress->updateProgress( mMessage, 0, NORMAL);
    }

    if ((numRows == srows) && (numCols == scols) && (numBands == sbands))   // full cube write from memory
    {
        for (row = 0; row < srows; row++)
        {
            if (mAbortFlag)
            {
                mMessage = "GeoTIFF export aborted!";
                if (mpProgress != NULL)
                {
                    mpProgress->updateProgress(mMessage, 0, ERRORS);
                }

                return false;
            }

            VERIFY(accessor.isValid());
            pBuffer = reinterpret_cast<unsigned char*>(accessor->getRow());
            if (pBuffer != NULL)
            {
                if (TIFFWriteScanline(pOut, pBuffer, row, size) < 0)
                {
                    mMessage = "Unable to save GeoTIFF file, check folder permissions.";
                    if (mpProgress)
                    {
                        mpProgress->updateProgress(mMessage, 0, ERRORS);
                    }

                    return false;
                }

                updateProgress(row, srows, mMessage, NORMAL);
            }
            accessor->nextRow();
        }
    }
    else // subcube write
    {
        const vector<DimensionDescriptor>& rows = mpFileDescriptor->getRows();
        const vector<DimensionDescriptor>& columns = mpFileDescriptor->getColumns();
        const vector<DimensionDescriptor>& bands = mpFileDescriptor->getBands();

        unsigned int activeRowNumber = 0;
        unsigned int rowSize(0);
        unsigned int outRow(0);
        for (unsigned int r = 0; r < srows; ++r)
        {
            if (mAbortFlag == true)
            {
                mMessage = "GeoTIFF export aborted!";
                if (mpProgress != NULL)
                {
                    mpProgress->updateProgress(mMessage, 0, ERRORS);
                }

                return false;
            }

            DimensionDescriptor rowDim = rows[r];
            if (rowDim.isActiveNumberValid())
            {
                // Skip to the next row
                for (; activeRowNumber < rowDim.getActiveNumber(); ++activeRowNumber)
                {
                    accessor->nextRow();
                }

                VERIFY(accessor.isValid());

                vector<char> rowData(size);
                if (rowData.empty())
                {
                    mMessage = "Error GeoTIFFExporter008: Unable to allocate row buffer.";
                    if (mpProgress)
                    {
                        mpProgress->updateProgress(mMessage, 0, ERRORS);
                    }

                    return false;
                }

                unsigned int activeColumnNumber = 0;

                char* pExportData = &(rowData.front());
                for (unsigned int c = 0; c < scols; ++c)
                {
                    DimensionDescriptor columnDim = columns[c];
                    if (columnDim.isActiveNumberValid())
                    {
                        // Skip to the next column
                        for (; activeColumnNumber < columnDim.getActiveNumber(); ++activeColumnNumber)
                        {
                            accessor->nextColumn();
                        }

                        char* pCurrentPixel = reinterpret_cast<char*>(accessor->getColumn());

                        unsigned int activeBandNumber = 0;
                        for (unsigned int b = 0; b < sbands; ++b)
                        {
                            DimensionDescriptor bandDim = bands[b];
                            if (bandDim.isActiveNumberValid())
                            {
                                // Skip to the next band
                                for (; activeBandNumber < bandDim.getActiveNumber(); ++activeBandNumber)
                                {
                                    pCurrentPixel += bytesPerElement;
                                }

                                memcpy(pExportData, pCurrentPixel, bytesPerElement);
                                pExportData += bytesPerElement;
                                rowSize += bytesPerElement;
                            }
                        }
                    }
                    else // this column is not included, go to next column
                    {
                        accessor->nextColumn();
                    }
                }

                if (rowSize > 0)
                {
                    // write here
                    if (TIFFWriteScanline(pOut, &rowData[0], outRow, size) < 0)
                    {
                        mMessage = "Error GeoTIFFExporter006: Unable to save GeoTIFF file, check folder permissions.";
                        if (mpProgress)
                        {
                            mpProgress->updateProgress(mMessage, 0, ERRORS);
                        }

                        return false;
                    }

                    updateProgress(outRow++, srows, mMessage, NORMAL);
                }
            }
            else // this row is not included, go to next row
            {
                accessor->nextRow();
            }
        }
    }

    //assumed everything has been done correctly up to now
    //copy over Geo ref info if there are any, else
    //try to look for world file in same directory and apply
    if (!(applyWorldFile(pOut)))
    {
        if (!(CreateGeoTIFF(pOut)))
        {
            //no geo info found, where is it located?
            mMessage = "Geo data is unavailable and will not be written to the output file!";
            updateProgress(srows, srows, mMessage, WARNING);
            if (mpStep != NULL)
            {
                mpStep->addMessage(mMessage, "app", "9C1E7ADE-ADC4-468c-B15E-FEB53D5FEF5B", true);
            }
        }
    }

    return true;
}
Beispiel #24
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 HIGHPASS::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Tutorial 5", "app", "219F1882-A59F-4835-BE2A-E83C0C8111EB");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());

   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);

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

   ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() +
      "DResult", 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());
   int rowSize= pDesc->getRowCount();
   int colSize = pDesc->getColumnCount();
   int zero=0;
   int prevCol = 0;
      int prevRow = 0;
      int nextCol = 0;
      int nextRow = 0;

	  int prevCol1 = 0;
	  int prevRow1= 0;
	  int nextCol1= 0;
	  int nextRow1= 0;

   for (unsigned 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 (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
      {
		  
		  double value=edgeDetection7(pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount());
          switchOnEncoding(pDesc->getDataType(), conversion, pDestAcc->getColumn(), value);
          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("HighPass is compete.", 100, NORMAL);
   }

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

   pStep->finalize();
   return true;
}
bool adaptive_median::copyImage4(RasterElement * pRaster,
								 RasterElement * dRaster, int i,
								 Progress * pProgress)
{
	int flag = 0;
	int size = 3;
	int sizeMax = MAX_SIZE;
	VERIFY(pRaster != NULL);
	RasterDataDescriptor *pDesc =
		dynamic_cast < RasterDataDescriptor * >(pRaster->getDataDescriptor());
	VERIFY(dRaster != NULL);
	RasterDataDescriptor *rDesc =
		dynamic_cast < RasterDataDescriptor * >(dRaster->getDataDescriptor());

	DimensionDescriptor thirdBand = pDesc->getActiveBand(i);	// get active
																// band

	// source
	FactoryResource < DataRequest > pRequest;
	pRequest->setInterleaveFormat(BSQ);
	pRequest->setBands(thirdBand, thirdBand);
	DataAccessor thirdBandDa = pRaster->getDataAccessor(pRequest.release());
	thirdBand = rDesc->getActiveBand(i);

	// destination
	FactoryResource < DataRequest > pResultRequest;
	pResultRequest->setWritable(true);
	pRequest->setInterleaveFormat(BSQ);
	pResultRequest->setBands(thirdBand, thirdBand);
	DataAccessor pDestAcc = dRaster->getDataAccessor(pResultRequest.release());
	VERIFY(thirdBandDa.isValid());
	VERIFY(pDestAcc.isValid());

	for (unsigned int curRow = 0; curRow < pDesc->getRowCount(); ++curRow)
	{
		for (unsigned int curCol = 0; curCol < pDesc->getColumnCount();
			 ++curCol)
		{
			VERIFY(pDestAcc.isValid());
			switchOnEncoding(pDesc->getDataType(), adaptivemedian,
							 pDestAcc->getColumn(), thirdBandDa, curRow,
							 curCol, pDesc->getRowCount(),
							 pDesc->getColumnCount(), size, sizeMax, pProgress,
							 &flag);
			if (flag == 1 && size <= sizeMax)
			{
				// increase window size
				size = size + 2;
				curCol--;
			}
			else
			{
				pDestAcc->nextColumn();
				size = 3;
				flag = 0;
			}
		}
		pDestAcc->nextRow();
	}

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

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

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

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

   double minGrayValue;
   double maxGrayValue;
   double deltaValue = 0.0;

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

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


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

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


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

	   }
   }
   
   free(OrigData);  


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

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

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

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

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

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

   pStep->finalize();


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

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

   RasterElement* pCube = elements[0];
   RasterElement* pCubeRef = elements[1];
   if ((pCube == NULL) || (pCubeRef == NULL))
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   
   EncodingType ResultType = pDesc->getDataType();
   if (pDesc->getDataType() == INT4SCOMPLEX)
   {
      ResultType = INT4SBYTES;
   }
   else if (pDesc->getDataType() == FLT8COMPLEX)
   {
      ResultType = FLT8BYTES;
   }

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

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

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

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

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

   GetGrayScale(pDesc->getDataType());

   
   for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
   {
	   if (pProgress != NULL)
       {
           pProgress->updateProgress("Image registration", row * 100 / pDesc->getRowCount(), NORMAL);
       }
       if (isAborted())
       {
          std::string msg = getName() + " has been aborted.";
          pStep->finalize(Message::Abort, msg);
          if (pProgress != NULL)
          {
             pProgress->updateProgress(msg, 0, ABORT);
          }
          return false;
       }
       for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
       {
	       locateAllStarPosition(pSrcAcc, pSrcAccRef, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), windowSize, pBuffer);
       }
   }

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

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

   //Output the value 
      for (unsigned int m = 0; m < pDesc->getRowCount(); m++)
      {
	      for (unsigned int n = 0; n < pDesc->getColumnCount(); n++)
	      {
		      if (isAborted())
              {
                  std::string msg = getName() + " has been aborted.";
                  pStep->finalize(Message::Abort, msg);
                  if (pProgress != NULL)
                  {
                      pProgress->updateProgress(msg, 0, ABORT);
                  }
                  return false;
              }
				      
			  if (!pDestAcc.isValid())
              {
                  std::string msg = "Unable to access the cube data.";
                  pStep->finalize(Message::Failure, msg);
                  if (pProgress != NULL) 
                  {
                      pProgress->updateProgress(msg, 0, ERRORS);
                   }
                   return false;
               }

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


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

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

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

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

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

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

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

   pStep->finalize();


   return true;
}