DynamicObject* DisplayQueryOptions::toDynamicObject() const
{
   DynamicObject* pDynObj = QueryOptions::toDynamicObject();
   VERIFYRV(pDynObj != NULL, NULL);

   pDynObj->setAttribute(UNIQUE_NAME, mUniqueName);
   pDynObj->setAttribute(CHECKED, mbQueryActive);
   pDynObj->setAttribute(ORDER, mOrder);

   return pDynObj;
}
Exemple #2
0
void FeatureClassDlg::addField()
{
    // Assign a unique default name for the field
    int fieldNumber = 1;
    QString fieldName = "Field_" + QString::number(fieldNumber);
    while (mpFieldTree->findItems(fieldName, Qt::MatchExactly, 0).empty() == false)
    {
        fieldName = "Field_" + QString::number(++fieldNumber);
    }

    // Add the field to the member DynamicObject
    DynamicObject* pClass = getCurrentFeatureClass();
    if (pClass != NULL)
    {
        pClass->setAttribute(fieldName.toStdString(), std::string());
    }

    // Create a new tree widget item and select it
    QTreeWidgetItem* pFieldItem = new QTreeWidgetItem();
    pFieldItem->setData(0, Qt::UserRole, QVariant(fieldName));
    pFieldItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
    pFieldItem->setText(0, fieldName);
    pFieldItem->setText(1, "string");

    mpFieldTree->addTopLevelItem(pFieldItem);
    mpFieldTree->setCurrentItem(pFieldItem);
}
bool ModuleDescriptor::updateSettings(DynamicObject& settings) const
{
   VERIFY(mCanCache);
   QByteArray moduleBlob;
   QDataStream moduleStream(&moduleBlob, QIODevice::WriteOnly);
   moduleStream << QString::fromStdString(getId());
   moduleStream << static_cast<quint64>(mFileDate.getStructured());
   moduleStream << mFileSize;
   moduleStream << QString::fromStdString(mFileName);
   moduleStream << QString::fromStdString(getName());
   moduleStream << QString::fromStdString(mVersion);
   moduleStream << QString::fromStdString(mDescription);
   moduleStream << mPlugInTotal;
   moduleStream << QString::fromStdString(mValidationKey);
   moduleStream << mModuleVersion;
   moduleStream << QString::fromStdString(mInstantiateSymbol);
   vector<PlugInDescriptorImp*>::const_iterator ppDescriptor;
   bool plugInSettingsSaved = true;
   for (ppDescriptor=mPlugins.begin(); ppDescriptor!=mPlugins.end(); ++ppDescriptor)
   {
      PlugInDescriptorImp* pDescriptor = *ppDescriptor;
      if (pDescriptor == NULL)
      {
         return false;
      }
      plugInSettingsSaved = pDescriptor->updateSettings(moduleStream);
      if (!plugInSettingsSaved)
      {
         return false;
      }
   }
   settings.setAttribute("details", string(moduleBlob.toBase64().constData()));
   //NOTE: not serializing mCanCache on purpose, since calling this function means it's being cached.
   return true;
}
DynamicObject* FeatureQueryOptions::toDynamicObject() const
{
   DynamicObject* pDynObj = QueryOptions::toDynamicObject();
   VERIFYRV(pDynObj != NULL, NULL);
   pDynObj->setAttribute(FORMAT_STRING, mFormatString);
   return pDynObj;
}
bool DynamicObjectImp::setAttributeByPath(QStringList pathComponents, DataVariant& value, bool swap)
{
   if (!value.isValid())
   {
      return false;
   }

   QString finalName = pathComponents.back();
   pathComponents.pop_back();

   string loopType = "DynamicObject";
   DynamicObject* pLoopObj = dynamic_cast<DynamicObject*>(this);
   DynamicObject* pCurObj = pLoopObj;
   for (QStringList::const_iterator iter = pathComponents.begin();
      iter != pathComponents.end(); ++iter)
   {
      if (pLoopObj == NULL || loopType != "DynamicObject")
      {
         return false;
      }

      pCurObj = pLoopObj;
      DataVariant& attrValue = pCurObj->getAttribute(iter->toStdString());
      loopType = attrValue.getTypeName();
      pLoopObj = attrValue.getPointerToValue<DynamicObject>();

      if ((pLoopObj != NULL) && (loopType != "DynamicObject"))
      {
         return false;
      }

      if (pLoopObj == NULL)
      {
         FactoryResource<DynamicObject> pNewObj;
         if (pCurObj != NULL)
         {
            pCurObj->setAttribute(iter->toStdString(), *pNewObj.get());
            DataVariant& currentValue = pCurObj->getAttribute(iter->toStdString());
            loopType = currentValue.getTypeName();
            pLoopObj = currentValue.getPointerToValue<DynamicObject>();
         }
      }
   }

   if (pLoopObj == NULL || loopType != "DynamicObject")
   {
      return false;
   }

   pCurObj = pLoopObj;
   DynamicObjectImp* const pCurObjImp = dynamic_cast<DynamicObjectImp*>(pCurObj);
   VERIFY(pCurObjImp != NULL);
   return pCurObjImp->setAttribute(finalName.toStdString(), value, swap);
}
bool Nitf::EngrdaParser::toDynamicObject(std::istream& input,
        size_t numBytes,
        DynamicObject& output,
        std::string &errorMessage) const
{
    std::vector<char> buf;
    bool success(true);

    Nitf::readField<std::string>(input, output, success, ENGRDA::RESRC, 20, errorMessage, buf);
    Nitf::readField<unsigned int>(input, output, success, ENGRDA::RECNT, 3, errorMessage, buf);
    unsigned int recnt = QString(&buf.front()).toUInt();
    for (unsigned int rec = 0; rec < recnt; ++rec)
    {
        std::string recId = QString::number(rec).toStdString();
        {
            FactoryResource<DynamicObject> record;
            output.setAttribute(recId, *record.get());
        }
        DynamicObject& record = dv_cast<DynamicObject>(output.getAttribute(recId));
        unsigned int lbln(0);
        Nitf::readAndConvertFromStream(input, lbln, success, ENGRDA::ENGLN, 2, errorMessage, buf);
        Nitf::readField<std::string>(input, record, success, ENGRDA::ENGLBL, lbln, errorMessage, buf);
        Nitf::readField<unsigned int>(input, record, success, ENGRDA::ENGMTXC, 4, errorMessage, buf);
        Nitf::readField<unsigned int>(input, record, success, ENGRDA::ENGMTXR, 4, errorMessage, buf);
        Nitf::readField<std::string>(input, record, success, ENGRDA::ENGTYP, 1, errorMessage, buf);
        Nitf::readField<unsigned int>(input, record, success, ENGRDA::ENGDTS, 1, errorMessage, buf);
        int dts = QString(&buf.front()).toInt(); // bytes per element
        Nitf::readField<std::string>(input, record, success, ENGRDA::ENGDATU, 2, errorMessage, buf);
        unsigned int datc(0); // data count
        Nitf::readAndConvertFromStream(input, datc, success, ENGRDA::ENGDATC, 8, errorMessage, buf);

        // read the data
        Nitf::readFromStream(input, buf, datc * dts, false);
        record.setAttribute(ENGRDA::ENGDATA, Blob(&buf.front(), buf.size()));
    }

    int64_t numRead = input.tellg();
    if (numRead < 0 || static_cast<uint64_t>(numRead) > std::numeric_limits<size_t>::max() ||
            numRead != static_cast<int64_t>(numBytes))
    {
        numReadErrMsg(numRead, numBytes, errorMessage);
        return false;
    }

    return success;
}
Exemple #7
0
void FeatureClassDlg::setFieldData(QTreeWidgetItem* pItem, int column)
{
    if (pItem == NULL)
    {
        return;
    }

    DynamicObject* pClass = getCurrentFeatureClass();
    if (pClass == NULL)
    {
        return;
    }

    QString fieldName = pItem->text(0);
    if (column == 0)     // Name
    {
        QString oldFieldName = pItem->data(column, Qt::UserRole).toString();
        if (fieldName == oldFieldName)
        {
            return;
        }

        if (mpFieldTree->findItems(fieldName, Qt::MatchExactly, column).count() > 1)
        {
            QMessageBox::warning(this, windowTitle(), "Another field exists with the same name.  "
                                 "Please choose a unique name for the field.");
            pItem->setText(column, oldFieldName);
            return;
        }

        DataVariant field = pClass->getAttribute(oldFieldName.toStdString());
        pClass->removeAttribute(oldFieldName.toStdString());
        pClass->setAttribute(fieldName.toStdString(), field);

        pItem->setData(column, Qt::UserRole, QVariant(fieldName));
    }
    else                 // Type or Value
    {
        QString fieldType = pItem->text(1);
        QString fieldValue = pItem->text(2);

        if (column == 1)  // Type
        {
            // If the type changed, ensure that the value is valid with the new type and reset the value if necessary
            QString validateString = fieldValue;
            int pos = 0;

            if (fieldType == "int")
            {
                QIntValidator validator(this);
                if (validator.validate(validateString, pos) != QValidator::Acceptable)
                {
                    pItem->setText(2, "0");
                    return;     // Return since this method will be called again as a result to changing the value text
                }
            }
            else if (fieldType == "double")
            {
                QDoubleValidator validator(this);
                if (validator.validate(fieldValue, pos) != QValidator::Acceptable)
                {
                    pItem->setText(2, "0.0");
                    return;     // Return since this method will be called again as a result to changing the value text
                }
            }
        }

        DataVariant field;
        if (fieldType == "int")
        {
            int intValue = fieldValue.toInt();
            field = DataVariant(intValue);
        }
        else if (fieldType == "double")
        {
            double doubleValue = fieldValue.toDouble();
            field = DataVariant(doubleValue);
        }
        else if (fieldType == "string")
        {
            std::string stringValue = fieldValue.toStdString();
            field = DataVariant(stringValue);
        }

        pClass->setAttribute(fieldName.toStdString(), field);
    }
}
Exemple #8
0
bool Nitf::RpcParser::ossimTagToDynamicObject(const ossimNitfRegisteredTag& input, DynamicObject& output,
   string &errorMessage) const
{
   const ossimNitfRegisteredTag* pInput = &input;
   const ossimNitfRpcBase* pBase = PTR_CAST(ossimNitfRpcBase, pInput);

   if (pBase != NULL)
   {
      bool status = output.setAttribute(SUCCESS, pBase->getSuccess());
      status = status && output.setAttribute(SAMP_SCALE, pBase->getSampleScale().toUInt32());
      status = status && output.setAttribute(SAMP_OFFSET, pBase->getSampleOffset().toUInt32());
      status = status && output.setAttribute(LONG_SCALE, pBase->getGeodeticLonScale().toDouble());
      status = status && output.setAttribute(LONG_OFFSET, pBase->getGeodeticLonOffset().toDouble());
      status = status && output.setAttribute(LINE_SCALE, pBase->getLineScale().toUInt32());
      status = status && output.setAttribute(LINE_OFFSET, pBase->getLineOffset().toUInt32());
      status = status && output.setAttribute(LAT_SCALE, pBase->getGeodeticLatScale().toDouble());
      status = status && output.setAttribute(LAT_OFFSET, pBase->getGeodeticLatOffset().toDouble());
      status = status && output.setAttribute(HEIGHT_SCALE, pBase->getGeodeticHeightScale().toInt());
      status = status && output.setAttribute(HEIGHT_OFFSET, pBase->getGeodeticHeightOffset().toInt());
      status = status && output.setAttribute(ERR_RAND, pBase->getErrorRand().toDouble());
      status = status && output.setAttribute(ERR_BIAS, pBase->getErrorBias().toDouble());

      unsigned int u;
      for (u = 1; u <= 20; ++u)
      {
         double coeff = pBase->getLineNumeratorCoeff(u-1).toDouble();
         status = status && output.setAttribute(getRpcCoefficient(LINE_NUMERATOR_COEF_PREFIX, u), coeff);
      }
      for (u = 1; u <= 20; ++u)
      {
         double coeff = pBase->getLineDenominatorCoeff(u-1).toDouble();
         status = status && output.setAttribute(getRpcCoefficient(LINE_DENOMINATOR_COEF_PREFIX, u), coeff);
      }
      for (u = 1; u <= 20; ++u)
      {
         double coeff = pBase->getSampleNumeratorCoeff(u-1).toDouble();
         status = status && output.setAttribute(getRpcCoefficient(SAMPLE_NUMERATOR_COEF_PREFIX, u), coeff);
      }
      for (u = 1; u <= 20; ++u)
      {
         double coeff = pBase->getSampleDenominatorCoeff(u-1).toDouble();
         status = status && output.setAttribute(getRpcCoefficient(SAMPLE_DENOMINATOR_COEF_PREFIX, u), coeff);
      }

      return status;
   }

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

   Service<DesktopServices> pDesktop;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   mXOffset = x1;
   mYOffset = y1;

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

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

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

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

   pLabels.release();
   mProgress.report("Labeling connected components", 100, NORMAL);
   mProgress.upALevel();
   return true;
}
Exemple #11
0
bool Nitf::StdidcParser::toDynamicObject(istream& input, size_t numBytes, DynamicObject& output,
   string &errorMessage) const
{
   vector<char> buf;
   bool ok(true);
   bool success(true);

   success = readFromStream(input, buf, 14);  // CCYYMMDDHHMMSS

   FactoryResource<DateTime> appDTG;

   string dtg;
   dtg.resize(15);
   memcpy(&dtg[0], &buf[0], 15);

   bool dateValid(false);
   bool timeValid(false);
   unsigned short year(0);
   unsigned short month(0);
   unsigned short day(0);
   unsigned short hour;
   unsigned short min;
   unsigned short sec;

   if (success)
   {
      success = DtgParseCCYYMMDDhhmmss(dtg, year, month, day, hour, min, sec, &dateValid, &timeValid);
   }

   if (success)
   {
      success = appDTG->set(year, month, day, hour, min, sec);
      if (success)
      {
         success = output.setAttribute(STDIDC::ACQUISITION_DATE, *appDTG.get());
      }
   }
   if (!success)
   {
      errorMessage += "Parsing " + STDIDC::ACQUISITION_DATE + " failed\n";
   }

   readField<string>(input, output, success, STDIDC::MISSION, 14, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::PASS, 2, errorMessage, buf);
   readField<unsigned int>(input, output, success, STDIDC::OP_NUM, 3, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::START_SEGMENT, 2, errorMessage, buf);
   readField<unsigned int>(input, output, success, STDIDC::REPRO_NUM, 2, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::REPLAY_REGEN, 3, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::BLANK_FILL, 1, errorMessage, buf, true);
   readField<unsigned int>(input, output, success, STDIDC::START_COLUMN, 3, errorMessage, buf);
   readField<unsigned int>(input, output, success, STDIDC::START_ROW, 5, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::END_SEGMENT, 2, errorMessage, buf);
   readField<unsigned int>(input, output, success, STDIDC::END_COLUMN, 3, errorMessage, buf);
   readField<unsigned int>(input, output, success, STDIDC::END_ROW, 5, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::COUNTRY, 2, errorMessage, buf, true);
   readField<unsigned int>(input, output, success, STDIDC::WAC, 4, errorMessage, buf, true);
   readField<string>(input, output, success, STDIDC::LOCATION, 11, errorMessage, buf);
   readField<string>(input, output, success, STDIDC::RESERVED2, 5, errorMessage, buf, true);
   readField<string>(input, output, success, STDIDC::RESERVED3, 8, errorMessage, buf, true);

   size_t numRead = input.tellg();
   if (numRead != numBytes)
   {
      numReadErrMsg(numRead, numBytes, errorMessage);
      return false;
   }

   return success;
}
Exemple #12
0
bool Nitf::AimidbParser::toDynamicObject(istream& input, size_t numBytes, DynamicObject& output,
   string &errorMessage) const
{
   vector<char> buf;
   unsigned short yy(0);
   unsigned short mm(0);
   unsigned short dd(0);
   unsigned short hh(0);
   unsigned short min(0);
   unsigned short ss(0);
   bool ok(true);

   bool success = true;

   success = readFromStream(input, buf, 14) && DtgParseCCYYMMDDhhmmss(string(&buf.front()), yy, mm, dd, hh, min, ss);
   if (success)
   {
      FactoryResource<DateTime> appDTG;
      success = appDTG->set(yy, mm, dd, hh, min, ss);
      if (success)
      {
         success = output.setAttribute(AIMIDB::ACQUISITION_DATE, *appDTG.get());
         if (!success)
         {
            errorMessage += "setAttribute " + AIMIDB::ACQUISITION_DATE + " failed\n";
         }
      }
      else
      {
         errorMessage += "DateTime Set " + AIMIDB::ACQUISITION_DATE + " failed\n";
      }
   }
   else
   {
      errorMessage += "Parsing " + AIMIDB::ACQUISITION_DATE + " failed\n";
   }


   readField<string>(input, output, success, AIMIDB::MISSION_NO, 4, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::MISSION_IDENTIFICATION, 10, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::FLIGHT_NO, 2, errorMessage, buf);
   readField<int>(input, output, success, AIMIDB::OP_NUM, 3, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::CURRENT_SEGMENT, 2, errorMessage, buf);
   readField<int>(input, output, success, AIMIDB::REPRO_NUM, 2, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::REPLAY, 3, errorMessage, buf, true);
   readField<string>(input, output, success, AIMIDB::RESERVED1, 1, errorMessage, buf, true);
   readField<int>(input, output, success, AIMIDB::START_TILE_COLUMN, 3, errorMessage, buf);
   readField<int>(input, output, success, AIMIDB::START_TILE_ROW, 5, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::END_SEGMENT, 2, errorMessage, buf);
   readField<int>(input, output, success, AIMIDB::END_TILE_COLUMN, 3, errorMessage, buf);
   readField<int>(input, output, success, AIMIDB::END_TILE_ROW, 5, errorMessage, buf);
   readField<string>(input, output, success, AIMIDB::COUNTRY, 2, errorMessage, buf, true);
   readField<string>(input, output, success, AIMIDB::RESERVED2, 4, errorMessage, buf, true);
   readField<string>(input, output, success, AIMIDB::LOCATION, 11, errorMessage, buf, true);
   readField<string>(input, output, success, AIMIDB::RESERVED3, 13, errorMessage, buf, true);

   size_t numRead = input.tellg();
   if (numRead != numBytes)
   {
      numReadErrMsg(numRead, numBytes, errorMessage);
      return false;
   }

   return success;
}
TreExportStatus Nitf::BandsaParser::exportMetadata(const RasterDataDescriptor &descriptor, 
   const RasterFileDescriptor &exportDescriptor, DynamicObject &tre, 
   unsigned int & ownerIndex, string & tagType, string &errorMessage) const
{
   // Find out if we are exporting a subset of the original bands. If so then delete the
   // band info for the excluded bands.

   const DynamicObject* pMetadata = descriptor.getMetadata();
   VERIFYRV(pMetadata != NULL, REMOVE);
   try
   {
      const DataVariant& nitfMetadata = pMetadata->getAttribute(Nitf::NITF_METADATA);
      const DynamicObject* pExistingBandsa = getTagHandle(dv_cast<DynamicObject>(nitfMetadata), "BANDSA", FindFirst());
      if (!pExistingBandsa)
      {
         return UNCHANGED;
      }

      const vector<DimensionDescriptor>& exportBands = exportDescriptor.getBands();

      VERIFYRV(!exportBands.empty(), REMOVE);

      tre.setAttribute(Nitf::TRE::BANDSA::ROW_SPACING,
         pExistingBandsa->getAttribute(Nitf::TRE::BANDSA::ROW_SPACING));
      tre.setAttribute(Nitf::TRE::BANDSA::ROW_SPACING_UNITS,
         pExistingBandsa->getAttribute(Nitf::TRE::BANDSA::ROW_SPACING_UNITS));
      tre.setAttribute(Nitf::TRE::BANDSA::COL_SPACING,
         pExistingBandsa->getAttribute(Nitf::TRE::BANDSA::COL_SPACING));
      tre.setAttribute(Nitf::TRE::BANDSA::COL_SPACING_UNITS,
         pExistingBandsa->getAttribute(Nitf::TRE::BANDSA::COL_SPACING_UNITS));
      tre.setAttribute(Nitf::TRE::BANDSA::FOCAL_LENGTH,
         pExistingBandsa->getAttribute(Nitf::TRE::BANDSA::FOCAL_LENGTH));

      unsigned int bandcount(0);

      for (vector<DimensionDescriptor>::const_iterator iter = exportBands.begin(); iter != exportBands.end(); ++iter)
      {
         // Use the original band number to find the associated band data in the original TRE
         LOG_IF(!iter->isOriginalNumberValid(), continue);
         unsigned int origBandNum = iter->getOriginalNumber();

         stringstream bandStreamStr;
         bandStreamStr << "#" << bandcount;
         string bandStr(bandStreamStr.str());

         stringstream origBandStreamStr;
         origBandStreamStr << "#" << origBandNum;
         string origBandStr(origBandStreamStr.str());

         ++bandcount;

         string fieldName;
         string origFieldName;

         fieldName = BANDSA::BANDPEAK + bandStr;
         origFieldName = BANDSA::BANDPEAK + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDLBOUND + bandStr;
         origFieldName = BANDSA::BANDLBOUND + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDUBOUND + bandStr;
         origFieldName = BANDSA::BANDUBOUND + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDWIDTH + bandStr;
         origFieldName = BANDSA::BANDWIDTH + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDCALDRK + bandStr;
         origFieldName = BANDSA::BANDCALDRK + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDCALINC + bandStr;
         origFieldName = BANDSA::BANDCALINC + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDRESP + bandStr;
         origFieldName = BANDSA::BANDRESP + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDASD + bandStr;
         origFieldName = BANDSA::BANDASD + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));

         fieldName = BANDSA::BANDGSD + bandStr;
         origFieldName = BANDSA::BANDGSD + origBandStr;
         tre.setAttribute(fieldName, pExistingBandsa->getAttribute(origFieldName));
      }

      tre.setAttribute(Nitf::TRE::BANDSA::BANDCOUNT, bandcount);
   }
   catch (const bad_cast&)
   {
      return REMOVE;
   }
   catch (const string& message)
   {
      errorMessage = message;
      return REMOVE;
   }

   return REPLACE;
}
Exemple #14
0
int main() {


	cout << "Hello world !" << endl;

	DynamicObject toto = DynamicObject("toto");

	shared_ptr<Scalar<float> > pi( new Scalar<float>("float", 3.145) );
	shared_ptr<Integer> age( new Integer(345) );
	shared_ptr<Scalar<Glib::ustring> > phrase ( new Scalar<Glib::ustring>("string", "c'etait un cafard qui vivait dans le noir") );

	toto.setAttribute( Glib::ustring("pi"), pi);
	toto.setAttribute( "phrase", phrase);
	toto.setAttribute( "age", age);

	cout << (*pi)() << endl;
	cout << (*phrase)() << endl;

	cout << "Toto has attribute 'pi' : " << toto.hasAttribute("pi") << endl;
	cout << "Toto has attribute 'phrase' : " << toto.hasAttribute("phrase") << endl;
	cout << "Toto has attribute 'tournoyant' : " << toto.hasAttribute("tournoyant") << endl;

	const Glib::ustring pi_name("pi");


	shared_ptr<Scalar<float> > pi2 = toto.getAttribute< Scalar<float> > (pi_name);
	shared_ptr<Scalar<Glib::ustring> > phrase2 = toto.getAttribute< Scalar<Glib::ustring> > ("phrase");


	cout << "Get attribute 'pi' : " << *pi2 << endl;
	cout << "Get attribute 'phrase' : " << *phrase2 << endl;

	try
	{
		shared_ptr<Scalar<Glib::ustring> > phrase3 = toto.getAttribute< Scalar<Glib::ustring> > ("aioli");
	}
	catch(Glib::ustring e)
	{
		cout << e << endl;
	}


	cout << endl << "Serializationed (I'am sure it exists :) toto : " << endl;

	shared_ptr<xmlpp::Document> output = toto.serializeXML();
	cout << output->write_to_string_formatted()  << endl;


	SourceFile sf("./");

	shared_ptr<IStream> stream = sf.loadStream("testpo.cpp");
	unsigned int bytesRead = 0;
	while (!stream->eof())
	{
		char buffer[256];
		unsigned int nbRead = stream->read(buffer, 255);
		buffer[nbRead] = 0;
//	cout << buffer;
		bytesRead += nbRead;
	}
	stream->close();

	cout << endl << "Bytes Read : " << bytesRead << endl;

	sf.setOverWrite(true);

	shared_ptr<IStream> streamW = sf.saveStream("testpo.cppW");

	unsigned int bytesWritten = streamW->write("Jesuislorsdelajusticeetdel'emeriteca\nvalier", 40);
	streamW->close();

	cout << endl << "Bytes Written : " << bytesWritten << endl;



	shared_ptr<ISource> loadChannel(new SourceFile(".", false));
	shared_ptr<ISource> saveChannel(new SourceFile(".", true));

	DynamicObjectManager *pom = DynamicObjectManager::getInstancePtr();

	pom->addLoadSource(loadChannel);
	pom->addSaveSource(saveChannel);

	shared_ptr<DynamicObject> Zelda = pom->load("zelda");

	shared_ptr<Integer> ageZelda = Zelda->getAttribute< Integer > ("age");
	shared_ptr<Integer> newAge(new Integer((*ageZelda)() + 1));
	Zelda->setAttribute("age2", newAge);


	try
	{

		shared_ptr< Float > piZelda = Zelda->getAttribute< Float > ("pi");
		cout << "Float pi**2 zelda : " << (*piZelda) * (*piZelda) << endl;



		shared_ptr< String > nut = Zelda->getAttribute< String > ("nut");
		cout << "Attribute nut = '" << *nut << "'" << endl;



		shared_ptr< Double > dpi = Zelda->getAttribute< Double > ("dpi");
		cout << "Double PI in Zelda : " << setprecision(16) << *dpi << endl;
		cout << "Squared Double PI in Zelda : " << setprecision(16) << (*dpi) * (*dpi) << endl;


		typedef list< shared_ptr<IAttribute> >::iterator ListIterator;
		shared_ptr< List > list = Zelda->getAttribute< List > ("ListPreums");
		for (ListIterator it = list->begin(); it != list->end(); it++)
		{
			if (shared_ptr<String> str = dynamic_pointer_cast<String>(*it))
			{
				cout << "String element in list : '" << (*str) << "'" << endl;
			}

			if (shared_ptr<Integer> integer = dynamic_pointer_cast<Integer>(*it))
			{
				cout << "Integer element in list : [" << (*integer) + 2 << "]" << endl;
			}

			if (shared_ptr<Double> dbl = dynamic_pointer_cast<Double>(*it))
			{
				cout << "Double element in list : [" << (*dbl) << "]" << endl;
			}

			if (shared_ptr<Float> flt = dynamic_pointer_cast<Float>(*it))
			{
				cout << "Float element in list : [" << (*flt) << "]" << endl;
			}
		}

	}
	catch(Glib::ustring e)
	{
		cout << e << endl;
	}

	pom->save(Zelda->getInstance());

	cout << endl << "Serializationed (I'am sure it exists :) Zelda : " << endl;

	shared_ptr<xmlpp::Document> outputZelda = Zelda->serializeXML();
	cout << outputZelda->write_to_string_formatted()  << endl;


	cout << endl << endl << "--------------------------------------------" << endl << endl;


	shared_ptr<DynamicObject> Zelda2 = pom->load("zelda2");

	shared_ptr<xmlpp::Document> outputZelda2 = Zelda2->serializeXML();
	cout << outputZelda2->write_to_string_formatted()  << endl;

	return 0;
}