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 getAccessor(int band, bool writable = false) {
     FactoryResource<DataRequest> pRequest = FactoryResource<DataRequest>();
     pRequest->setRows(pDataDescriptor->getActiveRow(0), pDataDescriptor->getActiveRow(getRowCount() - 1));
     pRequest->setColumns(pDataDescriptor->getActiveColumn(0), pDataDescriptor->getActiveColumn(getColumnCount() - 1));
     pRequest->setBands(pDataDescriptor->getActiveBand(band),  pDataDescriptor->getActiveBand(band));
     pRequest->setWritable(writable);
     return pRaster->getDataAccessor(pRequest.release());
 }
void Simulation_GUI::StartOrtho()
{
   mpStartOrtho->setEnabled(false);

   // Update Grid Information
   OrthoGrid.X_Step = X_Spacing->value();
   OrthoGrid.Y_Step = Y_Spacing->value();

   OrthoGrid.X_Dim = int(OrthoGrid.X_Dim/OrthoGrid.X_Step)+1.0;
   OrthoGrid.Y_Dim = int(OrthoGrid.Y_Dim/OrthoGrid.Y_Step)+1.0; 

   OrthoGrid.Lon_Step = (OrthoGrid.Lon_Max-OrthoGrid.Lon_Min)/OrthoGrid.X_Dim;
   
   OrthoGrid.Lat_Step = (OrthoGrid.Lat_Max-OrthoGrid.Lat_Min)/OrthoGrid.Y_Dim;

   //Start Ortho
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());

   FactoryResource<DataRequest> pRequest;
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* oMetadata = dMeta->getMetadata();

	// RETRIEVE & UPDATE METADATA INFORMATION //

	bool control = Metadata->ReadFile(image_path);

	Metadata->UpdateMetadata(oMetadata); 

	SAR_Model *ModProva;
	ModProva = new SAR_Slant_Model(*Metadata, 10);

	if(Metadata->Projection == "SGF")
	{
		ModProva = new SAR_Ground_Model(*Metadata,10);
	}

	SAR_Simulator_Processor ProcessOrtho(pCube, ModProva, OrthoGrid, Height->value());
	
	// RETRIVE SELECTED RESAMPLING METHOD AND EXECUTE ORTHO

	int indexR = mpInterpolationList->currentIndex();
	
	//if (mpFlatten->isChecked() ==true) 
	//{
		//VERIFYNRV(ProcessOrtho.process(indexR));	
	//}
	//else 
	//{
		VERIFYNRV(RetrieveDSMGrid());
		VERIFYNRV(ProcessOrtho.process(indexR, pDSM, DSMGrid, GeoidOffSet->value(),mpDSMInterpolationList->currentIndex()));
	//}

}
// FileDescriptor
FileDescriptor* FileDescriptorAdapter::copy() const
{
   FactoryResource<FileDescriptor> pFileDescriptor;
   if (pFileDescriptor->clone(this) == false)
   {
      return NULL;
   }

   return pFileDescriptor.release();
}
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 #7
0
DynamicObject *QueryOptions::toDynamicObject() const
{
   FactoryResource<DynamicObject> pDynObj;
   VERIFYRV(pDynObj.get() != NULL, NULL);

   pDynObj->setAttribute(QUERY_NAME, mQueryName);
   pDynObj->setAttribute(QUERY_STRING, mQueryString);
   pDynObj->setAttribute(SYMBOL_NAME, mSymbolName);
   pDynObj->setAttribute(SYMBOL_SIZE, mSymbolSize);
   pDynObj->setAttribute(LINE_STATE, mLineState);
   pDynObj->setAttribute(LINE_STYLE, mLineStyle);
   pDynObj->setAttribute(LINE_WIDTH, mLineWidth);
   pDynObj->setAttribute(LINE_COLOR, mLineColor);
   pDynObj->setAttribute(LINE_SCALED, mLineScaled);
   pDynObj->setAttribute(FILL_COLOR, mFillColor);
   pDynObj->setAttribute(FILL_STYLE, mFillStyle);
   pDynObj->setAttribute(HATCH_STYLE, mHatchStyle);

   return pDynObj.release();
}
Beispiel #8
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;
}
Beispiel #10
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 #11
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 Orthorectification::process(int type, RasterElement *pDSM, GRID DSMGrid, double Geoid_Offset, int DSM_resampling)
{
	StepResource pStep("Orthorectification Process", "app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	pStep->addStep("Start","app", "B4D426EC-E06D-11E1-83C8-42E56088709B");
	boxsize=0;

	res_type = type;

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

    ProgressResource pResource("ProgressBar");

	Progress *pProgress=pResource.get(); 

	pProgress->setSettingAutoClose(false);

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

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

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

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

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

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

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

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

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

	}

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

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

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

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

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

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

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

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

		  // RETRIEVE HEIGHT VALUE FROM DSM 

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

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

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

      pDestAcc->nextRow();
    }

   Service<DesktopServices> pDesktop;

   Service<ModelServices> pMod;

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

   GcpPoint Punto;

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

   GcpL->addPoint(Punto);

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

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

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

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

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

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

   pView->setDataOrigin(LOWER_LEFT);

   pResultCube.release();

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

   return true;
   
}
Beispiel #13
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;
}
void ConvolutionFilterShell::ConvolutionFilterThread::convolve(const T*)
{
   int numResultsCols = mInput.mpIterCheck->getNumSelectedColumns();
   if (mInput.mpResult == NULL)
   {
      return;
   }

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

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

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

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

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

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

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

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

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

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

            switchOnEncoding(pResultDescriptor->getDataType(), assignResult,
                             resultAccessor->getColumn(), accum + mInput.mOffset);
            resultAccessor->nextColumn();
         }
         resultAccessor->nextRow();
      }
   }
}
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 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;
}
Beispiel #17
0
bool EdgeDetector::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Edge Detector", "app", "37C57772-DD49-4532-8BC6-9CFB8587D0C9");
   if (pInArgList == NULL || pOutArgList == NULL)
   {
      return false;
   }
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg());
   if (pCube == NULL)
   {
      std::string msg = "A raster cube must be specified.";
      pStep->finalize(Message::Failure, msg);
      if (pProgress != NULL) 
      {
         pProgress->updateProgress(msg, 0, ERRORS);
      }
      return false;
   }
   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());
   VERIFY(pDesc != NULL);
   EncodingType ResultType = INT1UBYTE;

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

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

   Service<DesktopServices> pDesktop;
   EdgeRatioThresholdDlg dlg(pDesktop->getMainWidget(), SMALL_WINDOW_THRESHOLD, MEDIAN_WINDOW_THRESHOLD, LARGE_WINDOW_THRESHOLD);
   int stat = dlg.exec();
   if (stat == QDialog::Accepted)
   {
      for (unsigned int row = 0; row < pDesc->getRowCount(); ++row)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("Edge detect ", row * 100 / pDesc->getRowCount(), NORMAL);
         }
         if (isAborted())
         {
            std::string msg = getName() + " has been aborted.";
            pStep->finalize(Message::Abort, msg);
            if (pProgress != NULL)
            {
               pProgress->updateProgress(msg, 0, ABORT);
            }
            return false;
         }
         if (!pDestAcc.isValid())
         {
            std::string msg = "Unable to access the cube data.";
            pStep->finalize(Message::Failure, msg);
            if (pProgress != NULL) 
            {
               pProgress->updateProgress(msg, 0, ERRORS);
            }
            return false;
         }
         for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col)
         {
            switchOnEncoding(ResultType, EdgeDetectSAR, pDestAcc->getColumn(), pSrcAcc, row, col,
                             pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType(), 
			                 dlg.getSmallThreshold(), dlg.getMedianThreshold(), dlg.getLargeThreshold());
            pDestAcc->nextColumn();
         }

         pDestAcc->nextRow();
      }

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

	std::string msg = "Noise Reduction by Adaptive Median Filter ";
	Progress *pProgress =
		pInArgList->getPlugInArgValue < Progress > (Executable::ProgressArg());
	RasterElement *pCube =
		pInArgList->getPlugInArgValue < RasterElement >
		(Executable::DataElementArg());

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

	RasterDataDescriptor *pDesc =
		static_cast < RasterDataDescriptor * >(pCube->getDataDescriptor());
	VERIFY(pDesc != NULL);
	if (pDesc->getDataType() == INT4SCOMPLEX
		|| pDesc->getDataType() == FLT8COMPLEX)
	{
		std::string msg =
			"Noise Reduction cannot be performed on complex types.";
		pStep->finalize(Message::Failure, msg);
		if (pProgress != NULL)
		{
			pProgress->updateProgress(msg, 0, ERRORS);
		}
		return false;
	}

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

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

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

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

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

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

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

	ModelResource < RasterElement > pResultCube(dRas);

	if (pResultCube.get() == NULL)
	{
		std::string msg = "A raster cube could not be created.";
		pStep->finalize(Message::Failure, msg);
		if (pProgress != NULL)
		{
			pProgress->updateProgress(msg, 0, ERRORS);
		}
		return false;
	}

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

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

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

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

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

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

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

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

	pStep->finalize();
	return true;
}
bool 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;
}
Beispiel #22
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 #23
0
bool ResultsExporter::runAllTests(Progress *pProgress, ostream& failure)
{
    bool success = true;

    mpProgress = pProgress;
    mpResults = RasterUtilities::createRasterElement("ResultsExporterTestMatrix", 2, 2, FLT4BYTES, true, NULL);
    if (mpResults == NULL)
    {
        failure << "Unable to create a Raster Element.";
        success = false;
    }
    else
    {
        ModelResource<RasterElement> pResultsResource(mpResults);
        RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(mpResults->getDataDescriptor());
        if (pDescriptor == NULL)
        {
            failure << "Unable to get the Raster Data Descriptor.";
            success = false;
        }
        else
        {
            // Bad values
            std::vector<int> badValues;
            badValues.push_back(2);
            badValues.push_back(4);
            pDescriptor->setBadValues(badValues);

            // Create the element
            FactoryResource<DataRequest> pRequest;
            pRequest->setWritable(true);
            DataAccessor da = mpResults->getDataAccessor(pRequest.release());
            if (da.isValid() == false)
            {
                failure << "Data Accessor is not valid.";
                success = false;
            }
            else
            {
                float* pData = reinterpret_cast<float*>(da->getRow());
                if (pData == NULL)
                {
                    failure << "Data is not accessible.";
                    success = false;
                }
                else
                {
                    pData[0] = 1.0;
                    pData[1] = 2.0;
                    pData[2] = 3.0;
                    pData[3] = 4.0;

                    mFirstThreshold = 1.5;
                    mSecondThreshold = 4.5;
                    mPassArea = MIDDLE;
                    mGeocoordType = GEOCOORD_LATLON;
                    mbMetadata = false;
                    mbAppendFile = false;

                    const Filename* pTempPath = ConfigurationSettings::getSettingTempPath();
                    if (pTempPath == NULL)
                    {
                        failure << "Unable to get the temporary path from ConfigurationSettings.";
                        success = false;
                    }
                    else
                    {
                        const string filename = pTempPath->getFullPathAndName() + "/ResultsExporterTest.rls";
                        mpFileDescriptor = dynamic_cast<RasterFileDescriptor*>
                                           (RasterUtilities::generateFileDescriptorForExport(pDescriptor, filename));
                        if (mpFileDescriptor == NULL)
                        {
                            failure << "Unable to generate a Raster File Descriptor for export.";
                            success = false;
                        }
                        else
                        {
                            FactoryResource<RasterFileDescriptor> pFileDescriptor(mpFileDescriptor);
                            stringstream stream;
                            writeOutput(stream);

                            if (stream.str() != "ResultsExporterTestMatrix    Pixel: (1, 2)    3.000000\n\n")
                            {
                                failure << "Invalid output stream.";
                                success = false;
                            }
                        }
                    }
                }
            }
        }
    }

    mpResults = NULL;
    mpProgress = NULL;
    mpFileDescriptor = NULL;
    return success;
}
void Simulation_GUI::CheckModel()
{
   ProgressResource pProgress("ProgressBar");

   RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor());

   FactoryResource<DataRequest> pRequest;
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* oMetadata = dMeta->getMetadata();

	// RETRIEVE & UPDATE METADATA INFORMATION //

	bool control = Metadata->ReadFile(image_path);

	Metadata->UpdateMetadata(oMetadata); 
  
	// WIDGET SELECT & RETRIEVE GCPs INFORMATION  //
	GcpList * GCPs = NULL;

    Service<ModelServices> pModel;
	std::vector<DataElement*> pGcpLists = pModel->getElements(pCube, TypeConverter::toString<GcpList>());

    if (!pGcpLists.empty())
	{
         QStringList aoiNames("<none>");
         for (std::vector<DataElement*>::iterator it = pGcpLists.begin(); it != pGcpLists.end(); ++it)
         {
            aoiNames << QString::fromStdString((*it)->getName());
         }
         QString aoi = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Select a GCP List", "Select a GCP List for validate the orientation model", aoiNames);
         
         if (aoi != "<none>")
         {
            std::string strAoi = aoi.toStdString();
            for (std::vector<DataElement*>::iterator it = pGcpLists.begin(); it != pGcpLists.end(); ++it)
            {
               if ((*it)->getName() == strAoi)
               {
                  GCPs = static_cast<GcpList*>(*it);
                  break;
               }
            }
            if (GCPs == NULL)
            {
               std::string msg = "Invalid GCPList.";
               pProgress->updateProgress(msg, 0, ERRORS);
               return;
            }
         }
		 else
		 {
			 std::string msg = "A set of GCPs must be specified.";
			 if (pProgress.get() != NULL)
             {
				 pProgress->updateProgress(msg, 0, ERRORS);
             }
			 return;
		 }
	} // End if GcpList
   
  	
	// UPDATE GCPs HEIGHT INFORMATION AND SWITCH Lat&Lon COORDINATE FOR CORRECT VISUALIZAZION IN THE GCPs EDITOR
 
    std::list<GcpPoint> Punti = GCPs->getSelectedPoints();
     
	Punti = Metadata->UpdateGCP(Punti, image_path);

	//SAR_Model ModProva(*Metadata);

	SAR_Model *ModProva;
	//ModProva = new SAR_Ground_Model(Prova_metadata);
	ModProva = new SAR_Slant_Model(*Metadata);

	if(Metadata->Projection == "SGF")
	{
		ModProva = new SAR_Ground_Model(*Metadata);
	}

	P_COORD Punto;
	int N=Punti.size();
	int n=0;
	double Lat, Lon;

	accumulator_set<double, stats<tag::mean, tag::variance> > accX, accY;

	list<GcpPoint>::iterator pList;
	for (pList = Punti.begin(); pList != Punti.end(); pList++)
	{
		if(pList->mPixel.mX<Metadata->Width && pList->mPixel.mY<Metadata->Height)	
		{
			Lon = pList->mCoordinate.mX;
			Lat = pList->mCoordinate.mY;
			
			Punto = ModProva->SAR_GroundToImage(pList->mCoordinate.mX,pList->mCoordinate.mY,pList->mCoordinate.mZ); 
			pList->mRmsError.mX = pList->mPixel.mX -Punto.I;
			pList->mRmsError.mY = pList->mPixel.mY -Punto.J;
			accX(pList->mRmsError.mX);
			accY(pList->mRmsError.mY);

			pList->mCoordinate.mX = Lat;
			pList->mCoordinate.mY = Lon;

		}
		else
		{
			Lon = pList->mCoordinate.mX;
			Lat = pList->mCoordinate.mY;
			pList->mRmsError.mX = -9999;
			pList->mRmsError.mY = -9999;
			pList->mCoordinate.mX = Lat;
			pList->mCoordinate.mY = Lon;
		}


        pProgress->updateProgress("Calculating statistics", int(100*n/N), NORMAL);
		
		n++;
	}

	 double meanX = mean(accX);
	 double meanY = mean(accY);

	 double varX = variance(accX);
	 double varY = variance(accY);
	
     GCPs->clearPoints();
     GCPs->addPoints(Punti);
	

		std::string msg = "Number of Rows : " + StringUtilities::toDisplayString(pDesc->getRowCount()) + "\n"
						  "Number of Columns : " + StringUtilities::toDisplayString(pDesc->getColumnCount()) + "\n\n"
						  "Metadata update completed" + "\n\n"					  
						  "**********     Validation Results     **********" "\n\n"
						  "Number of GCPs: " + StringUtilities::toDisplayString(Punti.size()) + "\n\n"
						  "Mean I : " + StringUtilities::toDisplayString(meanX) + "\n"
						  "Variance I : " + StringUtilities::toDisplayString(varX) + "\n\n"
						  "Mean J : " + StringUtilities::toDisplayString(meanY) + "\n"
						  "Variance J : " + StringUtilities::toDisplayString(varY) + "\n\n" ;
				  						                      
		pProgress->updateProgress(msg, 100, NORMAL);

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

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

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

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

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

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

		  acc->nextValidPoint();
	   }
	   pProgress->updateProgress("DEM generation is complete.", 100, NORMAL);
	   pStep->finalize();
	   return demRM;
}
bool SpectralLibraryManager::generateResampledLibrary(const RasterElement* pRaster)
{
    VERIFY(pRaster != NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return true;
}
Beispiel #27
0
void NormalizeData::NormalizeDataThread::run()
{
   if (mInput.mpResult == NULL)
   {
      getReporter().reportError("No result data element.");
      return;
   }

   EncodingType encoding = mInput.mpDescriptor->getDataType();
   int numCols = mInput.mpResultDescriptor->getColumnCount();

   int oldPercentDone = 0;

   int startRow = mRowRange.mFirst;
   int stopRow = mRowRange.mLast;
   bool isBip = (mInput.mpResultDescriptor->getInterleaveFormat() == BIP);
   unsigned int numBandsInLoop = isBip ? 1 : mInput.mpResultDescriptor->getBandCount();
   unsigned int numBandsPerElement = isBip ? mInput.mpResultDescriptor->getBandCount() : 1;
   std::vector<double> bandMaxValues;
   bandMaxValues.reserve(mInput.mpDescriptor->getBandCount());
   for (unsigned int band = 0; band < mInput.mpDescriptor->getBandCount(); band++)
   {
      bandMaxValues.push_back(mInput.mpRaster->getStatistics(mInput.mpDescriptor->getActiveBand(band))->getMax());
   }

   Service<ModelServices> pModel;

   for(unsigned int band = 0; band < numBandsInLoop; band++)
   {
      FactoryResource<DataRequest> pResultRequest;
      pResultRequest->setRows(mInput.mpResultDescriptor->getActiveRow(mRowRange.mFirst),
         mInput.mpResultDescriptor->getActiveRow(mRowRange.mLast));
      pResultRequest->setColumns(mInput.mpResultDescriptor->getActiveColumn(0),
         mInput.mpResultDescriptor->getActiveColumn(numCols - 1));
      if (!isBip)
      {
         pResultRequest->setBands(mInput.mpResultDescriptor->getActiveBand(band), mInput.mpResultDescriptor->getActiveBand(band));
      }
      pResultRequest->setWritable(true);
      DataAccessor resultAccessor = mInput.mpResult->getDataAccessor(pResultRequest.release());
      if (!resultAccessor.isValid())
      {
         getReporter().reportError("Invalid data access.");
         return;
      }

      FactoryResource<DataRequest> pRequest;
      pRequest->setRows(mInput.mpDescriptor->getActiveRow(mRowRange.mFirst),
         mInput.mpDescriptor->getActiveRow(mRowRange.mLast));
      pRequest->setColumns(mInput.mpDescriptor->getActiveColumn(0),
         mInput.mpDescriptor->getActiveColumn(numCols - 1));
      if (!isBip)
      {
         pRequest->setBands(mInput.mpResultDescriptor->getActiveBand(band), mInput.mpResultDescriptor->getActiveBand(band));
      }
      DataAccessor accessor = mInput.mpRaster->getDataAccessor(pRequest.release());
      if (!accessor.isValid())
      {
         getReporter().reportError("Invalid data access.");
         return;
      }

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

         for (int col_index = 0; col_index < numCols; col_index++)
         {
            if (!resultAccessor.isValid())
            {
               getReporter().reportError("Invalid data access.");
               return;
            }

            for (unsigned int inner = 0; inner < numBandsPerElement; inner++)
            {
               double val = pModel->getDataValue(encoding, accessor->getColumn(), inner);
               val /= bandMaxValues[std::max(band, inner)];
               reinterpret_cast<double*>(resultAccessor->getColumn())[inner] = val;
            }

            resultAccessor->nextColumn();
            accessor->nextColumn();
         }
         resultAccessor->nextRow();
         accessor->nextRow();
      }
   }
   getReporter().reportCompletion(getThreadIndex());
}
bool Test_Update_TerraSAR::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
  StepResource pStep("Tutorial CEO", "app", "0FD3C564-041D-4f8f-BBF8-96A7A165AB61");

   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;
   DataAccessor pAcc = pCube->getDataAccessor(pRequest.release());

   std::string path = pCube->getFilename();

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* Metadata = dMeta->getMetadata();

	// RETRIEVE & UPDATE METADATA INFORMATION //
		   
	TerraSAR_Metadata Prova_metadata;

	bool control = Prova_metadata.ReadFile(path);

	if (control == false)
	{
	std::string msg = "This is not a TerraSAR-X SLC Files, Metadata can't be updated";
	pProgress->updateProgress(msg, 100, ERRORS);
	return false;
	}

	Prova_metadata.UpdateMetadata(Metadata); 

	//SAR_Model ModProva(Prova_metadata,1000);

	SAR_Model *ModProva;
	//ModProva = new SAR_Ground_Model(Prova_metadata);
	
	ModProva = new SAR_Slant_Model(Prova_metadata);

	if(Prova_metadata.Projection == "SGF")
	{
		ModProva = new SAR_Ground_Model(Prova_metadata);
	}
	//else
	//{
	//	ModProva = new SAR_Slant_Model(Prova_metadata);
	//}
	
	
	// WIDGET SELECT & RETRIEVE GCPs INFORMATION  //
	GcpList * GCPs = NULL;

    Service<ModelServices> pModel;
	std::vector<DataElement*> pGcpLists = pModel->getElements(pCube, TypeConverter::toString<GcpList>());


	std::list<GcpPoint> Punti;

    if (!pGcpLists.empty())
	{
         QStringList aoiNames("<none>");
         for (std::vector<DataElement*>::iterator it = pGcpLists.begin(); it != pGcpLists.end(); ++it)
         {
            aoiNames << QString::fromStdString((*it)->getName());
         }
         QString aoi = QInputDialog::getItem(Service<DesktopServices>()->getMainWidget(),
            "Select a GCP List", "Select a GCP List for validate the orientation model", aoiNames);
         
         if (aoi != "<none>")
         {
            std::string strAoi = aoi.toStdString();
            for (std::vector<DataElement*>::iterator it = pGcpLists.begin(); it != pGcpLists.end(); ++it)
            {
               if ((*it)->getName() == strAoi)
               {
                  GCPs = static_cast<GcpList*>(*it);
                  break;
               }
            }
            if (GCPs == NULL)
            {
               std::string msg = "Invalid GCPList.";
               pStep->finalize(Message::Failure, msg);
               if (pProgress != NULL)
               {
                  pProgress->updateProgress(msg, 0, ERRORS);
               }

               return false;
            }
         }
		 else
		 {
			 std::string msg = "A set of GCPs must be specified.";
             pStep->finalize(Message::Failure, msg);
             if (pProgress != NULL)
             {
				 pProgress->updateProgress(msg, 0, ERRORS);
             }
			 return false;
		 }


		// UPDATE GCPs HEIGHT INFORMATION AND SWITCH Lat&Lon COORDINATE FOR CORRECT VISUALIZAZION IN THE GCPs EDITOR

		Punti = GCPs->getSelectedPoints();
     
		Punti = Prova_metadata.UpdateGCP(Punti, path, pProgress);



	P_COORD Punto;
	int N=Punti.size();
	int n=0, indexP=0;
	double Lat, Lon;

	accumulator_set<double, stats<tag::mean, tag::variance> > accX, accY;

	list<GcpPoint>::iterator pList;
	for (pList = Punti.begin(); pList != Punti.end(); pList++)
	{
		if(pList->mPixel.mX<Prova_metadata.Width && pList->mPixel.mY<Prova_metadata.Height)	
		{
			Lon = pList->mCoordinate.mX;
			Lat = pList->mCoordinate.mY;
			
			Punto = ModProva->SAR_GroundToImage(pList->mCoordinate.mX,pList->mCoordinate.mY,pList->mCoordinate.mZ); 
			//pList->mRmsError.mX = pList->mPixel.mX -Punto.I;
			//pList->mRmsError.mY = pList->mPixel.mY -Punto.J;

			pList->mPixel.mX = (Prova_metadata.Grid_Range_Time/Prova_metadata.RowSpacing)*(indexP-int(indexP/Prova_metadata.Grid_N_Range)*Prova_metadata.Grid_N_Range);
			pList->mRmsError.mX = (Prova_metadata.Grid_Range_Time/Prova_metadata.RowSpacing)*(indexP-int(indexP/Prova_metadata.Grid_N_Range)*Prova_metadata.Grid_N_Range) -Punto.I;

			pList->mPixel.mY = (Prova_metadata.Grid_Azimuth_Time*Prova_metadata.PRF)*int(indexP/Prova_metadata.Grid_N_Range);
			pList->mRmsError.mY = (Prova_metadata.Grid_Azimuth_Time*Prova_metadata.PRF)*int(indexP/Prova_metadata.Grid_N_Range) - Punto.J;
			
			accX(pList->mRmsError.mX);
			accY(pList->mRmsError.mY);

			pList->mCoordinate.mX = Lat;
			pList->mCoordinate.mY = Lon;

		}
		else
		{
			Lon = pList->mCoordinate.mX;
			Lat = pList->mCoordinate.mY;
			pList->mRmsError.mX = -9999;
			pList->mRmsError.mY = -9999;
			pList->mCoordinate.mX = Lat;
			pList->mCoordinate.mY = Lon;
		}

		if (pProgress != NULL)
		{
         pProgress->updateProgress("Calculating statistics", int(100*n/N), NORMAL);
		}
		n++;
		indexP++;
	}

	double meanX = mean(accX);
	double meanY = mean(accY);

	double varX = variance(accX);
	double varY = variance(accY);
	
    GCPs->clearPoints();
    GCPs->addPoints(Punti);


	if (pProgress != NULL)
	{
		std::string msg = "Number of Rows : " + StringUtilities::toDisplayString(pDesc->getRowCount()) + "\n"
						  "Number of Columns : " + StringUtilities::toDisplayString(pDesc->getColumnCount()) + "\n\n"
						  "Metadata update completed" + "\n\n"					  
						  "**********     Validation Results     **********" "\n\n"
						  "Number of GCPs: " + StringUtilities::toDisplayString(Punti.size()) + "\n\n"
						  "Mean I : " + StringUtilities::toDisplayString(meanX) + "\n"
						  "Variance I : " + StringUtilities::toDisplayString(varX) + "\n\n"
						  "Mean J : " + StringUtilities::toDisplayString(meanY) + "\n"
						  "Variance J : " + StringUtilities::toDisplayString(varY) + "\n\n" ;
				  						                      
		pProgress->updateProgress(msg, 100, NORMAL);
	}

	} // End if GcpList
	else
	{
		Punti.resize(Prova_metadata.Grid_N);
		Punti = Prova_metadata.UpdateGCP(Punti, path);

	}


	pStep->finalize(); 

	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;
}
Beispiel #30
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;
}