예제 #1
0
vector<ImportDescriptor*> CgmImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      FactoryResource<Filename> pFullFilename;
      pFullFilename->setFullPathAndName(filename);

      ImportDescriptor* pImportDescriptor = mpModel->createImportDescriptor(filename, "AnnotationElement", NULL);
      if (pImportDescriptor != NULL)
      {
         DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
         if (pDescriptor != NULL)
         {
            FactoryResource<FileDescriptor> pFileDescriptor;
            if (pFileDescriptor.get() != NULL)
            {
               pFileDescriptor->setFilename(filename);
               pDescriptor->setFileDescriptor(pFileDescriptor.get());
            }
         }

         descriptors.push_back(pImportDescriptor);
      }
   }

   return descriptors;
}
예제 #2
0
int test_rgb888_to_yuv(const unsigned char *src, int w, int h) 
{
   int lRetVal = 0;
   apexcv::ColorConverter rgb;
   
   DataDescriptor srcImg;
		srcImg.InitManual(w/*/4*/, h, (void *)src, (void *)OAL_MemoryReturnAddress((void *)src, ACCESS_PHY), DATATYPE_08U, 4, 1);
   DataDescriptor dstImg(w/*/4*/, h, DATATYPE_08U, 4, 1);
   DataDescriptor dstRefImg(w/*/4*/, h, DATATYPE_08U, 4, 1);
      
   if(srcImg.IsOK() && dstImg.IsOK() && dstRefImg.IsOK()) {
      //run implementation
      lRetVal |= rgb.convert(srcImg, dstImg, ColorConverter::RGB888_TO_YUV);
  
      //obtain dst data pointers
      unsigned char* pDst    = (unsigned char*) dstImg.GetDataPtr();
      unsigned char* pDstRef = (unsigned char*) dstRefImg.GetDataPtr();
      
      //run reference
      rgb888_to_yuv_ref((uint8_t*)pDstRef, w*4, (uint8_t*)src, w*4, w, h);

      if (dstImg == dstRefImg)
			 lRetVal |= 0;
		 else
			 lRetVal |= 1;
   } else {
      lRetVal |= 1;
   }
   
   //free buffers
   dstImg.SetFreeOnExit(true);
   dstRefImg.SetFreeOnExit(true);
   
   return lRetVal;
}
예제 #3
0
int test_rgb565_to_rgb888(const unsigned short *src, int w, int h) 
{
   int lRetVal = 0;
   apexcv::ColorConverter rgb;
   
   DataDescriptor srcImg;
		srcImg.InitManual(w, h, (void *)src, (void *)OAL_MemoryReturnAddress((void *)src, ACCESS_PHY), DATATYPE_16U);
   DataDescriptor dstImg(w, h, DATATYPE_32U);
   DataDescriptor dstRefImg(w, h, DATATYPE_32U);
      
   if(srcImg.IsOK() && dstImg.IsOK() && dstRefImg.IsOK()) {
      //run implementation
      lRetVal |= rgb.convert(srcImg, dstImg, apexcv::ColorConverter::RGB565_TO_RGB888);
  
      //obtain dst data pointers
      unsigned int* pDst    = (unsigned int*) dstImg.GetDataPtr();
      unsigned int* pDstRef = (unsigned int*) dstRefImg.GetDataPtr();
      
      //run reference
      rgb565_to_rgb888_ref(pDstRef, w, src, w, w, h);

      if (dstImg == dstRefImg)
			 lRetVal |= 0;
		 else
			 lRetVal |= 1;
   } else {
      lRetVal |= 1;
   }
   
   //free buffers
   dstImg.SetFreeOnExit(true);
   dstRefImg.SetFreeOnExit(true);
   
   return lRetVal;
}
예제 #4
0
bool EngrdaWidget::initialize(SessionItem* pSessionItem)
{
   DataElement* pElement = dynamic_cast<DataElement*>(pSessionItem);
   DataDescriptor* pDesc = (pElement == NULL) ? NULL : pElement->getDataDescriptor();
   const DynamicObject* pMeta = (pDesc == NULL) ? NULL : pDesc->getMetadata();
   return initialize(pMeta);
}
bool PropertiesFileDescriptor::initialize(SessionItem* pSessionItem)
{
   FileDescriptorWidget* pDescriptorPage = dynamic_cast<FileDescriptorWidget*>(getWidget());
   if (pDescriptorPage == NULL)
   {
      return false;
   }

   DataElement* pElement = dynamic_cast<DataElement*>(pSessionItem);
   if (pElement != NULL)
   {
      DataDescriptor* pDescriptor = pElement->getDataDescriptor();
      if (pDescriptor != NULL)
      {
         const FileDescriptor* pFileDescriptor = pDescriptor->getFileDescriptor();
         if (pFileDescriptor != NULL)
         {
            pDescriptorPage->setFileDescriptor(pFileDescriptor);
            return true;
         }
      }
   }

   return false;
}
예제 #6
0
/**
 * Finds the shader locations of all uniforms and textures from a given material.
 * The input material descriptor has all the possible textures and uniforms
 * that can be used by this shader. (Any material used with this shader
 * will have the same descriptor.)
 *
 * This function uses the descriptor of the input material to find and save
 * the GL shader locations of each texture and uniform. The locations are
 * saved into vectors - mTextureLocs and mUniformLocs. Each vector has an
 * entry for all of the uniforms/textures in the input material
 * (not just the ones used by this shader). If the shader does not
 * reference a particular uniform or texture, that location will be -1.
 * This function must be called after the GL shader program has
 * been selected as the current program.
 * @param material  can be any Material which uses this shader
 * @see #getUniformLoc
 */
