bool BackgroundSuppressionShell::preprocess() { if(mpRaster == NULL) { return false; } RasterDataDescriptor *pDesc = static_cast<RasterDataDescriptor*>(mpRaster->getDataDescriptor()); if(mpTemporaryBuffer.get() == NULL) { mpTemporaryBuffer.reset(new char[pDesc->getRowCount() * pDesc->getColumnCount() * pDesc->getBytesPerElement()]); if(mpTemporaryBuffer.get() == NULL) { return false; } } DataAccessor frameAccessor = getCurrentFrameAccessor(); size_t rowSize = pDesc->getColumnCount() * pDesc->getBytesPerElement(); for(unsigned int row = 0; row < pDesc->getRowCount(); row++) { if(!frameAccessor.isValid()) { return false; } memcpy(mpTemporaryBuffer.get() + row * rowSize, frameAccessor->getRow(), rowSize); frameAccessor->nextColumn(); } return true; }
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; }
const double *SignatureLibraryImp::getOrdinateData(unsigned int index) const { if (mNeedToResample || mResampledData.empty()) { const_cast<SignatureLibraryImp*>(this)->resample(mAbscissa); } if (index < mSignatures.size() && (!mAbscissa.empty() || mpOdre.get() != NULL)) { if (mAbscissa.empty()) { const RasterDataDescriptor* pDesc = dynamic_cast<const RasterDataDescriptor*>(mpOdre.get()->getDataDescriptor()); if (pDesc != NULL) { FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BIP); pRequest->setBands(pDesc->getActiveBand(0), pDesc->getActiveBand(pDesc->getBandCount() - 1), pDesc->getBandCount()); pRequest->setRows(pDesc->getActiveRow(index), pDesc->getActiveRow(index), 1); DataAccessor da = mpOdre->getDataAccessor(pRequest.release()); if (da.isValid()) { static vector<double> sOriginalOrdinateData; sOriginalOrdinateData.resize(mOriginalAbscissa.size()); switchOnEncoding(pDesc->getDataType(), getOriginalAsDouble, da->getRow(), mOriginalAbscissa.size(), sOriginalOrdinateData); return &sOriginalOrdinateData[0]; } } return NULL; } return &mResampledData[index * getAbscissa().size()]; } return NULL; }
bool SpectralLibraryManager::getResampledSignatureValues(const RasterElement* pRaster, const Signature* pSignature, std::vector<double>& values) { values.clear(); if (pRaster == NULL || pSignature == NULL) { return false; } const RasterElement* pLibData = getResampledLibraryData(pRaster); if (pLibData == NULL) { return false; } int index = getSignatureIndex(pSignature); if (index < 0) { return false; } const RasterDataDescriptor* pLibDesc = dynamic_cast<const RasterDataDescriptor*>(pLibData->getDataDescriptor()); VERIFY(pLibDesc != NULL); unsigned int numBands = pLibDesc->getBandCount(); values.reserve(numBands); FactoryResource<DataRequest> pRqt; unsigned int row = static_cast<unsigned int>(index); pRqt->setInterleaveFormat(BIP); pRqt->setRows(pLibDesc->getActiveRow(row), pLibDesc->getActiveRow(row), 1); DataAccessor acc = pLibData->getDataAccessor(pRqt.release()); VERIFY(acc.isValid()); double* pDbl = reinterpret_cast<double*>(acc->getColumn()); for (unsigned int band = 0; band < numBands; ++band) { values.push_back(*pDbl); ++pDbl; } return true; }
bool Orthorectification::process(int type, RasterElement *pDSM, GRID DSMGrid, double Geoid_Offset, int DSM_resampling) { StepResource pStep("Orthorectification Process", "app", "B4D426EC-E06D-11E1-83C8-42E56088709B"); pStep->addStep("Start","app", "B4D426EC-E06D-11E1-83C8-42E56088709B"); boxsize=0; res_type = type; if (res_type == 0) { boxsize=0; } else if (res_type == 1) { boxsize=1; } else if (res_type == 2) { boxsize=2; } else if (res_type == 3) { boxsize=3; } ProgressResource pResource("ProgressBar"); Progress *pProgress=pResource.get(); pProgress->setSettingAutoClose(false); RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(Image->getDataDescriptor()); FactoryResource<DataRequest> pRequest; DataAccessor pSrcAcc = Image->getDataAccessor(pRequest.release()); RasterDataDescriptor* pDescDSM = static_cast<RasterDataDescriptor*>(pDSM->getDataDescriptor()); FactoryResource<DataRequest> pRequestDSM; DataAccessor pDSMAcc = pDSM->getDataAccessor(pRequestDSM.release()); unsigned int N_Row = int(OrthoGrid.Y_Dim)+1; unsigned int N_Col = int(OrthoGrid.X_Dim)+1; // Check name of raster element // Service<ModelServices> pModel; vector<string> mCubeNames = pModel->getElementNames("RasterElement"); int NameIndex = 0, control=0; stringstream out; string OutputName=Image->getName(); string OutputName1 = OutputName.substr(0,OutputName.find_last_of(".")); while (control == 0) { control = 1; OutputName = OutputName1+"_ortho_"; out << NameIndex; OutputName.append(out.str()+".tiff"); for (unsigned int k=0; k<mCubeNames.size(); k++) { if (OutputName.compare(mCubeNames[k]) == 0) control = 0; } NameIndex++; out.str(""); out.clear(); } // Create output raster element and assoiciated descriptor and accessor // ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(OutputName,N_Row ,N_Col, FLT4BYTES)); RasterDataDescriptor* pResultDesc = static_cast<RasterDataDescriptor*> (pResultCube->getDataDescriptor()); FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); double NodeLat, NodeLon, H_IJ=0; //int DSM_I, DSM_J; for (unsigned int row = 0; row < N_Row; ++row) { if (pProgress != NULL) { pProgress->updateProgress("Calculating result", row * 100 / N_Row, NORMAL); } if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pProgress->updateProgress(msg, 0, ERRORS); pStep->finalize(Message::Failure, msg); return false; } for (unsigned int col = 0; col < N_Col; ++col) { NodeLat = OrthoGrid.Lat_Min+row*OrthoGrid.Lat_Step; NodeLon = OrthoGrid.Lon_Min+col*OrthoGrid.Lon_Step; // RETRIEVE HEIGHT VALUE FROM DSM if (DSM_resampling == 0) { int DSM_I = int((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step); int DSM_J = pDescDSM->getRowCount() - int((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step); pDSMAcc->toPixel(DSM_J,DSM_I); VERIFY(pDSMAcc.isValid()); H_IJ = (pDSMAcc->getColumnAsDouble()); } else { double DSM_I = ((NodeLon - DSMGrid.Lon_Min)/DSMGrid.Lon_Step); double DSM_J = pDescDSM->getRowCount() - ((NodeLat - DSMGrid.Lat_Min)/DSMGrid.Lat_Step); H_IJ = bilinear_height(pDSMAcc,DSM_I,DSM_J); } P_COORD NodeImage = Model->SAR_GroundToImage(NodeLon,NodeLat,H_IJ+Geoid_Offset); if ((NodeImage.I>1 && NodeImage.I< Model->Metadata.Width-1) && (NodeImage.J>1 && NodeImage.J< Model->Metadata.Height-1)) { switchOnEncoding(pResultDesc->getDataType(), copypixel3, pDestAcc->getColumn(), pSrcAcc, int(NodeImage.I), int(NodeImage.J),boxsize, H_IJ); } pDestAcc->nextColumn(); } pDestAcc->nextRow(); } Service<DesktopServices> pDesktop; Service<ModelServices> pMod; GcpList* GcpL = static_cast<GcpList*>(pMod->createElement("corner coordinate","GcpList",pResultCube.get())); // Update GCPs Information: to account for Opticks reading gcp lat&lon values the opposite way around, // here it is necessary to switch the value to assign lat to gcp.mCoordinate.mX and lon to gcp.mCoordinate.mY GcpPoint Punto; Punto.mCoordinate.mX = OrthoGrid.Lat_Min; Punto.mCoordinate.mY = OrthoGrid.Lon_Min; Punto.mCoordinate.mZ = 0.0; Punto.mPixel.mX = 0.0; Punto.mPixel.mY = 0.0; GcpL->addPoint(Punto); Punto.mCoordinate.mX = OrthoGrid.Lat_Max; Punto.mCoordinate.mY = OrthoGrid.Lon_Min; Punto.mCoordinate.mZ = 0.0; Punto.mPixel.mX = 0.0; Punto.mPixel.mY = OrthoGrid.Y_Dim; GcpL->addPoint(Punto); Punto.mCoordinate.mX = OrthoGrid.Lat_Min; Punto.mCoordinate.mY = OrthoGrid.Lon_Max; Punto.mCoordinate.mZ = 0.0; Punto.mPixel.mX = OrthoGrid.X_Dim; Punto.mPixel.mY = 0.0; GcpL->addPoint(Punto); Punto.mCoordinate.mX = OrthoGrid.Lat_Max; Punto.mCoordinate.mY = OrthoGrid.Lon_Max; Punto.mCoordinate.mZ = 0.0; Punto.mPixel.mX = OrthoGrid.X_Dim; Punto.mPixel.mY = OrthoGrid.Y_Dim; GcpL->addPoint(Punto); SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); pView->createLayer(GCP_LAYER,GcpL,"GCP"); pView->setDataOrigin(LOWER_LEFT); pResultCube.release(); pProgress->updateProgress("Orthorectification is complete.", 100, NORMAL); pStep->addStep("End","app", "B4D426EC-E06D-11E1-83C8-42E56088709B"); pStep->finalize(); return true; }
bool SamAlgorithm::processAll() { auto_ptr<Wavelengths> pWavelengths; ProgressTracker progress(getProgress(), "Starting SAM", "spectral", "C4320027-6359-4F5B-8820-8BC72BF1B8F0"); progress.getCurrentStep()->addProperty("Interactive", isInteractive()); RasterElement* pElement = getRasterElement(); if (pElement == NULL) { progress.report(SAMERR012, 0, ERRORS, true); return false; } progress.getCurrentStep()->addProperty("Cube", pElement->getName()); const RasterDataDescriptor* pDescriptor = static_cast<RasterDataDescriptor*>(pElement->getDataDescriptor()); VERIFY(pDescriptor != NULL); BitMaskIterator iter(getPixelsToProcess(), pElement); unsigned int numRows = iter.getNumSelectedRows(); unsigned int numColumns = iter.getNumSelectedColumns(); unsigned int numBands = pDescriptor->getBandCount(); Opticks::PixelOffset layerOffset(iter.getColumnOffset(), iter.getRowOffset()); // get cube wavelengths DynamicObject* pMetadata = pElement->getMetadata(); if (pMetadata != NULL) { pWavelengths.reset(new Wavelengths(pMetadata)); if (!pWavelengths->isEmpty() && (!pWavelengths->hasEndValues() || !pWavelengths->hasStartValues())) { pWavelengths->calculateFwhm(); } } VERIFY(pWavelengths.get() != NULL); int sig_index = 0; bool bSuccess = true; if (mInputs.mSignatures.empty()) { progress.report(SAMERR005, 0, ERRORS, true); return false; } int iSignatureCount = mInputs.mSignatures.size(); // Get colors for all the signatures vector<ColorType> layerColors, excludeColors; excludeColors.push_back(ColorType(0, 0, 0)); excludeColors.push_back(ColorType(255, 255, 255)); ColorType::getUniqueColors(iSignatureCount, layerColors, excludeColors); // Create a vector for the signature names vector<string> sigNames; // Create a pseudocolor results matrix if necessary RasterElement* pPseudocolorMatrix = NULL; RasterElement* pLowestSAMValueMatrix = NULL; // Check for multiple Signatures and if the user has selected // to combined multiple results in one pseudocolor output layer if (iSignatureCount > 1 && mInputs.mbCreatePseudocolor) { pPseudocolorMatrix = createResults(numRows, numColumns, mInputs.mResultsName); pLowestSAMValueMatrix = createResults(numRows, numColumns, "LowestSAMValue"); if (pPseudocolorMatrix == NULL || pLowestSAMValueMatrix == NULL ) { progress.report(SAMERR007, 0, ERRORS, true); return false; } FactoryResource<DataRequest> pseudoRequest; pseudoRequest->setWritable(true); string failedDataRequestErrorMessage = SpectralUtilities::getFailedDataRequestErrorMessage(pseudoRequest.get(), pPseudocolorMatrix); DataAccessor pseudoAccessor = pPseudocolorMatrix->getDataAccessor(pseudoRequest.release()); if (!pseudoAccessor.isValid()) { string msg = "Unable to access results."; if (!failedDataRequestErrorMessage.empty()) { msg += "\n" + failedDataRequestErrorMessage; } progress.report(msg, 0, ERRORS, true); return false; } FactoryResource<DataRequest> lsvRequest; lsvRequest->setWritable(true); failedDataRequestErrorMessage = SpectralUtilities::getFailedDataRequestErrorMessage(lsvRequest.get(), pLowestSAMValueMatrix); DataAccessor lowestSamValueAccessor = pLowestSAMValueMatrix->getDataAccessor(lsvRequest.release()); if (!lowestSamValueAccessor.isValid()) { string msg = "Unable to access results."; if (!failedDataRequestErrorMessage.empty()) { msg += "\n" + failedDataRequestErrorMessage; } progress.report(msg, 0, ERRORS, true); return false; } //Lets zero out all the results incase we connect to an existing matrix. float* pPseudoValue = NULL; float* pLowestValue = NULL; for (unsigned int row_ctr = 0; row_ctr < numRows; row_ctr++) { for (unsigned int col_ctr = 0; col_ctr < numColumns; col_ctr++) { if (!pseudoAccessor.isValid() || !lowestSamValueAccessor.isValid()) { progress.report("Unable to access results.", 0, ERRORS, true); return false; } pLowestValue = reinterpret_cast<float*>(lowestSamValueAccessor->getColumn()); pPseudoValue = reinterpret_cast<float*>(pseudoAccessor->getColumn()); //Initialize the matrices *pPseudoValue = 0.0f; *pLowestValue = 180.0f; pseudoAccessor->nextColumn(); lowestSamValueAccessor->nextColumn(); } pseudoAccessor->nextRow(); lowestSamValueAccessor->nextRow(); } } RasterElement* pResults = NULL; bool resultsIsTemp = false; // Processes each selected signature one at a time and // accumulates results for (sig_index = 0; bSuccess && (sig_index < iSignatureCount) && !mAbortFlag; sig_index++) { // Get the spectrum Signature* pSignature = mInputs.mSignatures[sig_index]; // Create the results matrix sigNames.push_back(pSignature->getName()); std::string rname = mInputs.mResultsName; if (iSignatureCount > 1 && !mInputs.mbCreatePseudocolor) { rname += " " + sigNames.back(); } else if (iSignatureCount > 1) { rname += "SamTemp"; resultsIsTemp = true; } pResults = createResults(numRows, numColumns, rname); if (pResults == NULL) { bSuccess = false; break; } //Send the message to the progress object QString messageSigNumber = QString("Processing Signature %1 of %2 : SAM running on signature %3") .arg(sig_index+1).arg(iSignatureCount).arg(QString::fromStdString(sigNames.back())); string message = messageSigNumber.toStdString(); vector<double> spectrumValues; vector<int> resampledBands; bSuccess = resampleSpectrum(pSignature, spectrumValues, *pWavelengths.get(), resampledBands); // Check for limited spectral coverage and warning log if (bSuccess && pWavelengths->hasCenterValues() && resampledBands.size() != pWavelengths->getCenterValues().size()) { QString buf = QString("Warning SamAlg014: The spectrum only provides spectral coverage for %1 of %2 bands.") .arg(resampledBands.size()).arg(pWavelengths->getCenterValues().size()); progress.report(buf.toStdString(), 0, WARNING, true); } if (bSuccess) { BitMaskIterator iterChecker(getPixelsToProcess(), pElement); SamAlgInput samInput(pElement, pResults, spectrumValues, &mAbortFlag, iterChecker, resampledBands); //Output Structure SamAlgOutput samOutput; // Reports current Spectrum SAM is running on mta::ProgressObjectReporter reporter(message, getProgress()); // Initializes all threads mta::MultiThreadedAlgorithm<SamAlgInput, SamAlgOutput, SamThread> mtaSam(Service<ConfigurationSettings>()->getSettingThreadCount(), samInput, samOutput, &reporter); // Calculates spectral angle for current signature mtaSam.run(); if (samInput.mpResultsMatrix == NULL) { Service<ModelServices>()->destroyElement(pResults); progress.report(SAMERR006, 0, ERRORS, true); mAbortFlag = false; return false; } if ((isInteractive() || mInputs.mbDisplayResults) && iSignatureCount > 1 && mInputs.mbCreatePseudocolor) { // Merges results in to one output layer if a Pseudocolor // output layer has been selected FactoryResource<DataRequest> pseudoRequest, currentRequest, lowestRequest; pseudoRequest->setWritable(true); string failedDataRequestErrorMessage = SpectralUtilities::getFailedDataRequestErrorMessage(pseudoRequest.get(), pPseudocolorMatrix); DataAccessor daPseudoAccessor = pPseudocolorMatrix->getDataAccessor(pseudoRequest.release()); if (!daPseudoAccessor.isValid()) { string msg = "Unable to access data."; if (!failedDataRequestErrorMessage.empty()) { msg += "\n" + failedDataRequestErrorMessage; } progress.report(msg, 0, ERRORS, true); return false; } DataAccessor daCurrentAccessor = pResults->getDataAccessor(currentRequest.release()); lowestRequest->setWritable(true); failedDataRequestErrorMessage = SpectralUtilities::getFailedDataRequestErrorMessage(lowestRequest.get(), pLowestSAMValueMatrix); DataAccessor daLowestSAMValue = pLowestSAMValueMatrix->getDataAccessor(lowestRequest.release()); if (!daLowestSAMValue.isValid()) { string msg = "Unable to access data."; if (!failedDataRequestErrorMessage.empty()) { msg += "\n" + failedDataRequestErrorMessage; } progress.report(msg, 0, ERRORS, true); return false; } float* pPseudoValue = NULL; float* pCurrentValue = NULL; float* pLowestValue = NULL; for (unsigned int row_ctr = 0; row_ctr < numRows; row_ctr++) { for (unsigned int col_ctr = 0; col_ctr < numColumns; col_ctr++) { if (!daPseudoAccessor.isValid() || !daCurrentAccessor.isValid()) { Service<ModelServices>()->destroyElement(pResults); progress.report("Unable to access data.", 0, ERRORS, true); return false; } daPseudoAccessor->toPixel(row_ctr, col_ctr); daCurrentAccessor->toPixel(row_ctr, col_ctr); pPseudoValue = reinterpret_cast<float*>(daPseudoAccessor->getColumn()); pCurrentValue = reinterpret_cast<float*>(daCurrentAccessor->getColumn()); daLowestSAMValue->toPixel(row_ctr, col_ctr); pLowestValue = reinterpret_cast<float*>(daLowestSAMValue->getColumn()); if (*pCurrentValue <= mInputs.mThreshold) { if (*pCurrentValue < *pLowestValue) { *pPseudoValue = sig_index+1; *pLowestValue = *pCurrentValue; } } } } } else { ColorType color; if (sig_index <= static_cast<int>(layerColors.size())) { color = layerColors[sig_index]; } double dMaxValue = pResults->getStatistics()->getMax(); // Displays results for current signature displayThresholdResults(pResults, color, LOWER, mInputs.mThreshold, dMaxValue, layerOffset); } //If we are on the last signature then destroy the lowest value Matrix if (sig_index == iSignatureCount-1) { if (pLowestSAMValueMatrix != NULL) { Service<ModelServices>()->destroyElement(pLowestSAMValueMatrix); pLowestSAMValueMatrix = NULL; } } } } //End of Signature Loop Counter if (resultsIsTemp || !bSuccess) { Service<ModelServices>()->destroyElement(pResults); pResults = NULL; } if (bSuccess) { // Displays final Pseudocolor output layer results if ((isInteractive() || mInputs.mbDisplayResults) && iSignatureCount > 1 && mInputs.mbCreatePseudocolor) { displayPseudocolorResults(pPseudocolorMatrix, sigNames, layerOffset); } } // Aborts gracefully after clean up if (mAbortFlag) { progress.abort(); mAbortFlag = false; return false; } if (bSuccess) { if (pPseudocolorMatrix != NULL) { mpResults = pPseudocolorMatrix; mpResults->updateData(); } else if (pResults != NULL) { mpResults = pResults; mpResults->updateData(); } else { progress.report(SAMERR016, 0, ERRORS, true); return false; } progress.report(SAMNORM200, 100, NORMAL); } progress.getCurrentStep()->addProperty("Display Layer", mInputs.mbDisplayResults); progress.getCurrentStep()->addProperty("Threshold", mInputs.mThreshold); progress.upALevel(); return bSuccess; }
void ConvolutionFilterShell::ConvolutionFilterThread::convolve(const T*) { int numResultsCols = mInput.mpIterCheck->getNumSelectedColumns(); if (mInput.mpResult == NULL) { return; } const RasterDataDescriptor* pResultDescriptor = static_cast<const RasterDataDescriptor*>( mInput.mpResult->getDataDescriptor()); // account for AOIs which extend outside the dataset int maxRowNum = static_cast<int>(mInput.mpDescriptor->getRowCount()) - 1; mRowRange.mFirst = std::max(0, mRowRange.mFirst); mRowRange.mLast = std::min(mRowRange.mLast, maxRowNum); unsigned int bandCount = mInput.mBands.size(); for (unsigned int bandNum = 0; bandNum < bandCount; ++bandNum) { FactoryResource<DataRequest> pResultRequest; pResultRequest->setRows(pResultDescriptor->getActiveRow(mRowRange.mFirst), pResultDescriptor->getActiveRow(mRowRange.mLast)); pResultRequest->setColumns(pResultDescriptor->getActiveColumn(0), pResultDescriptor->getActiveColumn(numResultsCols - 1)); pResultRequest->setBands(pResultDescriptor->getActiveBand(bandNum), pResultDescriptor->getActiveBand(bandNum)); pResultRequest->setWritable(true); DataAccessor resultAccessor = mInput.mpResult->getDataAccessor(pResultRequest.release()); if (!resultAccessor.isValid()) { return; } int oldPercentDone = -1; int rowOffset = static_cast<int>(mInput.mpIterCheck->getOffset().mY); int startRow = mRowRange.mFirst + rowOffset; int stopRow = mRowRange.mLast + rowOffset; int columnOffset = static_cast<int>(mInput.mpIterCheck->getOffset().mX); int startColumn = columnOffset; int stopColumn = numResultsCols + columnOffset - 1; int yshift = (mInput.mKernel.Nrows() - 1) / 2; int xshift = (mInput.mKernel.Ncols() - 1) / 2; FactoryResource<DataRequest> pRequest; pRequest->setRows(mInput.mpDescriptor->getActiveRow(std::max(0, startRow - yshift)), mInput.mpDescriptor->getActiveRow(std::min(maxRowNum, stopRow + mInput.mKernel.Nrows() - yshift))); pRequest->setColumns(mInput.mpDescriptor->getActiveColumn(startColumn), mInput.mpDescriptor->getActiveColumn(stopColumn)); pRequest->setBands(mInput.mpDescriptor->getActiveBand(mInput.mBands[bandNum]), mInput.mpDescriptor->getActiveBand(mInput.mBands[bandNum])); DataAccessor accessor = mInput.mpRaster->getDataAccessor(pRequest.release()); if (!accessor.isValid()) { return; } Service<ModelServices> model; ModelServices* pModel = model.get(); int numRows = stopRow - startRow + 1; for (int row_index = startRow; row_index <= stopRow; ++row_index) { int percentDone = 100 * ((bandNum * numRows) + (row_index - startRow)) / (numRows * bandCount); if (percentDone > oldPercentDone) { oldPercentDone = percentDone; getReporter().reportProgress(getThreadIndex(), percentDone); } if (mInput.mpAbortFlag != NULL && *mInput.mpAbortFlag) { break; } for (int col_index = startColumn; col_index <= stopColumn; ++col_index) { double accum = 0.0; if (mInput.mpIterCheck->getPixel(col_index, row_index)) { for (int kernelrow = 0; kernelrow < mInput.mKernel.Nrows(); kernelrow++) { int neighbor_row = row_index - yshift + kernelrow; int real_row = std::min(std::max(0, neighbor_row), static_cast<int>(mInput.mpDescriptor->getRowCount()) - 1); for (int kernelcol = 0; kernelcol < mInput.mKernel.Ncols(); kernelcol++) { int neighbor_col = col_index - xshift + kernelcol; int real_col = std::min(std::max(0, neighbor_col), static_cast<int>(mInput.mpDescriptor->getColumnCount()) - 1); accessor->toPixel(real_row, real_col); if (accessor.isValid() == false) { return; } double val = 0.0; pModel->getDataValue<T>(reinterpret_cast<T*>(accessor->getColumn()), COMPLEX_MAGNITUDE, 0, val); accum += mInput.mKernel(kernelrow+1, kernelcol+1) * val / mInput.mKernel.Storage(); } } } if (resultAccessor.isValid() == false) { return; } switchOnEncoding(pResultDescriptor->getDataType(), assignResult, resultAccessor->getColumn(), accum + mInput.mOffset); resultAccessor->nextColumn(); } resultAccessor->nextRow(); } } }
double edgeDetection7(DataAccessor pSrcAcc, int row, int col, int rowSize, int colSize) { int prevCol = std::max(col - 1, 0); int prevRow = std::max(row - 1, 0); int nextCol = std::min(col + 1, colSize - 1); int nextRow = std::min(row + 1, rowSize - 1); int prevCol1 = std::max(col-2,0); int prevRow1= std::max(row-2,0); int nextCol1= std::min(col+2,colSize-1); int nextRow1= std::min(row+2,rowSize-1); pSrcAcc->toPixel(prevRow1, prevCol1); int row1col1 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow1, prevCol); int row1col2 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow1, col); int row1col3 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow1, nextCol); int row1col4 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow1, nextCol1); int row1col5 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow, prevCol1); int row2col1 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow, prevCol); int row2col2 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow, col); int row2col3 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow, nextCol); int row2col4 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(prevRow, nextCol1); int row2col5 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(row, prevCol1); int row3col1 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(row, prevCol); int row3col2 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(row, col); int row3col3 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(row, nextCol); int row3col4 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(row, nextCol1); int row3col5 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow, prevCol1); int row4col1 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow, prevCol); int row4col2 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow, col); int row4col3 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow, nextCol); int row4col4 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow, nextCol1); int row4col5 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow1, prevCol1); int row5col1 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow1, prevCol); int row5col2 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow1, col); int row5col3 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow1, nextCol); int row5col4 = pSrcAcc->getColumnAsInteger(); pSrcAcc->toPixel(nextRow1, nextCol1); int row5col5 = pSrcAcc->getColumnAsInteger(); int g = row1col1 + row1col2 + row1col3 + row1col4 + row1col5 + row2col1 + row2col2 + row2col3 + row2col4 + row2col5 + row3col1 + row3col2 + 24*row3col3 + row3col4 + row3col5 + row4col1 + row4col2 + row4col3 + row4col4 + row4col5 + row5col1 + row5col2 + row5col3 + row5col4 + row5col5; double value = g/159.0; return value; };
bool WaveletKSigmaFilter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Wavelet K-Sigma Filter", "app", "1A4BDC34-5A95-419B-8E53-C92333AFFC3E"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); EncodingType ResultType = pDesc->getDataType(); if (pDesc->getDataType() == INT4SCOMPLEX) { ResultType = INT4SBYTES; } else if (pDesc->getDataType() == FLT8COMPLEX) { ResultType = FLT8BYTES; } FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Noise_Removal_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType)); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); Service<DesktopServices> pDesktop; WaveletKSigmaDlg dlg(pDesktop->getMainWidget()); int stat = dlg.exec(); if (stat != QDialog::Accepted) { // pProgress->updateProgress("Level 4 " + StringUtilities::toDisplayString(dlg.getLevelThreshold(3)) // + " Level5 " + StringUtilities::toDisplayString(dlg.getLevelThreshold(4)), dlg.getLevelThreshold(0), NORMAL); return true; } unsigned int rowLoops; unsigned int colLoops; unsigned int rowIndex = 0; unsigned int colIndex = 0; double ScaleKValue[MAX_WAVELET_LEVELS] = {0.0}; for (int k=0; k<MAX_WAVELET_LEVELS;k++) { ScaleKValue[k] = dlg.getLevelThreshold(k); } if (0 == pDesc->getRowCount()%rowBlocks) { rowLoops = pDesc->getRowCount()/rowBlocks; } else { rowLoops = pDesc->getRowCount()/rowBlocks + 1; } if (0 == pDesc->getColumnCount()%colBlocks) { colLoops = pDesc->getColumnCount()/colBlocks; } else { colLoops = pDesc->getColumnCount()/colBlocks + 1; } for (unsigned int i = 0; i < rowLoops; i++) { if ( rowIndex + rowBlocks > pDesc->getRowCount()) { rowIndex = pDesc->getRowCount() - rowBlocks; } colIndex = 0; for (unsigned int j = 0; j < colLoops; j++) { if ( colIndex + colBlocks > pDesc->getColumnCount()) { colIndex = pDesc->getColumnCount() - colBlocks; } if (pProgress != NULL) { pProgress->updateProgress("Remove result", (i*colLoops+j) / (rowLoops*colLoops), NORMAL); } if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } //Process the data in current block ProcessData(pSrcAcc, pBuffer, rowIndex, colIndex, rowBlocks, colBlocks, ScaleKValue, pDesc->getDataType()); //Output the value for (unsigned int m = 0; m < rowBlocks; m++) { for (unsigned int n = 0; n < colBlocks; n++) { if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pDestAcc->toPixel(rowIndex+m, colIndex+n); switchOnEncoding(ResultType, speckleNoiseRemove, pDestAcc->getColumn(), (pBuffer+m*colBlocks+n)); } } colIndex += colBlocks; } rowIndex += rowBlocks; } if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("Noise removal is compete.", 100, NORMAL); } pOutArgList->setPlugInArgValue("Noise removal Result", pResultCube.release()); pStep->finalize(); return true; }
bool 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; }
bool SignatureLibraryImp::insertSignatures(const vector<Signature*>& signatures) { if (find(signatures.begin(), signatures.end(), static_cast<Signature*>(NULL)) != signatures.end()) { return false; } SignatureLibrary* pInterface = dynamic_cast<SignatureLibrary*>(this); if (!mOriginalAbscissa.empty()) { return false; } const DynamicObject* pMetadata = getMetadata(); VERIFY(pMetadata != NULL); const vector<double>* pWavelengths = dv_cast<vector<double> >(&pMetadata->getAttributeByPath(CENTER_WAVELENGTHS_METADATA_PATH)); if (pWavelengths == NULL || pWavelengths->empty()) { return false; } RasterDataDescriptor* pRasterDescriptor = RasterUtilities::generateRasterDataDescriptor(getName(), pInterface, signatures.size(), pWavelengths->size(), 1, BIP, FLT8BYTES, ON_DISK); if (pRasterDescriptor == NULL) { return false; } ModelResource<RasterElement> pRasterElement (dynamic_cast<RasterElement*>( Service<ModelServices>()->createElement(pRasterDescriptor))); if (pRasterElement.get() == NULL) { return false; } PlugInResource resampler("Resampler"); Resampler* pResampler = dynamic_cast<Resampler*>(resampler.get()); if (pResampler == NULL) { return false; } DataAccessor accessor = pRasterElement->getDataAccessor(); vector<Signature*>::const_iterator ppSignature; int i = 0; for (ppSignature = signatures.begin(); ppSignature != signatures.end(); ++ppSignature, ++i) { if (!accessor.isValid()) { return false; } double* pRasterData = reinterpret_cast<double*>(accessor->getRow()); const vector<double>* pFromData = dv_cast<vector<double> >(&(*ppSignature)->getData("Reflectance")); const vector<double>* pFromWavelengths = dv_cast<vector<double> >(&(*ppSignature)->getData("Wavelength")); if (pFromData == NULL || pFromWavelengths == NULL) { return false; } vector<double> toData; vector<int> toBands; vector<double> toFwhm; string errorMessage; bool success = pResampler->execute(*pFromData, toData, *pFromWavelengths, *pWavelengths, toFwhm, toBands, errorMessage); if (success == false || toBands.size() != pWavelengths->size()) { return false; } std::copy(toData.begin(), toData.end(), pRasterData); accessor->nextRow(); string name = (*ppSignature)->getName(); DataDescriptor* pDataDesc = Service<ModelServices>()->createDataDescriptor(name, "DataElement", pInterface); DataDescriptorImp* pSigDesc = dynamic_cast<DataDescriptorImp*>(pDataDesc); mSignatures.push_back(new LibrarySignatureAdapter(*pSigDesc, SessionItemImp::generateUniqueId(), i, pInterface)); mSignatureNames[name] = mSignatures.back(); } mpOdre.reset(pRasterElement.release()); mOriginalAbscissa = *pWavelengths; notify(SIGNAL_NAME(Subject, Modified)); return true; }
bool SignatureLibraryImp::resample(const vector<double> &abscissa) { if (mpOdre.get() == NULL) { return false; } if (abscissa == mAbscissa) { return true; } PlugInResource resampler("Resampler"); Resampler* pResampler = dynamic_cast<Resampler*>(resampler.get()); if (pResampler == NULL) { return false; } desample(); if (abscissa.empty()) { return true; } RasterDataDescriptor* pDesc = dynamic_cast<RasterDataDescriptor*>(mpOdre->getDataDescriptor()); VERIFY(pDesc != NULL); unsigned int numSigs = pDesc->getRowCount(); if (numSigs == 0) { return true; } mResampledData.resize(numSigs * abscissa.size()); DataAccessor da = mpOdre->getDataAccessor(); if (da.isValid() == false) { desample(); return false; } vector<double> originalOrdinateData(mOriginalAbscissa.size()); vector<double> toData; vector<double> toFwhm; vector<int> toBands; string errorMessage; for (unsigned int i = 0; i < mSignatures.size(); ++i) { switchOnEncoding(pDesc->getDataType(), getOriginalAsDouble, da->getRow(), mOriginalAbscissa.size(), originalOrdinateData); toData.clear(); toData.reserve(mAbscissa.size()); toBands.clear(); toBands.reserve(mAbscissa.size()); bool success = pResampler->execute(originalOrdinateData, toData, mOriginalAbscissa, abscissa, toFwhm, toBands, errorMessage); if (!success || toData.size() != abscissa.size()) { desample(); return false; } std::copy(toData.begin(), toData.end(), &mResampledData[i*abscissa.size()]); da->nextRow(); } mAbscissa = abscissa; mNeedToResample = false; notify(SIGNAL_NAME(Subject, Modified)); return true; }
bool adaptive_median::copyImage4(RasterElement * pRaster, RasterElement * dRaster, int i, Progress * pProgress) { int flag = 0; int size = 3; int sizeMax = MAX_SIZE; VERIFY(pRaster != NULL); RasterDataDescriptor *pDesc = dynamic_cast < RasterDataDescriptor * >(pRaster->getDataDescriptor()); VERIFY(dRaster != NULL); RasterDataDescriptor *rDesc = dynamic_cast < RasterDataDescriptor * >(dRaster->getDataDescriptor()); DimensionDescriptor thirdBand = pDesc->getActiveBand(i); // get active // band // source FactoryResource < DataRequest > pRequest; pRequest->setInterleaveFormat(BSQ); pRequest->setBands(thirdBand, thirdBand); DataAccessor thirdBandDa = pRaster->getDataAccessor(pRequest.release()); thirdBand = rDesc->getActiveBand(i); // destination FactoryResource < DataRequest > pResultRequest; pResultRequest->setWritable(true); pRequest->setInterleaveFormat(BSQ); pResultRequest->setBands(thirdBand, thirdBand); DataAccessor pDestAcc = dRaster->getDataAccessor(pResultRequest.release()); VERIFY(thirdBandDa.isValid()); VERIFY(pDestAcc.isValid()); for (unsigned int curRow = 0; curRow < pDesc->getRowCount(); ++curRow) { for (unsigned int curCol = 0; curCol < pDesc->getColumnCount(); ++curCol) { VERIFY(pDestAcc.isValid()); switchOnEncoding(pDesc->getDataType(), adaptivemedian, pDestAcc->getColumn(), thirdBandDa, curRow, curCol, pDesc->getRowCount(), pDesc->getColumnCount(), size, sizeMax, pProgress, &flag); if (flag == 1 && size <= sizeMax) { // increase window size size = size + 2; curCol--; } else { pDestAcc->nextColumn(); size = 3; flag = 0; } } pDestAcc->nextRow(); } return true; }
bool pagauss::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Tutorial 5", "app", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD54"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX) { std::string msg = "Edge detection cannot be performed on complex types."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Edge_Detection_Result", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType())); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); for (long signed int row = 0; row < pDesc->getRowCount(); ++row) { if (pProgress != NULL) { pProgress->updateProgress("Calculating result", row * 100 / pDesc->getRowCount(), NORMAL); } if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } for (long signed int col = 0; col < pDesc->getColumnCount(); ++col) { switchOnEncoding(pDesc->getDataType(), gauss, pDestAcc->getColumn(), pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount()); pDestAcc->nextColumn(); } pDestAcc->nextRow(); } if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("pagauss is compete.", 100, NORMAL); } pOutArgList->setPlugInArgValue("pagauss_Result", pResultCube.release()); pStep->finalize(); return true; }
bool 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; }
bool Tutorial3::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Tutorial 3", "app", "27170298-10CE-4E6C-AD7A-97E8058C29FF"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pAcc = pCube->getDataAccessor(pRequest.release()); double min = std::numeric_limits<double>::max(); double max = -min; double total = 0.0; for (unsigned int row = 0; row < pDesc->getRowCount(); ++row) { if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } if (!pAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } if (pProgress != NULL) { pProgress->updateProgress("Calculating statistics", row * 100 / pDesc->getRowCount(), NORMAL); } for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col) { switchOnEncoding(pDesc->getDataType(), updateStatistics, pAcc->getColumn(), min, max, total); pAcc->nextColumn(); } pAcc->nextRow(); } unsigned int count = pDesc->getColumnCount() * pDesc->getRowCount(); double mean = total / count; if (pProgress != NULL) { std::string msg = "Minimum value: " + StringUtilities::toDisplayString(min) + "\n" + "Maximum value: " + StringUtilities::toDisplayString(max) + "\n" + "Number of pixels: " + StringUtilities::toDisplayString(count) + "\n" + "Average: " + StringUtilities::toDisplayString(mean); pProgress->updateProgress(msg, 100, NORMAL); } pStep->addProperty("Minimum", min); pStep->addProperty("Maximum", max); pStep->addProperty("Count", count); pStep->addProperty("Mean", mean); pOutArgList->setPlugInArgValue("Minimum", &min); pOutArgList->setPlugInArgValue("Maximum", &max); pOutArgList->setPlugInArgValue("Count", &count); pOutArgList->setPlugInArgValue("Mean", &mean); pStep->finalize(); return true; }
bool 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; }
double bilinear_height(DataAccessor pSrcAcc, double I, double J) { double z1=0,z2=0,z3=0,z4=0; pSrcAcc->toPixel(int(J),int(I)); VERIFY(pSrcAcc.isValid()); z1 = pSrcAcc->getColumnAsDouble(); pSrcAcc->toPixel(int(J)+1,int(I)); VERIFY(pSrcAcc.isValid()); z2 = pSrcAcc->getColumnAsDouble(); pSrcAcc->toPixel(int(J),int(I)+1); VERIFY(pSrcAcc.isValid()); z3 = pSrcAcc->getColumnAsDouble(); pSrcAcc->toPixel(int(J)+1,int(I)+1); VERIFY(pSrcAcc.isValid()); z4 = pSrcAcc->getColumnAsDouble(); double a=0,b=0,c=0,d=0; d = z1; a = (z2-z1); b = (z3-z1); c = (z4+z1-z2-z3); double H = a*(J-int(J))+b*(I-int(I))+c*(I-int(I))*(J-int(J))+d; return H; }
bool 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; }
int eval(Progress* pProgress, vector<DataAccessor>& dataCubes, const vector<EncodingType>& types, int rows, int columns, int bands, char* exp, DataAccessor returnAccessor, bool degrees, char* error, bool cubeMath, bool interactive) { int stringSize = strlen(exp)*2; if (stringSize < 80) { stringSize = 80; } char* pString = new char[stringSize]; int iError = ParseExp(exp, bands, pString, dataCubes.size()); if (iError) { strcpy(error, pString); return -1; } bool lastCharSep = false; int itemsCount = 1; int i; for (i = 0; pString[i]; i++) { if (pString[i] == SEP) { if (lastCharSep == false) { itemsCount++; } lastCharSep = true; } else { lastCharSep = false; } } int* pItems = new int[itemsCount]; pItems[0] = 0; int pos = 1; for (i = 0; pString[i]; i++) { if (pString[i] == SEP) { //Skip multiple SEP's while (pString[i+1] == SEP) { pString[i] = 0; i++; } pItems[pos] = i+1; pos++; pString[i] = 0; } } char ops[] = "+ 2 1 - 2 1 * 2 2 / 2 2 ^ 2 3 sqrt 1 9 sin 1 9 cos 1 9 tan 1 9 log 1 9 log10 1 9 " "log2 1 9 exp 1 9 abs 1 9 asin 1 9 acos 1 9 atan 1 9 sinh 1 9 cosh 1 9 tanh 1 9 sec 1 9 csc 1 9 " "cot 1 9 asec 1 9 acsc 1 9 acot 1 9 sech 1 9 csch 1 9 coth 1 9 rand 1 9 "; DataNode* pTree = BuildTreeFromInfix(ops, pString, pItems, itemsCount, degrees); delete [] pItems; delete [] pString; pItems = NULL; pString = NULL; bool dispDZMes = true; bool dispUDMes = true; bool dispCMMes = true; int j; srand(time(NULL)); int bandCount = 1; if (cubeMath) { bandCount = bands; } float* pReturnValue = NULL; void* pCubeValue = NULL; vector<void*> cubeValues(dataCubes.size()); for (i = 0; i < rows; i++) { for (j = 0; j < columns; j++) { pReturnValue = reinterpret_cast<float*>(returnAccessor->getColumn()); for (unsigned int cubeNum = 0; cubeNum < dataCubes.size(); ++cubeNum) { cubeValues[cubeNum] = dataCubes[cubeNum]->getColumn(); } for (int bandNum = 0; bandNum < bandCount; ++bandNum) { try { float newValue = static_cast<float>(pTree->eval(cubeValues, bandNum, types)); if (RasterUtilities::isBad(newValue)) { throw out_of_range("The value is out of range"); } pReturnValue[bandNum] = newValue; } catch (DivZero) { if (interactive == true) { if (dispDZMes) { MBox mb("Warning", "Warning bandmathfuncs003: Divide By Zero\nSelect 'OK' to continue, \n" "all bad values will be set to 0. \nOr 'Cancel' to cancel the operation.", MB_OK_CANCEL_ALWAYS, NULL); if (mb.exec() == QDialog::Rejected) { return -2; } else if (mb.cbAlways->isChecked()) { dispDZMes = false; } } } else { if (dispDZMes) { if (pProgress != NULL) { pProgress->updateProgress("The band math operation attempted to divide by zero. " "Operation will continue and bad values will be set to 0.", 100 * i / rows, WARNING); } dispDZMes = false; } } memset(pReturnValue, 0, bandCount * sizeof(float)); // clear the point } catch (Undefined) { if (interactive == true) { if (dispUDMes) { MBox mb("Warning", "Warning bandmathfuncs001: Undefined Value\n" "Select 'OK' to continue, \nall bad values will be set to 0. \n" "Or 'Cancel' to cancel the operation.", MB_OK_CANCEL_ALWAYS, NULL); if (mb.exec() == QDialog::Rejected) { return -2; } else if (mb.cbAlways->isChecked()) { dispUDMes = false; } } } else { strcpy(error, "The band math operation encountered an undefined value."); return -1; } memset(pReturnValue, 0, bandCount * sizeof(float)); // clear the point } catch (Complex) { if (interactive == true) { if (dispCMMes) { MBox mb("Warning", "Warning bandmathfuncs002: Math Operation Resulted in a Complex Number\n" "Select 'OK' to continue, \nall bad values will be set to 0.\n" "Or 'Cancel' to cancel the operation.", MB_OK_CANCEL_ALWAYS, NULL); if (mb.exec() == QDialog::Rejected) { return -2; } else if (mb.cbAlways->isChecked()) { dispCMMes = false; } } } else { strcpy(error, "The band math operation resulted in an invalid complex number."); return -1; } memset(pReturnValue, 0, bandCount * sizeof(float)); // clear the point } catch (NoData) { strcpy(error, "The band math operation could not be perfomed because the data is not available."); return -1; } catch (...) { strcpy(error, "The band math operation resulted in a floating point error."); return -1; } } returnAccessor->nextColumn(); for (unsigned int cubeNum = 0; cubeNum < dataCubes.size(); ++cubeNum) { dataCubes[cubeNum]->nextColumn(); } } returnAccessor->nextRow(); for (unsigned int cubeNum = 0; cubeNum < dataCubes.size(); ++cubeNum) { dataCubes[cubeNum]->nextRow(); } if (pProgress != NULL) { pProgress->updateProgress("Band Math", 100 * i / rows, NORMAL); } } return 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 SamThread::ComputeSam(const T* pDummyData) { int reSamBan_index = 0, row_index = 0, col_index = 0; float* pResultsData = NULL; int oldPercentDone = -1; double spectrumMag = 0.0; const T* pData=NULL; const RasterDataDescriptor* pDescriptor = static_cast<const RasterDataDescriptor*>( mInput.mpCube->getDataDescriptor()); unsigned int numCols = pDescriptor->getColumnCount(); unsigned int numBands = pDescriptor->getBandCount(); unsigned int numRows = (mRowRange.mLast - mRowRange.mFirst + 1); int numResultsCols = 0; //Sets area to apply the SAM algortihm to. Either //the entire cube, or a selected ROI. if (mInput.mIterCheck.useAllPixels()) { //Total number of Columns in cube. numResultsCols = numCols; } else { numResultsCols = mInput.mIterCheck.getNumSelectedColumns(); } if (mInput.mpResultsMatrix == NULL) { return; } const RasterDataDescriptor* pResultDescriptor = static_cast<const RasterDataDescriptor*>( mInput.mpResultsMatrix->getDataDescriptor()); // Gets results matrix that was initialized in ProcessAll() mRowRange.mFirst = std::max(0, mRowRange.mFirst); mRowRange.mLast = std::min(mRowRange.mLast, static_cast<int>(pDescriptor->getRowCount()) - 1); FactoryResource<DataRequest> pResultRequest; pResultRequest->setRows(pResultDescriptor->getActiveRow(mRowRange.mFirst), pResultDescriptor->getActiveRow(mRowRange.mLast)); pResultRequest->setColumns(pResultDescriptor->getActiveColumn(0), pResultDescriptor->getActiveColumn(numResultsCols - 1)); pResultRequest->setWritable(true); DataAccessor resultAccessor = mInput.mpResultsMatrix->getDataAccessor(pResultRequest.release()); if (!resultAccessor.isValid()) { return; } // Resamples and sets search signature for (reSamBan_index = 0; reSamBan_index < (int) mInput.mResampledBands.size(); ++reSamBan_index) { spectrumMag += mInput.mSpectrum[reSamBan_index] * mInput.mSpectrum[reSamBan_index]; } spectrumMag = sqrt(spectrumMag); int rowOffset = mInput.mIterCheck.getOffset().mY; int startRow = (mRowRange.mFirst + rowOffset); int stopRow = (mRowRange.mLast + rowOffset); int columnOffset = mInput.mIterCheck.getOffset().mX; int startColumn = columnOffset; int stopColumn = (numResultsCols + columnOffset - 1); FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BIP); pRequest->setRows(pDescriptor->getActiveRow(startRow), pDescriptor->getActiveRow(stopRow)); pRequest->setColumns(pDescriptor->getActiveColumn(startColumn), pDescriptor->getActiveColumn(stopColumn)); DataAccessor accessor = mInput.mpCube->getDataAccessor(pRequest.release()); if (!accessor.isValid()) { return; } for (row_index = startRow; row_index <= stopRow; ++row_index) { int percentDone = mRowRange.computePercent(row_index-rowOffset); if (percentDone > oldPercentDone) { oldPercentDone = percentDone; getReporter().reportProgress(getThreadIndex(), percentDone); } if (mInput.mpAbortFlag != NULL && *mInput.mpAbortFlag) { break; } for (col_index = startColumn; col_index <= stopColumn; ++col_index) { VERIFYNRV(resultAccessor.isValid()); VERIFYNRV(accessor.isValid()); // Pointer to results data pResultsData = reinterpret_cast<float*>(resultAccessor->getColumn()); if (pResultsData == NULL) { return; } if (mInput.mIterCheck.getPixel(col_index, row_index)) { //Pointer to cube/sensor data pData = reinterpret_cast<T*>(accessor->getColumn()); VERIFYNRV(pData != NULL); *pResultsData = 0.0f; double pixelMag = 0.0; double angle =0.0; //Calculates Spectral Angle and Magnitude at current location for (unsigned int reSam_index = 0; reSam_index < mInput.mResampledBands.size(); ++reSam_index) { int resampledBand = mInput.mResampledBands[reSam_index]; double cubeVal = pData[resampledBand]; angle += cubeVal * mInput.mSpectrum[reSam_index]; pixelMag += cubeVal * cubeVal; } pixelMag = sqrt(pixelMag); if (pixelMag != 0.0 && spectrumMag != 0.0) { angle /= (pixelMag * spectrumMag); if (angle < -1.0) { angle = -1.0; } if (angle > 1.0) { angle = 1.0; } angle = (180.0 / 3.141592654) * acos(angle); *pResultsData = angle; } else { *pResultsData = 181.0; } } else { *pResultsData = 181.0; } //Increment Columns resultAccessor->nextColumn(); accessor->nextColumn(); } //Increment Rows resultAccessor->nextRow(); accessor->nextRow(); } }
bool ResultsExporter::writeOutput(ostream &stream) { mMessage = "Exporting results matrix..."; if (mpProgress != NULL) { mpProgress->updateProgress(mMessage, 0, NORMAL); } StepResource pStep(mMessage, "app", "D890E37C-B960-4527-8AAC-D62F2DE7A541"); RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(mpResults->getDataDescriptor()); if (pDescriptor == NULL) { mMessage = "Could not get the results data descriptor!"; if (mpProgress != NULL) { mpProgress->updateProgress(mMessage, 0, ERRORS); } pStep->finalize(Message::Failure); return false; } VERIFY(mpResults != NULL); string name = mpResults->getName(); VERIFY(mpFileDescriptor != NULL); const vector<DimensionDescriptor>& rows = mpFileDescriptor->getRows(); const vector<DimensionDescriptor>& columns = mpFileDescriptor->getColumns(); unsigned int numRows = pDescriptor->getRowCount(); unsigned int numColumns = pDescriptor->getColumnCount(); EncodingType eDataType = pDescriptor->getDataType(); const vector<int>& badValues = pDescriptor->getBadValues(); if (mbMetadata) { stream << APP_NAME << " Results Raster\n"; stream << "Version = 4\n"; stream << "Results Name = " << name << "\n"; DataElement* pParent = mpResults->getParent(); if (pParent != NULL) { stream << "Data Set Name = " << pParent->getName() << "\n"; } stream << "Rows = " << numRows << "\n"; stream << "Columns = " << numColumns << "\n"; string dataType = StringUtilities::toDisplayString(eDataType); stream << "Data Type = " << dataType << "\n"; Statistics* pStatistics = mpResults->getStatistics(); if (pStatistics != NULL) { stream << "Min = " << pStatistics->getMin() << "\n"; stream << "Max = " << pStatistics->getMax() << "\n"; stream << "Average = " << pStatistics->getAverage() << "\n"; stream << "Standard Deviation = " << pStatistics->getStandardDeviation() << "\n\n"; } } RasterElement* pGeo = getGeoreferencedRaster(); DataAccessor da = mpResults->getDataAccessor(); if (!da.isValid()) { mMessage = "Could not access the data in the results raster!"; if (mpProgress != NULL) { mpProgress->updateProgress(mMessage, 0, ERRORS); } pStep->finalize(Message::Failure); return false; } unsigned int activeRowNumber = 0; for (unsigned int r = 0; r < rows.size(); ++r) { if (mbAbort) { mMessage = "Results exporter aborted!"; if (mpProgress != NULL) { mpProgress->updateProgress(mMessage, 0, ABORT); } pStep->finalize(Message::Abort); return false; } DimensionDescriptor rowDim = rows[r]; // Skip to the next row for (; activeRowNumber < rowDim.getActiveNumber(); ++activeRowNumber) { da->nextRow(); } unsigned int activeColumnNumber = 0; for (unsigned int c = 0; c < columns.size(); ++c) { DimensionDescriptor columnDim = columns[c]; // Skip to the next column for (; activeColumnNumber < columnDim.getActiveNumber(); ++activeColumnNumber) { da->nextColumn(); } VERIFY(da.isValid()); double dValue = ModelServices::getDataValue(eDataType, da->getColumn(), COMPLEX_MAGNITUDE, 0); if (isValueExported(dValue, badValues)) { string location = getLocationString(r, c, pGeo); char buffer[1024]; sprintf(buffer, "%lf\n", dValue); stream << name << " " << location << " " << buffer; } } // Update the progress int iProgress = (r * 100) / rows.size(); if (iProgress == 100) { iProgress = 99; } if (mpProgress != NULL) { mpProgress->updateProgress(mMessage, iProgress, NORMAL); } } stream << "\n"; return true; }
bool TextureSegmentation::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("SAR image segmentation", "app", "CC430C1A-9D8C-4bb5-9254-FCF7EECAFA3C"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); EncodingType ResultType = INT1UBYTE; FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Segmentation_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType)); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } if (NULL != pBuffer) { free(pBuffer); } pBuffer = (float *)malloc(sizeof(float)*pDesc->getRowCount()*pDesc->getColumnCount()); MakeSegmentation(pSrcAcc, pBuffer, pBuffer, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType()); //Output the value unsigned int nCount = 0; for (unsigned int j = 0; j < pDesc->getColumnCount(); j++) { for (unsigned int i = 0; i < pDesc->getRowCount(); i++) { if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pDestAcc->toPixel(i, j); switchOnEncoding(ResultType, restoreSegmentationValue, pDestAcc->getColumn(), (pBuffer+nCount)); nCount++; } } if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("Image segmentation is compete.", 100, NORMAL); } pOutArgList->setPlugInArgValue("Image segmentation result", pResultCube.release()); pStep->finalize(); return true; }
bool HIGHPASS::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Tutorial 5", "app", "219F1882-A59F-4835-BE2A-E83C0C8111EB"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "DResult", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType())); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); int rowSize= pDesc->getRowCount(); int colSize = pDesc->getColumnCount(); int zero=0; int prevCol = 0; int prevRow = 0; int nextCol = 0; int nextRow = 0; int prevCol1 = 0; int prevRow1= 0; int nextCol1= 0; int nextRow1= 0; for (unsigned int row = 0; row < pDesc->getRowCount(); ++row) { if (pProgress != NULL) { pProgress->updateProgress("Calculating result", row * 100 / pDesc->getRowCount(), NORMAL); } if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col) { double value=edgeDetection7(pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount()); switchOnEncoding(pDesc->getDataType(), conversion, pDestAcc->getColumn(), value); pDestAcc->nextColumn(); } pDestAcc->nextRow(); } if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("HighPass is compete.", 100, NORMAL); } pOutArgList->setPlugInArgValue("Result", pResultCube.release()); pStep->finalize(); return true; }
bool 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; }
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 SpectralLibraryManager::generateResampledLibrary(const RasterElement* pRaster) { VERIFY(pRaster != NULL); // check that lib sigs are in same units as the raster element const RasterDataDescriptor* pDesc = dynamic_cast<const RasterDataDescriptor*>(pRaster->getDataDescriptor()); VERIFY(pDesc != NULL); const Units* pUnits = pDesc->getUnits(); if (pDesc->getUnits()->getUnitType() != mLibraryUnitType) { if (Service<DesktopServices>()->showMessageBox("Mismatched Units", "The data are not in the " "same units as the spectral library.\n Do you want to continue anyway?", "Yes", "No") == 1) { return false; } } FactoryResource<Wavelengths> pWavelengths; pWavelengths->initializeFromDynamicObject(pRaster->getMetadata(), false); // populate the library with the resampled signatures PlugInResource pPlugIn("Resampler"); Resampler* pResampler = dynamic_cast<Resampler*>(pPlugIn.get()); VERIFY(pResampler != NULL); if (pWavelengths->getNumWavelengths() != pDesc->getBandCount()) { mpProgress->updateProgress("Wavelength information in metadata does not match the number of bands " "in the raster element", 0, ERRORS); return false; } // get resample suitable signatures - leave out signatures that don't cover the spectral range of the data std::vector<std::vector<double> > resampledData; resampledData.reserve(mSignatures.size()); std::vector<Signature*> resampledSignatures; resampledSignatures.reserve(mSignatures.size()); std::vector<std::string> unsuitableSignatures; std::vector<double> sigValues; std::vector<double> sigWaves; std::vector<double> rasterWaves = pWavelengths->getCenterValues(); std::vector<double> rasterFwhm = pWavelengths->getFwhm(); std::vector<double> resampledValues; std::vector<int> bandIndex; DataVariant data; for (std::vector<Signature*>::const_iterator it = mSignatures.begin(); it != mSignatures.end(); ++it) { data = (*it)->getData(SpectralLibraryMatch::getNameSignatureWavelengthData()); VERIFY(data.isValid()); VERIFY(data.getValue(sigWaves)); resampledValues.clear(); data = (*it)->getData(SpectralLibraryMatch::getNameSignatureAmplitudeData()); VERIFY(data.isValid()); VERIFY(data.getValue(sigValues)); double scaleFactor = (*it)->getUnits( SpectralLibraryMatch::getNameSignatureAmplitudeData())->getScaleFromStandard(); for (std::vector<double>::iterator sit = sigValues.begin(); sit != sigValues.end(); ++sit) { *sit *= scaleFactor; } std::string msg; if (pResampler->execute(sigValues, resampledValues, sigWaves, rasterWaves, rasterFwhm, bandIndex, msg) == false || resampledValues.size() != rasterWaves.size()) { unsuitableSignatures.push_back((*it)->getName()); continue; } resampledData.push_back(resampledValues); resampledSignatures.push_back(*it); } if (resampledSignatures.empty()) { std::string errMsg = "None of the signatures in the library cover the spectral range of the data."; if (mpProgress != NULL) { mpProgress->updateProgress(errMsg, 0, ERRORS); return false; } } if (unsuitableSignatures.empty() == false) { std::string warningMsg = "The following library signatures do not cover the spectral range of the data:\n"; for (std::vector<std::string>::iterator it = unsuitableSignatures.begin(); it != unsuitableSignatures.end(); ++it) { warningMsg += *it + "\n"; } warningMsg += "These signatures will not be searched for in the data."; Service<DesktopServices>()->showMessageBox("SpectralLibraryManager", warningMsg); StepResource pStep("Spectral LibraryManager", "spectral", "64B6C87A-A6C3-4378-9B6E-221D89D8707B"); pStep->finalize(Message::Unresolved, warningMsg); } std::string libName = "Resampled Spectral Library"; // Try to get the resampled lib element in case session was restored. If NULL, create a new raster element with // num rows = num valid signatures, num cols = 1, num bands = pRaster num bands RasterElement* pLib = dynamic_cast<RasterElement*>(Service<ModelServices>()->getElement(libName, TypeConverter::toString<RasterElement>(), pRaster)); if (pLib != NULL) { // check that pLib has same number of sigs as SpectralLibraryManager RasterDataDescriptor* pLibDesc = dynamic_cast<RasterDataDescriptor*>(pLib->getDataDescriptor()); VERIFY(pLibDesc != NULL); if (pLibDesc->getRowCount() != mSignatures.size()) { mpProgress->updateProgress("An error occurred during session restore and some signatures were not restored." " Check the spectral library before using.", 0, ERRORS); Service<ModelServices>()->destroyElement(pLib); pLib = NULL; } } bool isNewElement(false); if (pLib == NULL) { pLib = RasterUtilities::createRasterElement(libName, static_cast<unsigned int>(resampledData.size()), 1, pDesc->getBandCount(), FLT8BYTES, BIP, true, const_cast<RasterElement*>(pRaster)); isNewElement = true; } if (pLib == NULL) { mpProgress->updateProgress("Error occurred while trying to create the resampled spectral library", 0, ERRORS); return false; } RasterDataDescriptor* pLibDesc = dynamic_cast<RasterDataDescriptor*>(pLib->getDataDescriptor()); VERIFY(pLibDesc != NULL); // copy resampled data into new element if (isNewElement) { FactoryResource<DataRequest> pRequest; pRequest->setWritable(true); pRequest->setRows(pLibDesc->getActiveRow(0), pLibDesc->getActiveRow(pLibDesc->getRowCount()-1), 1); DataAccessor acc = pLib->getDataAccessor(pRequest.release()); for (std::vector<std::vector<double> >::iterator sit = resampledData.begin(); sit != resampledData.end(); ++sit) { VERIFY(acc->isValid()); void* pData = acc->getColumn(); memcpy(acc->getColumn(), &(sit->begin()[0]), pLibDesc->getBandCount() * sizeof(double)); acc->nextRow(); } // set wavelength info in resampled library pWavelengths->applyToDynamicObject(pLib->getMetadata()); FactoryResource<Units> libUnits; libUnits->setUnitType(mLibraryUnitType); libUnits->setUnitName(StringUtilities::toDisplayString<UnitType>(mLibraryUnitType)); pLibDesc->setUnits(libUnits.get()); } pLib->attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &SpectralLibraryManager::resampledElementDeleted)); mLibraries[pRaster] = pLib; mResampledSignatures[pLib] = resampledSignatures; const_cast<RasterElement*>(pRaster)->attach(SIGNAL_NAME(Subject, Deleted), Slot(this, &SpectralLibraryManager::elementDeleted)); return true; }
bool Deconvolution::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Deconvolution Sharpening", "app", "619F3C8A-FB70-44E0-B211-B116E604EDDA"); if (pInArgList == NULL || pOutArgList == NULL) { return false; } Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); EncodingType ResultType = pDesc->getDataType(); if (pDesc->getDataType() == INT4SCOMPLEX) { ResultType = INT4SBYTES; } else if (pDesc->getDataType() == FLT8COMPLEX) { ResultType = FLT8BYTES; } FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Deconvolution_Sharpening_Result", pDesc->getRowCount(), pDesc->getColumnCount(), ResultType)); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); Service<DesktopServices> pDesktop; DeconvolutionDlg dlg(pDesktop->getMainWidget()); int stat = dlg.exec(); if (stat != QDialog::Accepted) { return true; } double minGrayValue; double maxGrayValue; double deltaValue = 0.0; int nFilterType = dlg.getCurrentFilterType(); int windowSize = dlg.getCurrentWindowSize(); double sigmaVal = dlg.getSigmaValue(); double gamaVal = dlg.getGamaValue(); windowSize = (windowSize-1)/2; if (NULL != pOriginalImage) { free(pOriginalImage); } pOriginalImage = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount()); double *OrigData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount()); double *NewData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount()); double *ConvoData = (double *)malloc(sizeof(double)*pDesc->getRowCount()*pDesc->getColumnCount()); double *pTempData; InitializeData(pSrcAcc, pOriginalImage, OrigData, pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType()); GetGrayScale(&minGrayValue, &maxGrayValue, pDesc->getDataType()); //Perform deconvolution iteratively for (int num = 0; num < MAX_ITERATION_NUMBER; num++) { if (pProgress != NULL) { pProgress->updateProgress("Deconvolution process", num*100/MAX_ITERATION_NUMBER, NORMAL); } if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } free(OrigData); free(NewData); free(ConvoData); return false; } deltaValue = DeconvolutionFunc(OrigData, pOriginalImage, NewData, ConvoData, sigmaVal, gamaVal, windowSize, pDesc->getRowCount(), pDesc->getColumnCount(), nFilterType, maxGrayValue, minGrayValue); pTempData = OrigData; OrigData = NewData; NewData = pTempData; double errorRate = deltaValue/(maxGrayValue-minGrayValue); if (errorRate < CONVERGENCE_THRESHOLD) { break; } } free(NewData); free(ConvoData); //Output result unsigned int nCount = 0; for (int i = 0; i < pDesc->getRowCount(); i++) { for (int j = 0; j < pDesc->getColumnCount(); j++) { if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } free(OrigData); return false; } pDestAcc->toPixel(i, j); switchOnEncoding(ResultType, restoreImageValue, pDestAcc->getColumn(), (OrigData+nCount)); nCount++; } } free(OrigData); if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("Deconvolution enhancement is complete.", 100, NORMAL); } pOutArgList->setPlugInArgValue("Deconvolution enhancement Result", pResultCube.release()); pStep->finalize(); return true; }
bool conservative_filter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { StepResource pStep("Conservative", "Filter", "5EA0CC75-9E0B-4c3d-BA23-6DB7157BBD55"); //what is this? if (pInArgList == NULL || pOutArgList == NULL) { return false; } Service <DesktopServices> pDesktop; conservative_filter_ui dialog(pDesktop->getMainWidget()); int status = dialog.exec(); if (status == QDialog::Accepted) { int radius = dialog.getRadiusValue(); Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); RasterElement* pCube = pInArgList->getPlugInArgValue<RasterElement>(Executable::DataElementArg()); if (pCube == NULL) { std::string msg = "A raster cube must be specified."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pCube->getDataDescriptor()); VERIFY(pDesc != NULL); if (pDesc->getDataType() == INT4SCOMPLEX || pDesc->getDataType() == FLT8COMPLEX) { std::string msg = "Conservative Filter cannot be performed on complex types."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pRequest; pRequest->setInterleaveFormat(BSQ); DataAccessor pSrcAcc = pCube->getDataAccessor(pRequest.release()); ModelResource<RasterElement> pResultCube(RasterUtilities::createRasterElement(pCube->getName() + "_Conservative_Filter_Result", pDesc->getRowCount(), pDesc->getColumnCount(), pDesc->getDataType())); if (pResultCube.get() == NULL) { std::string msg = "A raster cube could not be created."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } FactoryResource<DataRequest> pResultRequest; pResultRequest->setWritable(true); DataAccessor pDestAcc = pResultCube->getDataAccessor(pResultRequest.release()); for (unsigned int row = 0; row < pDesc->getRowCount(); ++row) { if (pProgress != NULL) { pProgress->updateProgress("Applying Conservative Filter", row * 100 / pDesc->getRowCount(), NORMAL); } if (isAborted()) { std::string msg = getName() + " has been aborted."; pStep->finalize(Message::Abort, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ABORT); } return false; } if (!pDestAcc.isValid()) { std::string msg = "Unable to access the cube data."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } for (unsigned int col = 0; col < pDesc->getColumnCount(); ++col) { switchOnEncoding(pDesc->getDataType(), verifyRange, pDestAcc->getColumn(), pSrcAcc, row, col, pDesc->getRowCount(), pDesc->getColumnCount(), radius); pDestAcc->nextColumn(); } pDestAcc->nextRow(); } if (!isBatch()) { Service<DesktopServices> pDesktop; SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow(pResultCube->getName(), SPATIAL_DATA_WINDOW)); SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView(); if (pView == NULL) { std::string msg = "Unable to create view."; pStep->finalize(Message::Failure, msg); if (pProgress != NULL) { pProgress->updateProgress(msg, 0, ERRORS); } return false; } pView->setPrimaryRasterElement(pResultCube.get()); pView->createLayer(RASTER, pResultCube.get()); } if (pProgress != NULL) { pProgress->updateProgress("COnservative Filter is complete", 100, NORMAL); } pOutArgList->setPlugInArgValue("conservative_filter_result", pResultCube.release()); pStep->finalize(); } return true; }