bool LandsatEtmPlusImporter::createRasterPager(RasterElement* pRaster) const
{
   string srcFile = pRaster->getFilename();
   if (srcFile.empty())
   {
      return false;
   }
   {
      //scoping to ensure the file is closed before creating the pager
      LargeFileResource srcFileRes;
      if (!srcFileRes.open(srcFile, O_RDONLY | O_BINARY, S_IREAD))
      {
         return false;
      }
   }
   // create the pager
   ExecutableResource pPager("BandResamplePager");
   VERIFY(pPager->getPlugIn() != NULL);
   bool isWritable = false;
   bool useDataDescriptor = false;
   FactoryResource<Filename> pFilename;
   VERIFY(pFilename.get() != NULL);
   pFilename->setFullPathAndName(pRaster->getFilename());

   pPager->getInArgList().setPlugInArgValue("Raster Element", pRaster);
   pPager->getInArgList().setPlugInArgValue("Filename", pFilename.get());
   pPager->getInArgList().setPlugInArgValue("isWritable", &isWritable);
   pPager->getInArgList().setPlugInArgValue("Use Data Descriptor", &useDataDescriptor);
   RasterDataDescriptor* pDescriptor = static_cast<RasterDataDescriptor*>(pRaster->getDataDescriptor());
   VERIFY(pDescriptor != NULL);
   RasterFileDescriptor* pFileDescriptor = static_cast<RasterFileDescriptor*>(pDescriptor->getFileDescriptor());
   VERIFY(pFileDescriptor != NULL);
   unsigned int band = 5, rows = mB6Rows, cols = mB6Cols;
   pPager->getInArgList().setPlugInArgValue("Band", &band);
   pPager->getInArgList().setPlugInArgValue("Rows", &rows);
   pPager->getInArgList().setPlugInArgValue("Columns", &cols);
   if (!pPager->execute())
   {
      return false;
   }
   RasterPager* pRasterPager = dynamic_cast<RasterPager*>(pPager->getPlugIn());
   if (pRasterPager != NULL)
   {
      pPager->releasePlugIn();
   }
   else
   {
      return false;
   }

   pRaster->setPager(pRasterPager);
   return true;
}
bool RasterElementImporterShell::performImport() const
{
   Progress* pProgress = getProgress();
   StepResource pStep("Perform import", "app", "762EF4BB-8813-4e45-B1BD-4CD237F7C151");

   FAIL_IF(mpRasterElement == NULL, "Could not find RasterElement", return false);

   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(
      mpRasterElement->getDataDescriptor());
   FAIL_IF(pDescriptor == NULL, "Could not find RasterDataDescriptor", return false);

   string message;

//#pragma message(__FILE__ "(" STRING(__LINE__) ") : warning : Re-evaluate this code when plug-ins " \
//   "are being loaded into the global symbol space (tclarke)")
   // This was changed from a try/catch due to a problem with the exceptions 
   // not being caught and propagating up to QApplication::notify on solaris.
   // it is believed this is due to how we load plug-ins;
   // they are loaded into a private symbol space. When this changes,
   // re-evaluate the try/catch model.
   if (pDescriptor->getProcessingLocation() == ON_DISK_READ_ONLY)
   {
      Service<SessionManager> pSessionManager;
      if (pSessionManager->isSessionLoading() == false)
      {
         RasterFileDescriptor* pOrigFileDescriptor = dynamic_cast<RasterFileDescriptor*>(pDescriptor->getFileDescriptor());
         std::vector<DimensionDescriptor> orgRows = pOrigFileDescriptor->getRows();
         std::vector<DimensionDescriptor> orgColumns = pOrigFileDescriptor->getColumns();
         std::vector<DimensionDescriptor> orgBands = pOrigFileDescriptor->getBands();

         std::vector<DimensionDescriptor>::iterator iter;
         unsigned int i = 0;
         for (iter = orgRows.begin(), i = 0; iter != orgRows.end(); ++iter, ++i)
         {
            iter->setActiveNumber(i);
         }
         for (iter = orgColumns.begin(), i = 0; iter != orgColumns.end(); ++iter, ++i)
         {
            iter->setActiveNumber(i);
         }
         for (iter = orgBands.begin(), i = 0; iter != orgBands.end(); ++iter, ++i)
         {
            iter->setActiveNumber(i);
         }
         vector<DimensionDescriptor> selectedRows = getSelectedDims(orgRows,
            pDescriptor->getRows());
         vector<DimensionDescriptor> selectedColumns = getSelectedDims(orgColumns,
            pDescriptor->getColumns());
         vector<DimensionDescriptor> selectedBands = getSelectedDims(orgBands,
            pDescriptor->getBands());

         if (!RasterUtilities::chipMetadata(mpRasterElement->getMetadata(),
            selectedRows, selectedColumns, selectedBands))
         {
            return checkAbortOrError("Could not chip metadata", pStep.get());
         }
      }

      if (createRasterPager(mpRasterElement) == false)
      {
         return checkAbortOrError("Could not create pager for RasterElement", pStep.get());
      }
   }
   else
   {
      if (mpRasterElement->createDefaultPager() == false)
      {
         return checkAbortOrError("Could not allocate resources for new RasterElement", pStep.get());
      }
      RasterDataDescriptor* pSourceDescriptor = RasterUtilities::generateUnchippedRasterDataDescriptor(mpRasterElement);
      if (pSourceDescriptor == NULL)
      {
         return checkAbortOrError("Could not get unchipped RasterDataDescriptor", pStep.get());
      }

      ModelResource<RasterElement> pSourceRaster(pSourceDescriptor);
      if (pSourceRaster.get() == NULL)
      {
         return checkAbortOrError("Could not create source RasterElement", pStep.get());
      }

      if (createRasterPager(pSourceRaster.get()) == false)
      {
         return checkAbortOrError("Could not create pager for source RasterElement", pStep.get());
      }

      if (copyData(pSourceRaster.get()) == false)
      {
         return checkAbortOrError("Could not copy data from source RasterElement", pStep.get());
      }

      double value = 0.0;
      uint64_t badValueCount = mpRasterElement->sanitizeData(value);
      if (badValueCount != 0)
      {
         if (mpProgress != NULL)
         {
            string message = StringUtilities::toDisplayString(badValueCount) + " bad value(s) found in data.\n" +
               "Bad values set to " + StringUtilities::toDisplayString(value);
            mpProgress->updateProgress(message, 100, WARNING);
         }
      }
   }

   pStep->finalize(Message::Success);
   return true;
}
std::vector<ImportDescriptor*> LandsatGeotiffImporter::createImportDescriptors(const std::string& filename,
   const DynamicObject* pImageMetadata,
   Landsat::LandsatImageType type)
{
   std::string suffix;
   if (type == Landsat::LANDSAT_VNIR)
   {
      suffix = "vnir";
   }
   else if (type == Landsat::LANDSAT_PAN)
   {
      suffix = "pan";
   }
   else if (type == Landsat::LANDSAT_TIR)
   {
      suffix = "tir";
   }
   std::vector<ImportDescriptor*> descriptors;
   std::string spacecraft = dv_cast<std::string>(
      pImageMetadata->getAttributeByPath("LANDSAT_MTL/L1_METADATA_FILE/PRODUCT_METADATA/SPACECRAFT_ID"), "");
   std::vector<std::string> bandNames = Landsat::getSensorBandNames(spacecraft, type);
   if (bandNames.empty())
   {
      //this spacecraft and iamge type
      //isn't meant to have any bands, so terminate early
      //e.g. spacecraft == "Landsat5" && type == Landsat::LANDSAT_PAN
      return descriptors;
   }
   std::vector<unsigned int> validBands;
   std::vector<std::string> bandFiles = Landsat::getGeotiffBandFilenames(
      pImageMetadata, filename, type, validBands);
   if (bandFiles.empty())
   {
      mWarnings.push_back("Unable to locate band files for " + suffix + " product."); 
      return descriptors;
   }
   ImportDescriptorResource pImportDescriptor(filename + "-" + suffix,
      TypeConverter::toString<RasterElement>(), NULL, false);
   if (pImportDescriptor.get() == NULL)
   {
      return descriptors;
   }
   RasterDataDescriptor* pDescriptor = dynamic_cast<RasterDataDescriptor*>(pImportDescriptor->getDataDescriptor());
   if (pDescriptor == NULL)
   {
      return descriptors;
   }
   pDescriptor->setProcessingLocation(ON_DISK);
   DynamicObject* pMetadata = pDescriptor->getMetadata();
   pMetadata->merge(pImageMetadata);
   FactoryResource<RasterFileDescriptor> pFileDescriptorRes;
   pDescriptor->setFileDescriptor(pFileDescriptorRes.get());
   RasterFileDescriptor* pFileDescriptor = dynamic_cast<RasterFileDescriptor*>(pDescriptor->getFileDescriptor());
   pFileDescriptor->setFilename(filename);

   std::string tiffFile = bandFiles[0];
   if (!Landsat::parseBasicsFromTiff(tiffFile, pDescriptor))
   {
      mWarnings.push_back("Unable to parse basic information about image from tiff file for " + suffix + " product.");
      return descriptors;
   }
   if (pDescriptor->getBandCount() != 1 || pDescriptor->getDataType() != INT1UBYTE)
   {
      mWarnings.push_back("Improperly formatted tiff file for " + suffix + " product.");
      return descriptors;
   }
   pDescriptor->setInterleaveFormat(BSQ); //one tiff file per band.
   pFileDescriptor->setInterleaveFormat(BSQ);
   std::vector<DimensionDescriptor> bands = RasterUtilities::generateDimensionVector(
      bandFiles.size(), true, false, true);
   pDescriptor->setBands(bands);
   pFileDescriptor->setBands(bands);
   pDescriptor->setBadValues(std::vector<int>(1, 0));
   pFileDescriptor->setDatasetLocation(suffix);

   //special metadata here
   Landsat::fixMtlMetadata(pMetadata, type, validBands);

   std::vector<std::string> defaultImport = OptionsLandsatImport::getSettingDefaultImport();
   bool fallbackToDn = false;
   descriptors.push_back(pImportDescriptor.release());

   if (type == Landsat::LANDSAT_VNIR)
   {
      //attempt to display true-color
      DimensionDescriptor redBand = RasterUtilities::findBandWavelengthMatch(0.630, 0.690, pDescriptor);
      DimensionDescriptor greenBand = RasterUtilities::findBandWavelengthMatch(0.510, 0.590, pDescriptor);
      DimensionDescriptor blueBand = RasterUtilities::findBandWavelengthMatch(0.410, 0.490, pDescriptor);
      if (redBand.isValid() && greenBand.isValid() && blueBand.isValid())
      {
         pDescriptor->setDisplayMode(RGB_MODE);
         pDescriptor->setDisplayBand(RED, redBand);
         pDescriptor->setDisplayBand(GREEN, greenBand);
         pDescriptor->setDisplayBand(BLUE, blueBand);
      }
   }

   std::vector<std::pair<double, double> > radianceFactors = Landsat::determineRadianceConversionFactors(
      pMetadata, type, validBands);
   bool shouldDefaultImportRadiance =
      std::find(defaultImport.begin(), defaultImport.end(), suffix + "-Radiance") != defaultImport.end();
   if (radianceFactors.size() == bandFiles.size())
   {
      //we have enough to create radiance import descriptor
      RasterDataDescriptor* pRadianceDescriptor = dynamic_cast<RasterDataDescriptor*>(
         pDescriptor->copy(filename + "-" + suffix + "-radiance", NULL));
      if (pRadianceDescriptor != NULL)
      {
         pRadianceDescriptor->setDataType(FLT4BYTES);
         pRadianceDescriptor->setValidDataTypes(std::vector<EncodingType>(1, pRadianceDescriptor->getDataType()));
         pRadianceDescriptor->setBadValues(std::vector<int>(1, -100));
         FactoryResource<Units> pUnits;
         pUnits->setUnitType(RADIANCE);
         pUnits->setUnitName("w/(m^2*sr*um)");
         pUnits->setScaleFromStandard(1.0);
         pRadianceDescriptor->setUnits(pUnits.get());
         FileDescriptor* pRadianceFileDescriptor = pRadianceDescriptor->getFileDescriptor();
         if (pRadianceFileDescriptor != NULL)
         {
            pRadianceFileDescriptor->setDatasetLocation(suffix + "-radiance");
            ImportDescriptorResource pRadianceImportDescriptor(pRadianceDescriptor,
               shouldDefaultImportRadiance);
            descriptors.push_back(pRadianceImportDescriptor.release());
         }
      }
   }
   else if (shouldDefaultImportRadiance)
   {
      fallbackToDn = true;
   }

   std::vector<double> reflectanceFactors = Landsat::determineReflectanceConversionFactors(
      pMetadata, type, validBands);
   bool shouldDefaultImportReflectance =
      std::find(defaultImport.begin(), defaultImport.end(), suffix + "-Reflectance") != defaultImport.end();
   if (radianceFactors.size() == bandFiles.size() && reflectanceFactors.size() == bandFiles.size())
   {
      //we have enough to create reflectance import descriptor
      RasterDataDescriptor* pReflectanceDescriptor = dynamic_cast<RasterDataDescriptor*>(
         pDescriptor->copy(filename + "-" + suffix + "-reflectance", NULL));
      if (pReflectanceDescriptor != NULL)
      {
         pReflectanceDescriptor->setDataType(INT2SBYTES);
         pReflectanceDescriptor->setValidDataTypes(
            std::vector<EncodingType>(1, pReflectanceDescriptor->getDataType()));
         pReflectanceDescriptor->setBadValues(std::vector<int>(1, std::numeric_limits<short>::max()));
         FactoryResource<Units> pUnits;
         pUnits->setUnitType(REFLECTANCE);
         pUnits->setUnitName("Reflectance");
         pUnits->setScaleFromStandard(1/10000.0);
         pReflectanceDescriptor->setUnits(pUnits.get());
         FileDescriptor* pReflectanceFileDescriptor = pReflectanceDescriptor->getFileDescriptor();
         if (pReflectanceFileDescriptor != NULL)
         {
            pReflectanceFileDescriptor->setDatasetLocation(suffix + "-reflectance");
            ImportDescriptorResource pReflectanceImportDescriptor(pReflectanceDescriptor,
               shouldDefaultImportReflectance);
            descriptors.push_back(pReflectanceImportDescriptor.release());
         }
      }
   }
   else if (shouldDefaultImportReflectance)
   {
      fallbackToDn = true;
   }

   double K1 = 0.0;
   double K2 = 0.0;
   bool haveTemperatureFactors = Landsat::getTemperatureConstants(pMetadata, type,
      K1, K2);
   bool shouldDefaultImportTemperature =
      std::find(defaultImport.begin(), defaultImport.end(), suffix + "-Temperature") != defaultImport.end();
   if (radianceFactors.size() == bandFiles.size() && haveTemperatureFactors)
   {
      //we have enough to create temperature import descriptor
      RasterDataDescriptor* pTemperatureDescriptor = dynamic_cast<RasterDataDescriptor*>(
         pDescriptor->copy(filename + "-" + suffix + "-temperature", NULL));
      if (pTemperatureDescriptor != NULL)
      {
         pTemperatureDescriptor->setDataType(FLT4BYTES);
         pTemperatureDescriptor->setValidDataTypes(
            std::vector<EncodingType>(1, pTemperatureDescriptor->getDataType()));
         pTemperatureDescriptor->setBadValues(std::vector<int>(1, -1));
         FactoryResource<Units> pUnits;
         pUnits->setUnitType(EMISSIVITY);
         pUnits->setUnitName("K");
         pUnits->setScaleFromStandard(1.0);
         pTemperatureDescriptor->setUnits(pUnits.get());
         FileDescriptor* pTemperatureFileDescriptor = pTemperatureDescriptor->getFileDescriptor();
         if (pTemperatureFileDescriptor != NULL)
         {
            pTemperatureFileDescriptor->setDatasetLocation(suffix + "-temperature");
            ImportDescriptorResource pTemperatureImportDescriptor(pTemperatureDescriptor,
               shouldDefaultImportTemperature);
            descriptors.push_back(pTemperatureImportDescriptor.release());
         }
      }
   }
   else if (shouldDefaultImportTemperature)
   {
      fallbackToDn = true;
   }

   if (fallbackToDn ||
      std::find(defaultImport.begin(), defaultImport.end(), suffix + "-DN") != defaultImport.end())
   {
      pImportDescriptor->setImported(true);
   }

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

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

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

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

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

   

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

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

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

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

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

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

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


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

		*/
		unsigned short *ptr=NULL;

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

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


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


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

	RawProcessor.recycle();
   
   return true;
}
示例#5
0
bool EditDataDescriptor::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "055486F4-A9DB-4FDA-9AA7-75D1917E2C87");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

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

   // Set the values in the data descriptor
   VERIFY(mpDescriptor != NULL);

   // File descriptor
   if (mpFileDescriptor != NULL)
   {
      mpDescriptor->setFileDescriptor(mpFileDescriptor);
   }

   // Processing location
   if (mpProcessingLocation != NULL)
   {
      mpDescriptor->setProcessingLocation(*mpProcessingLocation);
   }

   RasterDataDescriptor* pRasterDescriptor = dynamic_cast<RasterDataDescriptor*>(mpDescriptor);
   RasterFileDescriptor* pRasterFileDescriptor = dynamic_cast<RasterFileDescriptor*>(mpFileDescriptor);
   SignatureDataDescriptor* pSignatureDescriptor = dynamic_cast<SignatureDataDescriptor*>(mpDescriptor);
   SignatureFileDescriptor* pSignatureFileDescriptor = dynamic_cast<SignatureFileDescriptor*>(mpFileDescriptor);

   if (pRasterDescriptor != NULL)
   {
      if (pRasterFileDescriptor != NULL)
      {
         // Set the rows and columns to match the rows and columns in the file descriptor before creating the subset
         const vector<DimensionDescriptor>& rows = pRasterFileDescriptor->getRows();
         pRasterDescriptor->setRows(rows);

         const vector<DimensionDescriptor>& columns = pRasterFileDescriptor->getColumns();
         pRasterDescriptor->setColumns(columns);

         const vector<DimensionDescriptor>& bands = pRasterFileDescriptor->getBands();
         pRasterDescriptor->setBands(bands);
      }

      // Data type
      if (mpDataType != NULL)
      {
         pRasterDescriptor->setDataType(*mpDataType);
      }

      // InterleaveFormat
      if (mpInterleave != NULL)
      {
         pRasterDescriptor->setInterleaveFormat(*mpInterleave);
      }

      // Bad values
      if (mpBadValues != NULL)
      {
         pRasterDescriptor->setBadValues(*mpBadValues);
      }

      // Rows
      if ((mpStartRow != NULL) || (mpEndRow != NULL) || (mpRowSkipFactor != NULL))
      {
         // We need to obtain this origRows from the FileDescriptor if present since an importer
         // may generate a subset by default in which case the DataDescriptor will not contain all
         // the rows and subsetting will not work correctly. We
         // can't just set mpFileDescriptor = pRasterDescriptor->getFileDescriptor() since we only
         // want to replace the DataDescriptor's row list if one of the subset options is specified
         const RasterFileDescriptor* pFileDesc(pRasterFileDescriptor);
         if (pFileDesc == NULL)
         {
            pFileDesc = dynamic_cast<const RasterFileDescriptor*>(pRasterDescriptor->getFileDescriptor());
         }
         const vector<DimensionDescriptor>& origRows = (pFileDesc != NULL) ?
            pFileDesc->getRows() : pRasterDescriptor->getRows();
         unsigned int startRow = 0;
         if (mpStartRow != NULL)
         {
            startRow = *mpStartRow;
         }
         else if (origRows.empty() == false)
         {
            startRow = origRows.front().getOriginalNumber() + 1;
         }

         unsigned int endRow = 0;
         if (mpEndRow != NULL)
         {
            endRow = *mpEndRow;
         }
         else if (origRows.empty() == false)
         {
            endRow = origRows.back().getOriginalNumber() + 1;
         }

         unsigned int rowSkip = 0;
         if (mpRowSkipFactor != NULL)
         {
            rowSkip = *mpRowSkipFactor;
         }

         vector<DimensionDescriptor> rows;
         for (unsigned int i = 0; i < origRows.size(); ++i)
         {
            DimensionDescriptor rowDim = origRows[i];
            unsigned int originalNumber = rowDim.getOriginalNumber() + 1;
            if ((originalNumber >= startRow) && (originalNumber <= endRow))
            {
               rows.push_back(rowDim);
               i += rowSkip;
            }
         }

         pRasterDescriptor->setRows(rows);
      }

      // Columns
      if ((mpStartColumn != NULL) || (mpEndColumn != NULL) || (mpColumnSkipFactor != NULL))
      {
         // We need to obtain this origColumns from the FileDescriptor if present since an importer
         // may generate a subset by default in which case the DataDescriptor will not contain all
         // the columns and subsetting will not work correctly. We
         // can't just set mpFileDescriptor = pRasterDescriptor->getFileDescriptor() since we only
         // want to replace the DataDescriptor's column list if one of the subset options is specified
         const RasterFileDescriptor* pFileDesc(pRasterFileDescriptor);
         if (pFileDesc == NULL)
         {
            pFileDesc = dynamic_cast<const RasterFileDescriptor*>(pRasterDescriptor->getFileDescriptor());
         }
         const vector<DimensionDescriptor>& origColumns = (pFileDesc != NULL) ?
            pFileDesc->getColumns() : pRasterDescriptor->getColumns();

         unsigned int startColumn = 0;
         if (mpStartColumn != NULL)
         {
            startColumn = *mpStartColumn;
         }
         else if (origColumns.empty() == false)
         {
            startColumn = origColumns.front().getOriginalNumber() + 1;
         }

         unsigned int endColumn = 0;
         if (mpEndColumn != NULL)
         {
            endColumn = *mpEndColumn;
         }
         else if (origColumns.empty() == false)
         {
            endColumn = origColumns.back().getOriginalNumber() + 1;
         }

         unsigned int columnSkip = 0;
         if (mpColumnSkipFactor != NULL)
         {
            columnSkip = *mpColumnSkipFactor;
         }

         vector<DimensionDescriptor> columns;
         for (unsigned int i = 0; i < origColumns.size(); ++i)
         {
            DimensionDescriptor columnDim = origColumns[i];
            unsigned int originalNumber = columnDim.getOriginalNumber() + 1;
            if ((originalNumber >= startColumn) && (originalNumber <= endColumn))
            {
               columns.push_back(columnDim);
               i += columnSkip;
            }
         }

         pRasterDescriptor->setColumns(columns);
      }

      // Bands
      if ((mpStartBand != NULL) || (mpEndBand != NULL) || (mpBandSkipFactor != NULL) || (mpBadBandsFile != NULL))
      {
         // We need to obtain this origBands from the FileDescriptor if present since an importer
         // may generate a subset by default in which case the DataDescriptor will not contain all
         // the bands and subsetting (especially by bad band file) will not work correctly. We
         // can't just set mpFileDescriptor = pRasterDescriptor->getFileDescriptor() since we only
         // want to replace the DataDescriptor's band list if one of the subset options is specified
         const RasterFileDescriptor* pFileDesc(pRasterFileDescriptor);
         if (pFileDesc == NULL)
         {
            pFileDesc = dynamic_cast<const RasterFileDescriptor*>(pRasterDescriptor->getFileDescriptor());
         }
         const vector<DimensionDescriptor>& origBands = (pFileDesc != NULL) ?
            pFileDesc->getBands() : pRasterDescriptor->getBands();

         unsigned int startBand = 0;
         if (mpStartBand != NULL)
         {
            startBand = *mpStartBand;
         }
         else if (origBands.empty() == false)
         {
            startBand = origBands.front().getOriginalNumber() + 1;
         }

         unsigned int endBand = 0;
         if (mpEndBand != NULL)
         {
            endBand = *mpEndBand;
         }
         else if (origBands.empty() == false)
         {
            endBand = origBands.back().getOriginalNumber() + 1;
         }

         unsigned int bandSkip = 0;
         if (mpBandSkipFactor != NULL)
         {
            bandSkip = *mpBandSkipFactor;
         }

         // Get the bad bands from the file
         vector<unsigned int> badBands;
         if (mpBadBandsFile != NULL)
         {
            string filename = *mpBadBandsFile;
            if (filename.empty() == false)
            {
               FILE* pFile = fopen(filename.c_str(), "rb");
               if (pFile != NULL)
               {
                  char line[1024];
                  while (fgets(line, 1024, pFile) != NULL)
                  {
                     unsigned int bandNumber = 0;

                     int iValues = sscanf(line, "%u", &bandNumber);
                     if (iValues == 1)
                     {
                        badBands.push_back(bandNumber);
                     }
                  }

                  fclose(pFile);
               }
            }
         }

         vector<DimensionDescriptor> bands;
         for (unsigned int i = 0; i < origBands.size(); ++i)
         {
            DimensionDescriptor bandDim = origBands[i];
            unsigned int originalNumber = bandDim.getOriginalNumber() + 1;
            if ((originalNumber >= startBand) && (originalNumber <= endBand))
            {
               bool bBad = false;
               for (unsigned int j = 0; j < badBands.size(); ++j)
               {
                  unsigned int badBandNumber = badBands[j];
                  if (originalNumber == badBandNumber)
                  {
                     bBad = true;
                     break;
                  }
               }

               if (bBad == false)
               {
                  bands.push_back(bandDim);
                  i += bandSkip;
               }
            }
         }

         pRasterDescriptor->setBands(bands);
      }

      // X pixel size
      if (mpPixelSizeX != NULL)
      {
         pRasterDescriptor->setXPixelSize(*mpPixelSizeX);
      }

      // Y pixel size
      if (mpPixelSizeY != NULL)
      {
         pRasterDescriptor->setYPixelSize(*mpPixelSizeY);
      }

      // Units
      if ((mpUnitsName != NULL) || (mpUnitsType != NULL) ||
         (mpUnitsScale != NULL) || (mpUnitsRangeMin != NULL) || (mpUnitsRangeMax != NULL))
      {
         const Units* pOrigUnits = pRasterDescriptor->getUnits();

         FactoryResource<Units> pUnits;
         VERIFY(pUnits.get() != NULL);

         // Name
         if (mpUnitsName != NULL)
         {
            pUnits->setUnitName(*mpUnitsName);
         }
         else if (pOrigUnits != NULL)
         {
            pUnits->setUnitName(pOrigUnits->getUnitName());
         }

         // Type
         if (mpUnitsType != NULL)
         {
            pUnits->setUnitType(*mpUnitsType);
         }
         else if (pOrigUnits != NULL)
         {
            pUnits->setUnitType(pOrigUnits->getUnitType());
         }

         // Scale
         if (mpUnitsScale != NULL)
         {
            pUnits->setScaleFromStandard(*mpUnitsScale);
         }
         else if (pOrigUnits != NULL)
         {
            pUnits->setScaleFromStandard(pOrigUnits->getScaleFromStandard());
         }

         // Range minimum
         if (mpUnitsRangeMin != NULL)
         {
            pUnits->setRangeMin(*mpUnitsRangeMin);
         }
         else if (pOrigUnits != NULL)
         {
            pUnits->setRangeMin(pOrigUnits->getRangeMin());
         }

         // Range maximum
         if (mpUnitsRangeMax != NULL)
         {
            pUnits->setRangeMax(*mpUnitsRangeMax);
         }
         else if (pOrigUnits != NULL)
         {
            pUnits->setRangeMax(pOrigUnits->getRangeMax());
         }

         pRasterDescriptor->setUnits(pUnits.get());
      }

      // Display mode
      if (mpDisplayMode != NULL)
      {
         pRasterDescriptor->setDisplayMode(*mpDisplayMode);
      }

      // Display bands
      // Gray
      if (mpGrayBand != NULL)
      {
         DimensionDescriptor band = pRasterDescriptor->getOriginalBand(*mpGrayBand - 1);
         pRasterDescriptor->setDisplayBand(GRAY, band);
      }

      // Red
      if (mpRedBand != NULL)
      {
         DimensionDescriptor band = pRasterDescriptor->getOriginalBand(*mpRedBand - 1);
         pRasterDescriptor->setDisplayBand(RED, band);
      }

      // Green
      if (mpGreenBand != NULL)
      {
         DimensionDescriptor band = pRasterDescriptor->getOriginalBand(*mpGreenBand - 1);
         pRasterDescriptor->setDisplayBand(GREEN, band);
      }

      // Blue
      if (mpBlueBand != NULL)
      {
         DimensionDescriptor band = pRasterDescriptor->getOriginalBand(*mpBlueBand - 1);
         pRasterDescriptor->setDisplayBand(BLUE, band);
      }
   }
   else if (pSignatureDescriptor != NULL)
   {
      if (mpComponentName != NULL)
      {
         const Units* pOrigUnits = pSignatureDescriptor->getUnits(*mpComponentName);
         FactoryResource<Units> pUnits;
         if (pOrigUnits != NULL)
         {
            *pUnits = *pOrigUnits;
         }
         if (mpUnitsName != NULL)
         {
            pUnits->setUnitName(*mpUnitsName);
         }
         if (mpUnitsType != NULL)
         {
            pUnits->setUnitType(*mpUnitsType);
         }
         if (mpUnitsScale != NULL)
         {
            pUnits->setScaleFromStandard(*mpUnitsScale);
         }
         if (mpUnitsRangeMin != NULL)
         {
            pUnits->setRangeMin(*mpUnitsRangeMin);
         }
         if (mpUnitsRangeMax != NULL)
         {
            pUnits->setRangeMax(*mpUnitsRangeMax);
         }
         pSignatureDescriptor->setUnits(*mpComponentName, pUnits.get());
      }
   }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return true;
}