void GLShader::findUniforms(const DataDescriptor& desc, int bindingPoint)
{
    std::vector<int>& uniformLocs = mShaderLocs[bindingPoint];

    if (uniformLocs.size() > 0)
    {
        return;
    }
    uniformLocs.resize(desc.getNumEntries(), -1);
    desc.forEachEntry([&](const DataDescriptor::DataEntry& entry) mutable
    {
        if (entry.NotUsed)
        {
            return;
        }
        int loc = glGetUniformLocation(getProgramId(), entry.Name);
        if (loc >= 0)
        {
            uniformLocs[entry.Index] = loc;
#ifdef DEBUG_SHADER
            LOGV("SHADER: program %d uniform %s loc %d", getProgramId(), entry.Name, loc);
#endif
        }
        else
        {
#ifdef DEBUG_SHADER
            LOGV("SHADER: uniform %s has no location in shader %d", entry.Name, getProgramId());
#endif
        }
    });
    checkGLError("GLShader::findUniforms");
}
예제 #7
0
bool DiHdfImporter::createRasterPager(RasterElement *pRaster) const
{
   VERIFY(pRaster != NULL);
   DataDescriptor *pDescriptor = pRaster->getDataDescriptor();
   VERIFY(pDescriptor != NULL);
   FileDescriptor *pFileDescriptor = pDescriptor->getFileDescriptor();
   VERIFY(pFileDescriptor != NULL);

   std::string filename = pRaster->getFilename();
   Progress *pProgress = getProgress();

   FactoryResource<Filename> pFilename;
   pFilename->setFullPathAndName(filename);

   ExecutableResource pagerPlugIn("DiHdfRasterPager", std::string(), pProgress);
   pagerPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedElementArg(), pRaster);
   pagerPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedFilenameArg(), pFilename.get());

   bool success = pagerPlugIn->execute();

   RasterPager *pPager = dynamic_cast<RasterPager*>(pagerPlugIn->getPlugIn());
   if(!success || pPager == NULL)
   {
      std::string message = "Execution of DiHdfRasterPager failed!";
      if (pProgress != NULL) pProgress->updateProgress(message, 0, ERRORS);
      return false;
   }

   pRaster->setPager(pPager);
   pagerPlugIn->releasePlugIn();

   return true;
}
void Simulation_GUI::StartOrtho()
{
   mpStartOrtho->setEnabled(false);

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

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

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

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

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

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* oMetadata = dMeta->getMetadata();

	// RETRIEVE & UPDATE METADATA INFORMATION //

	bool control = Metadata->ReadFile(image_path);

	Metadata->UpdateMetadata(oMetadata); 

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

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

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

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

}
예제 #9
0
vector<ImportDescriptor*> LayerImporter::getImportDescriptors(const string& filename, bool reportErrors)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      MessageLog* pLog = NULL;
      if (reportErrors == true)
      {
         Service<MessageLogMgr> pLogMgr;
         pLog = pLogMgr->getLog();
      }

      XmlReader xml(pLog);
      XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDoc = xml.parse(filename, "metadata");
      DOMElement* pRootElement = NULL;
      if (pDoc != NULL)
      {
         pRootElement = pDoc->getDocumentElement();
      }
      if (pRootElement != NULL)
      {
         for (DOMNode* pChild = pRootElement->getFirstChild();
            pChild != NULL;
            pChild = pChild->getNextSibling())
         {
            if (pChild->getNodeType() == DOMNode::ELEMENT_NODE)
            {
               DOMElement* pChildElement = static_cast<DOMElement*>(pChild);
               string cNodeName = A(pChildElement->getNodeName());

               ImportDescriptor* pImportDescriptor = ModelImporter::populateImportDescriptor(pChildElement, filename);
               if (pImportDescriptor != NULL)
               {
                  DataDescriptor* pDataDescriptor = pImportDescriptor->getDataDescriptor();
                  if (NULL != pDataDescriptor)
                  {
                     DynamicObject* pMetadataZ = pDataDescriptor->getMetadata();
                     VERIFYRV(pMetadataZ, descriptors);
                     if (!pMetadataZ->getAttributeByPath("Layer/Import Options/Use Pixel Coordinates").isValid())
                     {
                        pMetadataZ->setAttributeByPath("Layer/Import Options/Use Pixel Coordinates", false);
                     }
                  }
                  descriptors.push_back(pImportDescriptor);
               }
            }
         }
      }
   }

   return descriptors;
}
vector<ImportDescriptor*> SignatureSetImporter::createImportDescriptors(DOMTreeWalker* pTree, vector<string> &datasetPath)
{
   vector<ImportDescriptor*> descriptors;
   FactoryResource<DynamicObject> pMetadata;
   VERIFYRV(pMetadata.get() != NULL, descriptors);

   string datasetName = StringUtilities::toDisplayString(mDatasetNumber++);
   for (DOMNode* pChld = pTree->firstChild(); pChld != NULL; pChld = pTree->nextSibling())
   {
      if (XMLString::equals(pChld->getNodeName(), X("metadata")))
      {
         DOMElement* pElmnt = static_cast<DOMElement*>(pChld);
         string name = A(pElmnt->getAttribute(X("name")));
         string val = A(pElmnt->getAttribute(X("value")));
         pMetadata->setAttribute(name, val);
         if (name == "Name")
         {
            datasetName = val;
         }
      }
      else if (XMLString::equals(pChld->getNodeName(), X("signature_set")))
      {
         datasetPath.push_back(datasetName);
         vector<ImportDescriptor*> sub = createImportDescriptors(pTree, datasetPath);
         datasetPath.pop_back();
         descriptors.insert(descriptors.end(), sub.begin(), sub.end());
         pTree->parentNode();
      }
   }
   ImportDescriptorResource pImportDescriptor(datasetName, "SignatureSet", datasetPath);
   VERIFYRV(pImportDescriptor.get() != NULL, descriptors);
   DataDescriptor* pDataDescriptor = pImportDescriptor->getDataDescriptor();
   VERIFYRV(pDataDescriptor != NULL, descriptors);
   FactoryResource<SignatureFileDescriptor> pFileDescriptor;
   VERIFYRV(pFileDescriptor.get() != NULL, descriptors);
   pFileDescriptor->setFilename(mFilename);
   datasetPath.push_back(datasetName);
   string loc = "/" + StringUtilities::join(datasetPath, "/");
   datasetPath.pop_back();
   pFileDescriptor->setDatasetLocation(loc);
   pDataDescriptor->setFileDescriptor(pFileDescriptor.get());
   pDataDescriptor->setMetadata(pMetadata.get());
   descriptors.push_back(pImportDescriptor.release());
   return descriptors;
}
bool PropertiesDataDescriptor::applyChanges()
{
   if (mpDescriptor.get() == NULL)
   {
      return false;
   }

   DataElement* pElement = dynamic_cast<DataElement*>(getSessionItem());
   if (pElement != NULL)
   {
      DataDescriptor* pDescriptor = pElement->getDataDescriptor();
      if (pDescriptor != NULL)
      {
         return pDescriptor->clone(mpDescriptor.get());
      }
   }

   return false;
}
예제 #12
0
DataDescriptor* DataDescriptorImp::copy(const string& name, const vector<string>& parent) const
{
   ModelServicesImp* pModel = ModelServicesImp::instance();
   if (pModel == NULL)
   {
      return NULL;
   }

   DataDescriptor* pDescriptor = pModel->createDataDescriptor(name, mType, parent);
   if (pDescriptor != NULL)
   {
      pDescriptor->setClassification(dynamic_cast<const Classification*>(&mClassification));
      pDescriptor->setMetadata(dynamic_cast<const DynamicObject*>(&mMetadata));
      pDescriptor->setProcessingLocation(mProcessingLocation);
      pDescriptor->setFileDescriptor(dynamic_cast<FileDescriptor*>(mpFileDescriptor));
   }

   return pDescriptor;
}
예제 #13
0
bool Nitf::NitfImporterShell::createRasterPager(RasterElement *pRaster) const
{
   VERIFY(pRaster != NULL);

   DataDescriptor* pDd = pRaster->getDataDescriptor();
   VERIFY(pDd != NULL);
   FileDescriptor* pFd = pDd->getFileDescriptor();
   VERIFY(pFd != NULL);

   const string& datasetLocation = pFd->getDatasetLocation();
   if (datasetLocation.empty() == true)
   {
      return false;
   }

   stringstream imageNameStream(datasetLocation.substr(1));
   int imageSegment;
   imageNameStream >> imageSegment;

   FactoryResource<Filename> pFn;
   pFn->setFullPathAndName(pFd->getFilename());

   ExecutableResource pPlugIn("NitfPager");
   pPlugIn->getInArgList().setPlugInArgValue("Segment Number", &imageSegment);
   pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedElementArg(), pRaster);
   pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedFilenameArg(), pFn.get());

   if (pPlugIn->execute() == true)
   {
      RasterPager* pPager = dynamic_cast<RasterPager*>(pPlugIn->getPlugIn());
      if (pPager != NULL)
      {
         pRaster->setPager(pPager);
         pPlugIn->releasePlugIn();
         return true;
      }
   }

   return false;
}
예제 #14
0
vector<ImportDescriptor*> ShapeFileImporter::getImportDescriptors(const string& filename)
{
   vector<ImportDescriptor*> descriptors;

   if (getFileAffinity(filename) != Importer::CAN_NOT_LOAD)
   {
      Service<ModelServices> pModel;

      ImportDescriptor* pImportDescriptor = pModel->createImportDescriptor(filename, "AnnotationElement", NULL);
      VERIFYRV(pImportDescriptor != NULL, descriptors);

      DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
      VERIFYRV(pDescriptor != NULL, descriptors);

      FactoryResource<FileDescriptor> pFileDescriptor;
      pFileDescriptor->setFilename(filename);
      pDescriptor->setFileDescriptor(pFileDescriptor.get());

      descriptors.push_back(pImportDescriptor);
   }

   return descriptors;
}
예제 #15
0
std::string GLShader::makeLayout(const DataDescriptor& desc, const char* blockName, bool useGPUBuffer)
{
    std::ostringstream stream;
    if (useGPUBuffer)
    {
        stream << "\nlayout (std140) uniform " << blockName << std::endl << "{" << std::endl;
        desc.forEachEntry([&stream](const DataDescriptor::DataEntry& entry) mutable
        {
            int nelems = entry.Count;
            stream << "   " << entry.Type << " " << entry.Name;
            if (nelems > 1)
            {
                stream << "[" << nelems << "]";
            }
            stream << ";" << std::endl;
        });
        stream << "};" << std::endl;
    }
    else
    {
        desc.forEachEntry([&stream](const DataDescriptor::DataEntry& entry) mutable
        {
            if (entry.IsSet)
            {
                int nelems = entry.Count;
                stream << "uniform " << entry.Type << " " << entry.Name;
                if (nelems > 1)
                {
                    stream << "[" << nelems << "]";
                }
                stream << ";" << std::endl;
            }
        });
    }
    return stream.str();
}
예제 #16
0
int test_ht_8UC3_to_y(const uint8_t *src, int w, int h, uint8_t KA, uint8_t KB, uint8_t KC, uint16_t KR)
{
   int lRetVal = 0;
   apexcv::OPT::ColorConverter rgb;

   DataDescriptor srcImg;
		srcImg.InitManual(w/*/4*/, h, (void *)src, (void *)OAL_MemoryReturnAddress((void *)src, ACCESS_PHY), DATATYPE_08U, 4, 1);
   DataDescriptor dstImg(w/*/4*/, h, DATATYPE_16S);
   DataDescriptor dstRefImg(w/*/4*/, h, DATATYPE_16S);


   if(srcImg.IsOK() && dstImg.IsOK() && dstRefImg.IsOK()) {
      //run implementation
      lRetVal |= rgb.convert(srcImg, dstImg, OPT::ColorConverter::HT_8UC3_TO_Y, KA, KB, KC, KR);

      //obtain dst data pointers
      int16_t* pDst    = (int16_t*) dstImg.GetDataPtr();
      int16_t* pDstRef = (int16_t*) dstRefImg.GetDataPtr();

      //run reference
      csc_8UC3_to_y_ref((int16_t*)pDstRef, w, (uint8_t*)src, w*4, w, h, KA, KB, KC, KR);

      if (dstImg == dstRefImg)
			 lRetVal |= 0;
		 else
			 lRetVal |= 1;
   } else {
      lRetVal |= 1;
   }

   //free buffers
   dstImg.SetFreeOnExit(true);
   dstRefImg.SetFreeOnExit(true);

   return lRetVal;
}
예제 #17
0
int test_integral_image(const unsigned char *src, int w, int h) 
{
   int lRetVal = 0;
   apexcv::IntegralImage i;
   
   DataDescriptor srcImg;
	     srcImg.InitManual(w, h, (void *)src, (void *)OAL_MemoryReturnAddress((void *)src, ACCESS_PHY), DATATYPE_08U);
   DataDescriptor dstImg(w, h, DATATYPE_32U);
   DataDescriptor dstRefImg(w, h, DATATYPE_32U);
   
   if(srcImg.IsOK() &&dstImg.IsOK() && dstRefImg.IsOK()) {
	   
      //run implementation
      lRetVal |= i.exec(srcImg, dstImg);
  
      //obtain dst data pointers
      unsigned int* pDst    = (unsigned int*) dstImg.GetDataPtr();
      unsigned int* pDstRef = (unsigned int*) dstRefImg.GetDataPtr();
      
      //run reference
      integral_image_ref(pDstRef, src, w, w, h);

      if (dstImg == dstRefImg)
			 lRetVal |= 0;
		 else
			 lRetVal |= 1;
   } else {
      lRetVal |= 1;
   }
   
   //free buffers
   dstImg.SetFreeOnExit(true);
   dstRefImg.SetFreeOnExit(true);
   
   return lRetVal;
}
bool SignatureImporter::execute(PlugInArgList* pInArgList, PlugInArgList* OutArgList)
{
   VERIFY(pInArgList != NULL);
   ProgressTracker progress(pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()),
      "Loading spectral signature", "spectral", "5A9F8379-7D7D-4575-B78B-305AE0DFC66D");

   Signature* pSignature = pInArgList->getPlugInArgValue<Signature>(Importer::ImportElementArg());
   VERIFY(pSignature != NULL);
   DataDescriptor* pDataDescriptor = pSignature->getDataDescriptor();
   VERIFY(pDataDescriptor != NULL);
   FileDescriptor* pFileDescriptor = pDataDescriptor->getFileDescriptor();
   VERIFY(pFileDescriptor != NULL);

   progress.getCurrentStep()->addProperty("filename", pFileDescriptor->getFilename().getFullPathAndName());
   
   DynamicObject* pMetadata = pSignature->getMetadata();
   VERIFY(pMetadata != NULL);
   string warningMsg;

   LargeFileResource pSigFile;
   VERIFY(pSigFile.open(pFileDescriptor->getFilename().getFullPathAndName(), O_RDONLY | O_BINARY, S_IREAD));

   const Units* pUnits = pSignature->getUnits("Reflectance");
   VERIFY(pUnits != NULL);

   // Read the signature data
   vector<double> wavelengthData, reflectanceData;

   int64_t fileSize = pSigFile.fileLength();
   bool readError = false;
   size_t largeValueCount(0);
   for (string line = pSigFile.readLine(&readError); readError == false; line = pSigFile.readLine(&readError))
   {
      if (isAborted())
      {
         progress.report("Importer aborted", 0, ABORT, true);
         return false;
      }

      int64_t fileLocation = pSigFile.tell();
      progress.report("Loading signature data", static_cast<int>(fileLocation * 100.0 / fileSize), NORMAL);

      trim(line);
      if (line.empty())
      {
         continue;
      }
      if (line.find('=') == string::npos)
      {
         double wavelength = 0.0, reflectance = 0.0;
         vector<string> dataEntry;
         split(dataEntry, line, is_space());
         bool error = true;
         if (dataEntry.size() >= 1)
         {
            wavelength = StringUtilities::fromXmlString<double>(dataEntry[0], &error);
            if (wavelength > 50.0)
            {
               // Assume wavelength values are in nanometers and convert to microns
               wavelength = Wavelengths::convertValue(wavelength, NANOMETERS, MICRONS);
            }
         }
         if (!error && dataEntry.size() == 2)
         {
            reflectance = StringUtilities::fromXmlString<double>(dataEntry[1], &error);

            // Since the signature file may not have contained info on units and unitScale (defaults to values of
            // "REFLECTANCE" and "1.0"), we need to check that the reflectance value is properly scaled.
            // In theory, a valid reflectance value should be between 0 and 1, but real data may extend beyond these
            // limits due to errors that occurred in collection, calibration, conversion, etc. We're assuming that a
            // value greater than 2.0 indicates that the value was scaled by a factor other than 1.0 - a common data
            // collection practice is to store a data value as an integer value equal to the actual value multiplied
            // by a scaling factor. This saves storage space while preserving precision. 10000 is a very common
            // scaling factor and the one we will assume was used. Right now we'll just count the number of large values.
            // If more than half the values are large, we will assume they were scaled and divide all the values by 10000.
            if (pUnits->getUnitType() == REFLECTANCE && pUnits->getScaleFromStandard() == 1.0
               && fabs(reflectance) > 2.0)
            {
               ++largeValueCount;
            }
         }
         if (error)
         {
            progress.report("Error parsing signature data", 0, ERRORS, true);
         }

         wavelengthData.push_back(wavelength);
         reflectanceData.push_back(reflectance);
      }
   }

   if ((readError == true) && (pSigFile.eof() != 1))
   {
      progress.report("Unable to read signature file", 0, ERRORS, true);
      return false;
   }

   // check for need to scale the values, i.e., at least half the values are large
   if (reflectanceData.empty() == false && largeValueCount > 0 && largeValueCount >= (reflectanceData.size() / 2))
   {
      warningMsg += (warningMsg.empty() ? "" : "\n");
      warningMsg += "Values appear to have been scaled - values have been divided by 10000";
      for (vector<double>::iterator it = reflectanceData.begin(); it != reflectanceData.end(); ++it)
      {
         *it *= 0.0001;  // divide by 10000
      }
   }
   pSignature->setData("Wavelength", wavelengthData);
   pSignature->setData("Reflectance", reflectanceData);
   if (warningMsg.empty())
   {
      progress.report("Spectral signature loaded", 100, NORMAL);
   }
   else
   {
      progress.report(warningMsg, 100, WARNING);
      progress.getCurrentStep()->addMessage(warningMsg, "spectral", "770EB61A-71CD-4f83-8C7B-E0FEF3D7EB8D");
   }
   progress.upALevel();
   return true;
}
예제 #19
0
bool GeoTIFFExporter::applyWorldFile(TIFF *pOut)
{
    FILE* pTfw = NULL;
    int size = 0;
    double pPixsize[3];
    double xoff;
    double yoff;
    double pTiepoint[6];
    double x_rot;
    double y_rot;
    double pAdfMatrix[16];

    DataDescriptor* pDescriptor = mpRaster->getDataDescriptor();
    if (pDescriptor == NULL)
    {
        return false;
    }

    FileDescriptor* pFileDescriptor = pDescriptor->getFileDescriptor();
    if (pFileDescriptor == NULL)
    {
        return false;
    }

    const Filename& filename = pFileDescriptor->getFilename();
    string path = filename.getPath();
    string title = filename.getTitle();

    std::string worldFilename = path + SLASH + title + ".tfw";

    pTfw = fopen(worldFilename.c_str(), "rt");
    if (pTfw == NULL)
    {
        return false;
    }

    fscanf(pTfw, "%lf", pPixsize + 0);
    fscanf(pTfw, "%lf", &y_rot);
    fscanf(pTfw, "%lf", &x_rot);
    fscanf(pTfw, "%lf", pPixsize + 1);
    fscanf(pTfw, "%lf", &xoff);
    fscanf(pTfw, "%lf", &yoff);
    fclose(pTfw);

    // Write out pixel scale, and tiepoint information.
    if ((x_rot == 0.0) && (y_rot == 0.0))
    {
        pPixsize[1] = abs(pPixsize[1]);
        pPixsize[2] = 0.0;
        TIFFSetField(pOut, GTIFF_PIXELSCALE, 3, pPixsize);
        pTiepoint[0] = 0.5;
        pTiepoint[1] = 0.5;
        pTiepoint[2] = 0.0;
        pTiepoint[3] = xoff;
        pTiepoint[4] = yoff;
        pTiepoint[5] = 0.0;
        TIFFSetField(pOut, GTIFF_TIEPOINTS, 6, pTiepoint);
    }
    else
    {
        memset(pAdfMatrix, 0, sizeof(double) * 16);
        pAdfMatrix[0] = pPixsize[0];
        pAdfMatrix[1] = x_rot;
        pAdfMatrix[3] = xoff - (pPixsize[0] + x_rot) * 0.5;
        pAdfMatrix[4] = y_rot;
        pAdfMatrix[5] = pPixsize[1];
        pAdfMatrix[7] = yoff - (pPixsize[1] + y_rot) * 0.5;
        pAdfMatrix[15] = 1.0;

        TIFFSetField(pOut, TIFFTAG_GEOTRANSMATRIX, 16, pAdfMatrix);
    }

    return true;
}
예제 #20
0
void ImportOptionsDlg::setCurrentDataset(ImportDescriptor* pImportDescriptor)
{
   if (pImportDescriptor == NULL)
   {
      return;
   }

   if (pImportDescriptor == mpCurrentDataset)
   {
      return;
   }

   // Apply changes to the current data set if necessary
   bool bSuccess = true;
   if ((mpCurrentDataset != NULL) && (mEditDataDescriptorModified == true))
   {
      if (mPromptForChanges == true)
      {
         int iReturn = QMessageBox::question(this, APP_NAME, "Apply changes to data?",
            QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel);
         if ((iReturn == QMessageBox::Yes) || (iReturn == QMessageBox::YesToAll))
         {
            bSuccess = applyChanges();
            if (iReturn == QMessageBox::YesToAll)
            {
               mPromptForChanges = false;
            }
         }
         else if (iReturn == QMessageBox::No)
         {
            // Update the validation icon for the original data descriptor
            validateDataset(mpCurrentDataset->getDataDescriptor());
         }
         else if (iReturn == QMessageBox::Cancel)
         {
            bSuccess = false;
         }
      }
      else
      {
         bSuccess = applyChanges();
      }
   }

   if (bSuccess == false)
   {
      // Select the tree widget item for the previously selected data set
      selectCurrentDatasetItem();
      return;
   }

   mpCurrentDataset = pImportDescriptor;

   // Destroy the existing edit data descriptor if necessary
   Service<ModelServices> pModel;
   if (mpEditDescriptor != NULL)
   {
      Classification* pClassification = mpEditDescriptor->getClassification();
      if (pClassification != NULL)
      {
         VERIFYNR(pClassification->detach(SIGNAL_NAME(Subject, Modified),
            Slot(this, &ImportOptionsDlg::editClassificationModified)));
      }

      RasterDataDescriptor* pRasterDescriptor = dynamic_cast<RasterDataDescriptor*>(mpEditDescriptor);
      if (pRasterDescriptor != NULL)
      {
         VERIFYNR(pRasterDescriptor->detach(SIGNAL_NAME(RasterDataDescriptor, RowsChanged),
            Slot(this, &ImportOptionsDlg::editDataDescriptorRowsModified)));
         VERIFYNR(pRasterDescriptor->detach(SIGNAL_NAME(RasterDataDescriptor, ColumnsChanged),
            Slot(this, &ImportOptionsDlg::editDataDescriptorColumnsModified)));
         VERIFYNR(pRasterDescriptor->detach(SIGNAL_NAME(RasterDataDescriptor, BandsChanged),
            Slot(this, &ImportOptionsDlg::editDataDescriptorBandsModified)));
      }

      RasterFileDescriptor* pRasterFileDescriptor =
         dynamic_cast<RasterFileDescriptor*>(mpEditDescriptor->getFileDescriptor());
      if (pRasterFileDescriptor != NULL)
      {
         VERIFYNR(pRasterFileDescriptor->detach(SIGNAL_NAME(RasterFileDescriptor, RowsChanged),
            Slot(this, &ImportOptionsDlg::editFileDescriptorRowsModified)));
         VERIFYNR(pRasterFileDescriptor->detach(SIGNAL_NAME(RasterFileDescriptor, ColumnsChanged),
            Slot(this, &ImportOptionsDlg::editFileDescriptorColumnsModified)));
         VERIFYNR(pRasterFileDescriptor->detach(SIGNAL_NAME(RasterFileDescriptor, BandsChanged),
            Slot(this, &ImportOptionsDlg::editFileDescriptorBandsModified)));
      }

      VERIFYNR(mpEditDescriptor->detach(SIGNAL_NAME(Subject, Modified),
         Slot(this, &ImportOptionsDlg::editDataDescriptorModified)));
      pModel->destroyDataDescriptor(mpEditDescriptor);
      mpEditDescriptor = NULL;
      mEditDataDescriptorModified = false;
   }

   // Create a new data descriptor to validate the user inputs
   DataDescriptor* pDescriptor = mpCurrentDataset->getDataDescriptor();
   if (pDescriptor != NULL)
   {
      mpEditDescriptor = pDescriptor->copy();
   }

   VERIFYNRV(mpEditDescriptor != NULL);
   VERIFYNR(mpEditDescriptor->attach(SIGNAL_NAME(Subject, Modified),
      Slot(this, &ImportOptionsDlg::editDataDescriptorModified)));

   RasterDataDescriptor* pRasterDescriptor = dynamic_cast<RasterDataDescriptor*>(mpEditDescriptor);
   FileDescriptor* pFileDescriptor = mpEditDescriptor->getFileDescriptor();
   RasterFileDescriptor* pRasterFileDescriptor = dynamic_cast<RasterFileDescriptor*>(pFileDescriptor);

   if (pRasterDescriptor != NULL)
   {
      VERIFYNR(pRasterDescriptor->attach(SIGNAL_NAME(RasterDataDescriptor, RowsChanged),
         Slot(this, &ImportOptionsDlg::editDataDescriptorRowsModified)));
      VERIFYNR(pRasterDescriptor->attach(SIGNAL_NAME(RasterDataDescriptor, ColumnsChanged),
         Slot(this, &ImportOptionsDlg::editDataDescriptorColumnsModified)));
      VERIFYNR(pRasterDescriptor->attach(SIGNAL_NAME(RasterDataDescriptor, BandsChanged),
         Slot(this, &ImportOptionsDlg::editDataDescriptorBandsModified)));
   }

   if (pRasterFileDescriptor != NULL)
   {
      VERIFYNR(pRasterFileDescriptor->attach(SIGNAL_NAME(RasterFileDescriptor, RowsChanged),
         Slot(this, &ImportOptionsDlg::editFileDescriptorRowsModified)));
      VERIFYNR(pRasterFileDescriptor->attach(SIGNAL_NAME(RasterFileDescriptor, ColumnsChanged),
         Slot(this, &ImportOptionsDlg::editFileDescriptorColumnsModified)));
      VERIFYNR(pRasterFileDescriptor->attach(SIGNAL_NAME(RasterFileDescriptor, BandsChanged),
         Slot(this, &ImportOptionsDlg::editFileDescriptorBandsModified)));
   }

   // Select the tree widget item for the current data set
   selectCurrentDatasetItem();

   // Disconnect pages
   updateConnections(false);

   // Subset page
   if (pRasterFileDescriptor != NULL)
   {
      // Show the tab if necessary
      if (mpTabWidget->indexOf(mpSubsetPage) == -1)
      {
         mpTabWidget->insertTab(2, mpSubsetPage, "Subset");
      }

      // Rows
      const vector<DimensionDescriptor>& rows = pRasterFileDescriptor->getRows();
      const vector<DimensionDescriptor>& loadedRows = pRasterDescriptor->getRows();
      mpSubsetPage->setRows(rows, loadedRows);

      // Columns
      const vector<DimensionDescriptor>& columns = pRasterFileDescriptor->getColumns();
      const vector<DimensionDescriptor>& loadedColumns = pRasterDescriptor->getColumns();
      mpSubsetPage->setColumns(columns, loadedColumns);

      // Bands
      const vector<DimensionDescriptor>& bands = pRasterFileDescriptor->getBands();
      const vector<DimensionDescriptor>& selectedBands = pRasterDescriptor->getBands();
      setSubsetBands(bands, selectedBands);

      // Initial bad band file directory
      if (pFileDescriptor != NULL)
      {
         QString strDirectory;

         string filename = pFileDescriptor->getFilename();
         if (filename.empty() == false)
         {
            QFileInfo fileInfo(QString::fromStdString(filename));
            strDirectory = fileInfo.absolutePath();
         }

         mpSubsetPage->setBadBandFileDirectory(strDirectory);
      }
   }
   else
   {
      // Remove the subset page, since the file descriptor either isn't
      // present or isn't a RasterFileDescriptor, just a FileDescriptor
      int index = mpTabWidget->indexOf(mpSubsetPage);
      if (index != -1)
      {
         mpTabWidget->removeTab(index);
      }
   }

   // Data descriptor page - enable editing for all fields
   mpDataPage->setDataDescriptor(mpEditDescriptor, true);

   // File descriptor page
   bool editFilePage = false;
   if (pRasterFileDescriptor != NULL)
   {
      unsigned int numRows = pRasterFileDescriptor->getRowCount();
      unsigned int numColumns = pRasterFileDescriptor->getColumnCount();
      unsigned int bitsPerElement = pRasterFileDescriptor->getBitsPerElement();
      unsigned int numBands = pRasterFileDescriptor->getBandCount();
      if ((numRows == 0) || (numColumns == 0) || (numBands == 0) || (bitsPerElement == 0))
      {
         editFilePage = true;
      }
   }

   mpFilePage->setFileDescriptor(pFileDescriptor, editFilePage);

   int iIndex = mpTabWidget->indexOf(mpFilePage);
   if (iIndex != -1)
   {
      if (pFileDescriptor == NULL)
      {
         mpTabWidget->removeTab(iIndex);
      }
   }
   else
   {
      if (pFileDescriptor != NULL)
      {
         mpTabWidget->insertTab(1, mpFilePage, "File");
      }
   }

   // Classification page
   updateClassificationLabel();

   Classification* pClassification = mpEditDescriptor->getClassification();
   if (pClassification != NULL)
   {
      VERIFYNR(pClassification->attach(SIGNAL_NAME(Subject, Modified),
         Slot(this, &ImportOptionsDlg::editClassificationModified)));
      mpClassificationPage->setClassification(pClassification);
   }

   // Metadata page
   mpMetadataPage->setMetadata(mpEditDescriptor->getMetadata());

   // Wavelengths page
   bool bWavelengthsPageActive = false;
   if (mpTabWidget->currentWidget() == mpWavelengthsPage)
   {
      bWavelengthsPageActive = true;
   }

   int index = mpTabWidget->indexOf(mpWavelengthsPage);
   if (index != -1)
   {
      mpTabWidget->removeTab(index);
   }

   if (pRasterFileDescriptor != NULL)
   {
      // Populate the wavelengths with the file descriptor bands since the metadata wavelengths
      // apply to all bands in the file
      mpWavelengthsPage->setWavelengths(pRasterFileDescriptor->getBands(), mpEditDescriptor->getMetadata());

      if (pRasterDescriptor != NULL)
      {
         mpWavelengthsPage->highlightActiveBands(pRasterDescriptor->getBands());
      }

      mpTabWidget->addTab(mpWavelengthsPage, "Wavelengths");

      if (bWavelengthsPageActive == true)
      {
         mpTabWidget->setCurrentWidget(mpWavelengthsPage);
      }
   }

   // Importer page
   bool bImporterPageActive = false;
   if (mpImporterPage != NULL)
   {
      if (mpTabWidget->currentWidget() == mpImporterPage)
      {
         bImporterPageActive = true;
      }
   }

   removeImporterPage();

   if (mpImporter != NULL)
   {
      mpImporterPage = mpImporter->getImportOptionsWidget(mpEditDescriptor);
      if (mpImporterPage != NULL)
      {
         QLayout* pLayout = mpImporterPage->layout();
         if (pLayout != NULL)
         {
            if (pLayout->margin() <= 0)
            {
               pLayout->setMargin(10);
            }
         }

         QString strCaption = mpImporterPage->windowTitle();
         if (strCaption.isEmpty() == true)
         {
            strCaption = "Importer";
         }

         mpTabWidget->addTab(mpImporterPage, strCaption);

         if (bImporterPageActive == true)
         {
            mpTabWidget->setCurrentWidget(mpImporterPage);
         }
      }

      // Set the valid processing locations on the data page.  This must be done after getting the import options
      // widget from the importer so that the auto importer will correctly query the importer that is used.
      // This can be changed if the importer design (and auto importer) is modified to support valid processing
      // locations for a specific data set.
      vector<ProcessingLocation> locations;
      if (mpImporter->isProcessingLocationSupported(IN_MEMORY) == true)
      {
         locations.push_back(IN_MEMORY);
      }

      if (mpImporter->isProcessingLocationSupported(ON_DISK) == true)
      {
         locations.push_back(ON_DISK);
      }

      if (mpImporter->isProcessingLocationSupported(ON_DISK_READ_ONLY) == true)
      {
         locations.push_back(ON_DISK_READ_ONLY);
      }

      mpDataPage->setValidProcessingLocations(locations);
   }

   // Validate the current data descriptor
   validateEditDataset();

   // Reconnect the pages
   updateConnections(true);

   // Notify connected objects
   emit currentDatasetChanged(mpCurrentDataset);
}
예제 #21
0
bool LayerImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Layer* pLayer = NULL;
   Progress* pProgress = NULL;
   DataElement* pElement = NULL;
   SpatialDataView* pView = NULL;
   StepResource pStep("Import layer", "app", "DF24688A-6B34-4244-98FF-5FFE2063AC05");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "C0A532DE-0E19-44D3-837C-16ABD267B2C1");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));

      pElement = pInArgList->getPlugInArgValue<DataElement>(Importer::ImportElementArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No data element", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No data element");
         return false;
      }
      pMsg->addProperty("Element name", pElement->getName());
      pView = pInArgList->getPlugInArgValue<SpatialDataView>(Executable::ViewArg());
      if (pView != NULL)
      {
         pMsg->addProperty("View name", pView->getName());
      }
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress((string("Read and parse file ") + pElement->getFilename()),
         20, NORMAL);
   }

   // parse the xml
   XmlReader xml(Service<MessageLogMgr>()->getLog());

   XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDomDocument = xml.parse(pElement->getFilename());
   if (pDomDocument == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to parse the file", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to parse the file");
      return false;
   }

   DOMElement* pRootElement = pDomDocument->getDocumentElement();
   VERIFY(pRootElement != NULL);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Create the layer", 40, NORMAL);
   }

   string name(A(pRootElement->getAttribute(X("name"))));
   string type(A(pRootElement->getAttribute(X("type"))));
   unsigned int formatVersion = atoi(A(pRootElement->getAttribute(X("version"))));

   { // scope the MessageResource
      MessageResource pMsg("Layer information", "app", "AA358F7A-107E-456E-8D11-36DDBE5B1645");
      pMsg->addProperty("name", name);
      pMsg->addProperty("type", type);
      pMsg->addProperty("format version", formatVersion);
   }


   // If user requested pixel coordinates be used.
   bool usePixelCoords = false;
   DataDescriptor* pDesc = pElement->getDataDescriptor();
   VERIFY( pDesc );
   pDesc->getMetadata()->getAttributeByPath( "Layer/Import Options/Use Pixel Coordinates" ).getValue( usePixelCoords );
   if (usePixelCoords)
   {
      // Remove geoVertices and geoBox elements.
      removeGeoNodes(pRootElement);
   }

   if (pView == NULL)
   {
      //no view provided, so find current view
      SpatialDataWindow* pWindow = dynamic_cast<SpatialDataWindow*>(mpDesktop->getCurrentWorkspaceWindow());
      if (pWindow != NULL)
      {
         pView = pWindow->getSpatialDataView();
      }
   }

   if (pView == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Could not access the view to create the layer.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "Could not access the view to create the layer.");
      return false;
   }

   bool error = false;
   LayerType layerType = StringUtilities::fromXmlString<LayerType>(type, &error);
   if (error == true)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("The layer type is invalid.", 100, ERRORS);
      }

      pStep->finalize(Message::Failure, "The layer type is invalid.");
      return false;
   }

   LayerList* pLayerList = pView->getLayerList();
   if (pLayerList != NULL)
   {
      RasterElement* pNewParentElement = pLayerList->getPrimaryRasterElement();
      if (pNewParentElement != NULL)
      {
         Service<ModelServices> pModel;
         if (pModel->setElementParent(pElement, pNewParentElement) == false)
         {
            pProgress->updateProgress("The layer already exists.", 100, ERRORS);
            pStep->finalize(Message::Failure, "The layer already exists.");
            return false;
         }
      }
   }

   UndoGroup group(pView, "Import " + StringUtilities::toDisplayString(layerType) + " Layer");

   pLayer = pView->createLayer(layerType, pElement);
   if (pLayer == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Unable to create the layer", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Unable to create the layer");
      return false;
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Build the layer", 60, NORMAL);
   }

   // deserialize the layer
   try
   {
      if (pLayer->fromXml(pRootElement, formatVersion) == false)
      {
         pProgress->updateProgress("Problem with layer file.", 100, ERRORS);
         pStep->finalize(Message::Failure, "Problem with layer file.");
         return false;
      }
   }
   catch (XmlReader::DomParseException&)
   {
      return false;
   }

   pStep->finalize(Message::Success);
   if (pProgress != NULL)
   {
      pProgress->updateProgress("Finished loading the layer", 100, NORMAL);
   }

   // Add the layer to the view
   pView->addLayer(pLayer);
   pView->setActiveLayer(pLayer);
   pView->setMouseMode("LayerMode");

   if (pOutArgList != NULL)
   {
      // set the output arguments
      pOutArgList->setPlugInArgValue("Layer", pLayer);
   }

   return true;
}
bool SignatureSetImporter::execute(PlugInArgList* pInArgList, PlugInArgList* OutArgList)
{
   VERIFY(pInArgList != NULL);
   Progress* pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
   ProgressTracker progress(pProgress, "Loading spectral signature library", "spectral", "7B21EE8A-D2E1-4325-BB9F-F4E521BFD5ED");

   SignatureSet* pSignatureSet = pInArgList->getPlugInArgValue<SignatureSet>(Importer::ImportElementArg());
   VERIFY(pSignatureSet != NULL);
   DataDescriptor* pDataDescriptor = pSignatureSet->getDataDescriptor();
   VERIFY(pDataDescriptor != NULL);
   FileDescriptor* pFileDescriptor = pDataDescriptor->getFileDescriptor();
   VERIFY(pFileDescriptor != NULL);
   const string& filename = pFileDescriptor->getFilename().getFullPathAndName();

   progress.getCurrentStep()->addProperty("signature set", pSignatureSet->getName());
   progress.getCurrentStep()->addProperty("dataset location", pFileDescriptor->getDatasetLocation());

   // locate the spot in the tree for this dataset
   try
   {
      string expr;
      vector<string> parts = StringUtilities::split(pFileDescriptor->getDatasetLocation(), '/');
      for (vector<string>::iterator part = parts.begin(); part != parts.end(); ++part)
      {
         if (!part->empty())
         {
            expr += "/signature_set[metadata/@name='Name' and metadata/@value='" + *part + "']";
         }
      }
      expr += "/signature";
      loadDoc(filename);
      DOMXPathResult* pResult = mXml[filename]->query(expr, DOMXPathResult::SNAPSHOT_RESULT_TYPE);
      VERIFY(pResult != NULL);
      int nodeTotal = pResult->getSnapshotLength();
      for (int nodeNum = 0; nodeNum < nodeTotal; ++nodeNum)
      {
         if (isAborted())
         {
            progress.report("Aborted file " + pFileDescriptor->getFilename().getFullPathAndName(), 0, WARNING, true);
            progress.report("User aborted the operation.", 0, ABORT, true);
            return false;
         }
         int percent = static_cast<int>(100.0 * nodeNum / nodeTotal);
         progress.report("Importing signature library", percent, NORMAL);
         if (!pResult->snapshotItem(nodeNum) || !pResult->isNode())
         {
            continue;
         }
         const DOMElement* pElmnt = static_cast<const DOMElement*>(pResult->getNodeValue());
         string filename = A(pElmnt->getAttribute(X("filename")));
         if (filename.empty() == false)
         {
            string path = pFileDescriptor->getFilename().getPath();

            QString tempFilename = QString::fromStdString(filename);
            if (tempFilename.startsWith("./") == true)
            {
               tempFilename.replace(0, 1, QString::fromStdString(path));
               filename = tempFilename.toStdString();
            }
            else
            {
               QFileInfo fileInfo(tempFilename);
               if (fileInfo.isRelative() == true)
               {
                  filename = path + SLASH + filename;
               }
            }
         }

         // don't pass progress to importer - the individual signature imports are rapid and passing progress will
         // cause isAborted() to not function properly.
         ImporterResource importer("Auto Importer", filename, NULL);
         if (importer->getPlugIn() == NULL)
         {
            progress.report("The \"Auto Importer\" is not available and is required to import signature sets.", 0, ERRORS, true);
            return false;
         }
         if (importer->execute())
         {
            vector<DataElement*> elements = importer->getImportedElements();
            vector<Signature*> sigs(elements.size(), NULL);
            for (vector<DataElement*>::iterator element = elements.begin(); element != elements.end(); ++element)
            {
               Signature* pSig = dynamic_cast<Signature*>(*element);
               if (pSig != NULL)
               {
                  pSignatureSet->insertSignature(pSig);
                  // reparent the signature
                  Service<ModelServices>()->setElementParent(pSig, pSignatureSet);
               }
            }
         }
         else
         {
            progress.report("Unable to import signature " + filename, percent, WARNING, true);
         }
      }
   }
   catch(DOMException &exc)
   {
      progress.report(A(exc.getMessage()), 0, ERRORS, true);
      return false;
   }
   SignatureSet* pParent = dynamic_cast<SignatureSet*>(pSignatureSet->getParent());
   if (pParent != NULL && pParent->getFilename() == pSignatureSet->getFilename())
   {
      pParent->insertSignature(pSignatureSet);
   }

   progress.report("Spectral signature library loaded", 100, NORMAL);
   progress.upALevel();
   return true;
}
예제 #23
0
ImportOptionsDlg::ImportOptionsDlg(Importer* pImporter, const QMap<QString, vector<ImportDescriptor*> >& files,
   QWidget* pParent) :
   QDialog(pParent),
   mpImporter(pImporter),
   mpCurrentDataset(NULL),
   mpEditDescriptor(NULL),
   mEditDataDescriptorModified(false),
   mPromptForChanges(true),
   mAllowDeselectedFiles(true),
   mpDatasetTree(NULL),
   mpClassificationLabel(NULL),
   mpTabWidget(NULL),
   mpDataPage(NULL),
   mpFilePage(NULL),
   mpClassificationPage(NULL),
   mpSubsetPage(NULL),
   mpMetadataPage(NULL),
   mpWavelengthsPage(NULL),
   mpImporterPage(NULL),
   mpValidationLabel(NULL)
{
   QSplitter* pSplitter = new QSplitter(this);

   // Dataset list
   QWidget* pDatasetWidget = new QWidget(pSplitter);
   QLabel* pDatasetLabel = new QLabel("Data Sets:", pDatasetWidget);

   mpDatasetTree = new QTreeWidget(pDatasetWidget);
   mpDatasetTree->setSelectionMode(QAbstractItemView::SingleSelection);
   mpDatasetTree->setSelectionBehavior(QAbstractItemView::SelectItems);
   mpDatasetTree->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
   mpDatasetTree->setTextElideMode(Qt::ElideLeft);
   mpDatasetTree->setMinimumWidth(225);
   mpDatasetTree->setHeaderHidden(true);

   QPushButton* pImportAllButton = new QPushButton("Import All", pDatasetWidget);
   QPushButton* pImportNoneButton = new QPushButton("Import None", pDatasetWidget);

   // Classification label
   QWidget* pInfoWidget = new QWidget(pSplitter);

   QFont labelFont = font();
   labelFont.setBold(true);

   mpClassificationLabel = new QLabel(pInfoWidget);
   mpClassificationLabel->setFont(labelFont);
   mpClassificationLabel->setAlignment(Qt::AlignCenter);

   // Tab widget
   mpTabWidget = new QTabWidget(pInfoWidget);
   mpDataPage = new DataDescriptorWidget();
   mpFilePage = new FileDescriptorWidget();
   mpClassificationPage = new ClassificationWidget();
   mpSubsetPage = new SubsetWidget();
   mpMetadataPage = new MetadataWidget();
   mpWavelengthsPage = new WavelengthsWidget();

   mpTabWidget->addTab(mpDataPage, "Data");
   mpTabWidget->addTab(mpFilePage, "File");
   mpTabWidget->addTab(mpClassificationPage, "Classification");
   mpTabWidget->addTab(mpSubsetPage, "Subset");
   mpTabWidget->addTab(mpMetadataPage, "Metadata");

   // Validation label
   mpValidationLabel = new QLabel(this);
   mpValidationLabel->setWordWrap(true);

   QFont validationFont = mpValidationLabel->font();
   validationFont.setBold(true);
   mpValidationLabel->setFont(validationFont);

   // Dialog buttons
   mpOkButton = new QPushButton("&OK", this);
   QPushButton* pCancelButton = new QPushButton("&Cancel", this);

   // Layout
   QLayout* pDataLayout = mpDataPage->layout();
   if (pDataLayout != NULL)
   {
      pDataLayout->setMargin(10);
   }

   QLayout* pFileLayout = mpFilePage->layout();
   if (pFileLayout != NULL)
   {
      pFileLayout->setMargin(10);
   }

   QLayout* pClassificationLayout = mpClassificationPage->layout();
   if (pClassificationLayout != NULL)
   {
      pClassificationLayout->setMargin(10);
   }

   QLayout* pSubsetLayout = mpSubsetPage->layout();
   if (pSubsetLayout != NULL)
   {
      pSubsetLayout->setMargin(10);
   }

   QLayout* pMetadataLayout = mpMetadataPage->layout();
   if (pMetadataLayout != NULL)
   {
      pMetadataLayout->setMargin(10);
   }

   QLayout* pWavelengthsLayout = mpWavelengthsPage->layout();
   if (pWavelengthsLayout != NULL)
   {
      pWavelengthsLayout->setMargin(10);
   }

   QGridLayout* pDatasetLayout = new QGridLayout(pDatasetWidget);
   pDatasetLayout->setMargin(0);
   pDatasetLayout->setSpacing(5);
   pDatasetLayout->addWidget(pDatasetLabel, 0, 0, 1, 2);
   pDatasetLayout->addWidget(mpDatasetTree, 1, 0, 1, 2);
   pDatasetLayout->addWidget(pImportAllButton, 2, 0, Qt::AlignRight);
   pDatasetLayout->addWidget(pImportNoneButton, 2, 1);
   pDatasetLayout->setRowStretch(1, 10);
   pDatasetLayout->setColumnStretch(0, 10);

   QVBoxLayout* pInfoLayout = new QVBoxLayout(pInfoWidget);
   pInfoLayout->setMargin(0);
   pInfoLayout->setSpacing(10);
   pInfoLayout->addWidget(mpClassificationLabel);
   pInfoLayout->addWidget(mpTabWidget, 10);

   QHBoxLayout* pButtonLayout = new QHBoxLayout();
   pButtonLayout->setMargin(0);
   pButtonLayout->setSpacing(5);
   pButtonLayout->addWidget(mpValidationLabel, 10);
   pButtonLayout->addWidget(mpOkButton, 0, Qt::AlignBottom);
   pButtonLayout->addWidget(pCancelButton, 0, Qt::AlignBottom);

   QVBoxLayout* pVBox = new QVBoxLayout(this);
   pVBox->setMargin(10);
   pVBox->setSpacing(10);
   pVBox->addWidget(pSplitter, 10);
   pVBox->addLayout(pButtonLayout);

   // Initialization
   setWindowTitle("Import Options");
   setModal(true);
   resize(700, 450);

   pSplitter->addWidget(pDatasetWidget);
   pSplitter->addWidget(pInfoWidget);

   // Populate the data set tree widget
   QTreeWidgetItem* pSelectItem = NULL;

   QMap<QString, vector<ImportDescriptor*> >::const_iterator fileIter;
   for (fileIter = files.begin(); fileIter != files.end(); ++fileIter)
   {
      // Filename item
      QString filename = fileIter.key();
      if (filename.isEmpty() == true)
      {
         continue;
      }

      QTreeWidgetItem* pFileItem = new QTreeWidgetItem(mpDatasetTree);

      QFileInfo fileInfo(filename);
      pFileItem->setText(0, fileInfo.fileName());
      pFileItem->setIcon(0, style()->standardIcon(QStyle::SP_FileIcon));
      pFileItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
      pFileItem->setToolTip(0, filename);
      pFileItem->setCheckState(0, Qt::Unchecked);

      // Dataset items
      vector<ImportDescriptor*> fileDatasets = fileIter.value();
      vector<ImportDescriptor*> datasets;
      copy(fileDatasets.begin(), fileDatasets.end(), back_inserter(datasets));
      stable_sort(datasets.begin(), datasets.end(), ElementDepthComparitor());

      map<vector<string>, QTreeWidgetItem*> parentPaths;

      vector<ImportDescriptor*>::iterator datasetIter;
      for (datasetIter = datasets.begin(); datasetIter != datasets.end(); ++datasetIter)
      {
         ImportDescriptor* pImportDescriptor = *datasetIter;
         if (pImportDescriptor == NULL)
         {
            continue;
         }

         DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor();
         if (pDescriptor == NULL)
         {
            continue;
         }

         const string& name = pDescriptor->getName();
         if (name.empty())
         {
            continue;
         }

         QTreeWidgetItem* pItem = new QTreeWidgetItem(static_cast<QTreeWidget*>(NULL),
            QStringList() << QString::fromStdString(name));
         if (pItem == NULL)
         {
            continue;
         }

         // Tool tip
         pItem->setToolTip(0, QString::fromStdString(name));

         // Check state
         Qt::ItemFlags itemFlags = pItem->flags();
         itemFlags |= Qt::ItemIsUserCheckable;
         pItem->setFlags(itemFlags);

         if (pImportDescriptor->isImported())
         {
            pItem->setCheckState(0, Qt::Checked);

            if (pSelectItem == NULL)
            {
               pSelectItem = pItem;
            }
         }
         else
         {
            pItem->setCheckState(0, Qt::Unchecked);
         }

         // Add to the proper parent
         map<vector<string>, QTreeWidgetItem*>::iterator parent = parentPaths.find(pDescriptor->getParentDesignator());
         if (parent != parentPaths.end())
         {
            parent->second->addChild(pItem);
         }
         else
         {
            pFileItem->addChild(pItem);
         }

         vector<string> myDesignator = pDescriptor->getParentDesignator();
         myDesignator.push_back(pDescriptor->getName());
         parentPaths[myDesignator] = pItem;

         mDatasets[pImportDescriptor] = pItem;
         validateDataset(pDescriptor);
         enforceSelections(pItem);
      }
   }

   mpDatasetTree->expandAll();

   // Update the tab widget for the selected data set
   if (pSelectItem == NULL)
   {
      // No data set is set to import by default so select the first data set in the tree widget
      for (int i = 0; i < mpDatasetTree->topLevelItemCount() && pSelectItem == NULL; ++i)
      {
         QTreeWidgetItem* pParentItem = mpDatasetTree->topLevelItem(i);
         if ((pParentItem != NULL) && (pParentItem->childCount() > 0))
         {
            pSelectItem = pParentItem->child(0);
         }
      }
   }

   if (pSelectItem != NULL)
   {
      mpDatasetTree->setItemSelected(pSelectItem, true);
      updateEditDataset();
   }

   // Connections
   VERIFYNR(connect(mpDatasetTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
      SLOT(datasetItemChanged(QTreeWidgetItem*))));
   VERIFYNR(connect(mpDatasetTree, SIGNAL(itemSelectionChanged()), this, SLOT(updateEditDataset())));
   VERIFYNR(connect(pImportAllButton, SIGNAL(clicked()), this, SLOT(selectAllDatasets())));
   VERIFYNR(connect(pImportNoneButton, SIGNAL(clicked()), this, SLOT(deselectAllDatasets())));
   VERIFYNR(connect(mpOkButton, SIGNAL(clicked()), this, SLOT(accept())));
   VERIFYNR(connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject())));
   updateConnections(true);
}
예제 #24
0
string TextObjectImp::getSubstitutedText()
{
   string txt = getText();

   DataElement* pParent = getElement();
   pParent = (pParent == NULL) ? NULL : pParent->getParent();
   DataDescriptor* pParentDesc = (pParent == NULL) ? NULL : pParent->getDataDescriptor();
   DynamicObject* pParentMetadata = (pParentDesc == NULL) ? NULL : pParentDesc->getMetadata();
   for (int i = 0; i < 50; ++i)
   {
      //each pass does replacement of $M(a) currently in the string.
      //do 50 passes to perform sub-expansion at most fifty times, ie. prevent infinite loop
      //for non-terminating recursive expansion
      string::size_type pos = txt.find("$");
      while (pos != string::npos)
      {
         if (pos + 1 >= txt.size())
         {
            break;
         }
         string type = txt.substr(pos+1, 1);
         if (type != "$") //ie. not $$, the escape sequence so continue
         {
            bool replaced = false;
            if (pos+4 < txt.size()) //ie. $M(a)
            {
               if (txt[pos+2] == '(')
               {
                  string::size_type closeParen = txt.find(')', pos+2);
                  if (closeParen == string::npos)
                  {
                     closeParen = txt.size();
                  }
                  string variableName = txt.substr(pos+3, closeParen-(pos+2)-1);
                  string replacementString;
                  if (type == "M" || type == "S")
                  {
                     DataElement* pElmnt = pParent;
                     DynamicObject* pMetadata = pParentMetadata;
                     if (variableName.substr(0, 2) == "//")
                     {
                        string::size_type endNamePos = variableName.find("//", 2);
                        if (endNamePos != string::npos)
                        {
                           string elementName = variableName.substr(2, endNamePos - 2);
                           variableName = variableName.substr(endNamePos + 2);
                           if (!variableName.empty())
                           {
                              if (elementName[0] == '[' && elementName[elementName.size() - 1] == ']')
                              {
                                 elementName = elementName.substr(1, elementName.size() - 2);
                                 std::list<GraphicObject*> objects;
                                 getLayer()->getObjects(VIEW_OBJECT, objects);
                                 for (std::list<GraphicObject*>::iterator object = objects.begin();
                                    object != objects.end(); ++object)
                                 {
                                    GraphicObject* pObj = *object;
                                    if (pObj->getName() == elementName)
                                    {
                                       SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pObj->getObjectView());
                                       if (pSdv != NULL)
                                       {
                                          pElmnt = pSdv->getLayerList()->getPrimaryRasterElement();
                                          DataDescriptor* pDesc =
                                             (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                          pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                                       }
                                       break;
                                    }
                                 }
                              }
                              else
                              {
                                 pElmnt = Service<ModelServices>()->getElement(elementName,
                                    TypeConverter::toString<RasterElement>(), NULL);
                                 DataDescriptor* pDesc = (pElmnt == NULL) ? NULL : pElmnt->getDataDescriptor();
                                 pMetadata = (pDesc == NULL) ? NULL : pDesc->getMetadata();
                              }
                           }
                           else
                           {
                              pElmnt = NULL;
                              pMetadata = NULL;
                           }
                        }
                     }
                     bool success = false;
                     if (type == "M" && pMetadata != NULL)
                     {
                        DataVariant var = pMetadata->getAttributeByPath(variableName);
                        if (var.isValid())
                        {
                           DataVariant::Status status;
                           replacementString = var.toDisplayString(&status);
                           success = (status == DataVariant::SUCCESS);
                           if (mMetadataObjects.find(pMetadata) == mMetadataObjects.end())
                           {
                              mMetadataObjects.insert(make_pair(pMetadata, new AttachmentPtr<DynamicObject>(
                                 pMetadata, SIGNAL_NAME(Subject, Modified),
                                 Slot(this, &TextObjectImp::invalidateTexture))));
                           }
                        }
                     }
                     else if (type == "S" && pElmnt != NULL && variableName == "CLASSIFICATION")
                     {
                        Classification* pClass = pElmnt->getDataDescriptor()->getClassification();
                        pClass->getClassificationText(replacementString);
                        success = true;
                        if (mClassificationObjects.find(pClass) == mClassificationObjects.end())
                        {
                           mClassificationObjects.insert(make_pair(pClass, new AttachmentPtr<Classification>(
                              pClass, SIGNAL_NAME(Subject, Modified),
                              Slot(this, &TextObjectImp::invalidateTexture))));
                        }
                     }
                     if (!success)
                     {
                        replacementString = "Error!";
                     }
                     replaced = true;
                  }
                  if (replaced)
                  {
                     txt.replace(pos, closeParen-pos+1, replacementString);
                     pos = txt.find("$", pos+replacementString.size());
                  }
               }
            }
            if (!replaced)
            {
               pos = txt.find("$", pos+1);
            }
         }
         else
         {
            pos = txt.find("$", pos+2);
         }
      }
   }
   string::size_type pos = txt.find("$$");
   while (pos != string::npos)
   {
      txt.replace(pos, 2, "$");
      pos = txt.find("$$");
   }

   return txt;
}
bool Test_Update_TerraSAR::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
  StepResource pStep("Tutorial CEO", "app", "0FD3C564-041D-4f8f-BBF8-96A7A165AB61");

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

      return false;
   }

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

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

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

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* Metadata = dMeta->getMetadata();

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

	bool control = Prova_metadata.ReadFile(path);

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

	Prova_metadata.UpdateMetadata(Metadata); 

	//SAR_Model ModProva(Prova_metadata,1000);

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

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

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


	std::list<GcpPoint> Punti;

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

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


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

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



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

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

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

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

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

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

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

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

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

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


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

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

	}


	pStep->finalize(); 

	return true;
}
예제 #26
0
bool ModelExporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   Progress* pProgress = NULL;
   FileDescriptor* pFileDescriptor = NULL;
   DataElement* pElement = NULL;

   StepResource pStep("Export model element", "app", "2BF48AAB-4832-4694-8583-882A8D584E97");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "1B02F950-2E04-4BEF-8561-BB8D993340F7");

      pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (pProgress != NULL));

      pFileDescriptor = pInArgList->getPlugInArgValue<FileDescriptor>(Exporter::ExportDescriptorArg());
      if (pFileDescriptor == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No file specified", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No file specified");
         return false;
      }
      pMsg->addProperty("Destination", pFileDescriptor->getFilename());

      pElement = pInArgList->getPlugInArgValueUnsafe<DataElement>(Exporter::ExportItemArg());
      if (pElement == NULL)
      {
         if (pProgress != NULL)
         {
            pProgress->updateProgress("No model element specified", 100, ERRORS);
         }
         pStep->finalize(Message::Failure, "No model element specified");
         return false;
      }
      pMsg->addProperty("Name", pElement->getName());
   }

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Open output file", 10, NORMAL);
   }
   FILE* pFile = fopen(pFileDescriptor->getFilename().getFullPathAndName().c_str(), "w");
   if (pFile == NULL)
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("File can not be created", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "File can not be created");
      return false;
   }

   DataDescriptor* pElementDescriptor = pElement->getDataDescriptor();
   VERIFY(pElementDescriptor != NULL);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Save element", 20, NORMAL);
   }
   string elementName = pElementDescriptor->getType();
   XMLWriter xml(elementName.c_str(), Service<MessageLogMgr>()->getLog());
   if (!pElement->toXml(&xml))
   {
      if (pProgress != NULL)
      {
         pProgress->updateProgress("Error saving model element", 100, ERRORS);
      }
      pStep->finalize(Message::Failure, "Error saving model element");
      return false;
   }
   else
   {
      xml.writeToFile(pFile);
   }
   fclose(pFile);

   if (pProgress != NULL)
   {
      pProgress->updateProgress("Finished saving the model element", 100, NORMAL);
   }
   pStep->finalize(Message::Success);
   return true;
}
void Simulation_GUI::CheckModel()
{
   ProgressResource pProgress("ProgressBar");

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

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

   DataDescriptor* dMeta = pCube->getDataDescriptor();

   DynamicObject* oMetadata = dMeta->getMetadata();

	// RETRIEVE & UPDATE METADATA INFORMATION //

	bool control = Metadata->ReadFile(image_path);

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

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

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

	//SAR_Model ModProva(*Metadata);

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

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

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

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

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

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

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


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

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

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

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

     //	pStep->finalize(); 
}
예제 #28
0
bool Nitf::NitfImporterShell::createRasterPager(RasterElement* pRaster) const
{
   if (pRaster == NULL)
   {
      return false;
   }

   // Get the filename
   string filename = pRaster->getFilename();

   FactoryResource<Filename> pFilename;
   pFilename->setFullPathAndName(filename);

   // Get the image segment corresponding to this raster element
   DataDescriptor* pDescriptor = pRaster->getDataDescriptor();
   VERIFY(pDescriptor != NULL);

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

   const string& datasetLocation = pFileDescriptor->getDatasetLocation();
   if (datasetLocation.empty() == true)
   {
      return false;
   }

   string imageSegmentText = datasetLocation.substr(1);
   unsigned int imageSegment = StringUtilities::fromDisplayString<unsigned int>(imageSegmentText) - 1;

   // Create the resource to execute the pager
   ExecutableResource pPlugIn;

   // Check for J2K compression in the metadata of the raster element being imported and not the given raster
   // element, because the given raster element may be a temporary raster element used by RasterElementImporterShell
   // when the processing location is IN_MEMORY, which does not contain the metadata or the parent information
   // (see RasterUtilities::generateUnchippedRasterDataDescriptor())
   string imageCompression;

   const RasterElement* pElement = getRasterElement();
   if (pElement != NULL)
   {
      const DynamicObject* pMetadata = pElement->getMetadata();
      VERIFYRV(pMetadata, NULL);

      const string attributePath[] =
      {
         Nitf::NITF_METADATA,
         Nitf::IMAGE_SUBHEADER,
         Nitf::ImageSubheaderFieldNames::COMPRESSION,
         END_METADATA_NAME
      };

      imageCompression = pMetadata->getAttributeByPath(attributePath).toDisplayString();
   }

   if ((imageCompression == Nitf::ImageSubheaderFieldValues::IC_C8) ||
      (imageCompression == Nitf::ImageSubheaderFieldValues::IC_M8))
   {
      // Get the offset and size of the image segment in the file
      uint64_t offset = getImageOffset(filename, imageSegment);
      uint64_t size = getImageSize(filename, imageSegment);

      // Use the JPEG2000 pager
      pPlugIn->setPlugIn("JPEG2000 Pager");
      pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedElementArg(), pRaster);
      pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedFilenameArg(), pFilename.get());
      pPlugIn->getInArgList().setPlugInArgValue("Offset", &offset);
      pPlugIn->getInArgList().setPlugInArgValue("Size", &size);
   }
   else
   {
      // Use the NITF Pager
      pPlugIn->setPlugIn("NitfPager");
      pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedElementArg(), pRaster);
      pPlugIn->getInArgList().setPlugInArgValue(CachedPager::PagedFilenameArg(), pFilename.get());
      pPlugIn->getInArgList().setPlugInArgValue("Segment Number", &imageSegment);
   }

   if (pPlugIn->execute() == true)
   {
      RasterPager* pPager = dynamic_cast<RasterPager*>(pPlugIn->getPlugIn());
      if (pPager != NULL)
      {
         pRaster->setPager(pPager);
         pPlugIn->releasePlugIn();
         return true;
      }
   }

   return false;
}