コード例 #1
0
void ossimRpfToc::createTocAndCopyFrames( const ossimFilename& dotRpfFile,
                                          const ossimFilename& outputDir )
{
   static const char MODULE[] = "ossimRpfToc::createTocAndCopyFrames";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\ndot rpf file:      " << dotRpfFile
         << "\noutput directory:  " << outputDir
         << "\n";
   }

   if ( outputDir.expand().exists() == false )
   {
      if ( !outputDir.createDirectory(true, 0775) )
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not create directory: ";
         e+= outputDir.c_str();
         throw ossimException(e);
      }
   }

   // Open the dot rpf file.
   std::ifstream* dotRpfStr = new std::ifstream;
   dotRpfStr->open(dotRpfFile, ios_base::in);
   if ( !dotRpfStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotRpfFile.c_str();
      throw ossimException(e);
   }

   ossimFilename sourceADotTocFile = getSourceTocFile(*dotRpfStr);
   if ( sourceADotTocFile.empty() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not deduce source a.toc file!";
      throw ossimException(e);
   }
   
   // Open the source a.toc file. Note the true flag is to keep the file header.
   ossimRefPtr<ossimRpfToc> sourceADotToc = new ossimRpfToc;
   if ( sourceADotToc->parseFile(sourceADotTocFile, true) != ossimErrorCodes::OSSIM_OK )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
 
      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   ossimRefPtr<const ossimNitfFileHeader> sourceNitfFileHdr = sourceADotToc->getNitfFileHeader();
   if ( !sourceNitfFileHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;        

      std::string e = MODULE;
      e += " ERROR:\nCould not get nitf file header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   ossimRefPtr<const ossimRpfHeader> sourceRpfHdr = sourceADotToc->getRpfHeader();
   if ( !sourceRpfHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not get rpf header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the boundary rect sub header from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectSectionSubheader> boundaryRectSectionSubheader =
      sourceRpfHdr->getNewBoundaryRectSectSubheader(sourceADotTocFile);
   if ( !boundaryRectSectionSubheader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }   

   // Get the boundary rect table from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectTable> boundaryRectTable =
      sourceRpfHdr->getNewBoundaryRectTable(sourceADotTocFile);
   if ( !boundaryRectTable.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect table from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Get the frame file subheader from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSectionSubheader> frameFileSubHeader =
      sourceRpfHdr->getNewFrameFileIndexSectionSubheader(sourceADotTocFile);
   if ( !frameFileSubHeader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the frame file subsection from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSubsection> frameFileSubSection =
      sourceRpfHdr->getNewFileIndexSubsection(sourceADotTocFile);
   if ( !frameFileSubSection.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub section from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e); 
   }
   
   // Open the output file to write to.
   const ossimFilename A_DOT_TOC_FILE = "a.toc";
   ossimFilename dotTocFile = outputDir.dirCat(A_DOT_TOC_FILE);
   std::ofstream* dotTocStr = new std::ofstream;
   dotTocStr->open( dotTocFile.c_str(), ios::out|ios::binary );
   if ( !dotTocStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      delete dotTocStr;
      dotTocStr =0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Variables used throughout:
   ossimRefPtr<ossimProperty> prop = new ossimStringProperty();
   ossimString field;
   ossimString s;
   std::streampos fileHeaderLength = 0;
   std::streampos fileLength = 0;
      
   ossimRefPtr<ossimNitfFileHeaderV2_0> fileHdr = new ossimNitfFileHeaderV2_0();
   
   // Set the CLEVEL:
   s = "01";
   fileHdr->setComplexityLevel(s);
   
   // Set the OSTAID:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OSTAID_KW);
   fileHdr->setProperty(prop);
   
   // Set the FDT (date):
   fileHdr->setDate();
   
   // Set the FTITLE:
   s = "a.toc";
   fileHdr->setTitle(s);
   
   // Set the FSCLAS:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCLAS_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCODE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCODE_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCTLH:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCTLH_KW);
   fileHdr->setProperty(prop);
   
   // Set the ONAME:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::ONAME_KW);
   fileHdr->setProperty(prop);
   
   // Set the OPHONE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OPHONE_KW);
   fileHdr->setProperty(prop);
   
   // Add the rpf header.
   ossimRpfHeader* rpfHdr = new ossimRpfHeader( *(sourceRpfHdr.get()) );
   
   ossimRefPtr<ossimNitfRegisteredTag> rpfHdrRp = rpfHdr;
   ossimNitfTagInformation rpfHdrInfo(rpfHdrRp);
   fileHdr->addTag(rpfHdrInfo);
   
   //---
   // Write it out...
   // The first write will be with an rpfheader with no location sections just
   // to see where the end of the file header is.
   //---
   fileHdr->writeStream(*dotTocStr);
   
   //---
   // End of file header. Get the header length. This will also be the
   // start of the location section.
   //---
   std::streampos pos = dotTocStr->tellp();
   std::streamoff locationSectionOffset = pos;
   
   // Set the header length:
   fileHdr->setHeaderLength( static_cast<ossim_uint64>(locationSectionOffset) );
   
   // Set the location of the location section.
   rpfHdr->setLocationSectionPos(locationSectionOffset);

   // Set the file name.
   rpfHdr->setFilename(A_DOT_TOC_FILE);
   
   // Add the component location records to the header.
   ossimRpfLocationSection* locSec = rpfHdr->getLocationSection();
   
   // Clear the records copied from the source a.toc.
   locSec->clearFields();
   
   //---
   // Set the length of the locSec to 74.  The record itself is 14 bytes plus
   // an additional 60 bytes for six location records ten bytes each.
   //---
   const ossim_uint16 LOCATION_SECTION_SIZE = 74;
   locSec->setLocationSectionLength(LOCATION_SECTION_SIZE);
   
   // Set the offset which 14 bytes to get to the first record.
   locSec->setLocationTableOffset(14);
   
   // Six records:
   locSec->setNumberOfComponentLocationRecords(6);
   
   // Each record 10 bytes:
   locSec->setLocationRecordLength(10);
   
   // Don't know the aggregate length yet.
   
   ossimRpfComponentLocationRecord locRec;
   
   // Note: See ossimRpfConstants for enum ossimRpfComponentId
   
   const ossim_uint32 RPFHDR_SIZE = 48;
   const ossim_uint32 LOCATION_SECTION_OFFSET = static_cast<ossim_uint32>(locationSectionOffset);
   const ossim_uint32 BOUNDARY_SUBHEADER_SIZE = 8;
   const ossim_uint32 BOUNDARY_RECORD_SIZE = 132;
   const ossim_uint32 FILE_SUBHEADER_SIZE = 13;
   // const ossim_uint32 = ;
   
   // Record 1 RPFHDR location:
   ossim_uint32 rpfHdrOffset = 0;
   if ( fileHdr->getTag(rpfHdrInfo, "RPFHDR") )
   {
      rpfHdrOffset = rpfHdrInfo.getTagDataOffset();
   }

   locRec.m_componentId = OSSIM_RPF_HEADER_COMPONENT; // 128
   locRec.m_componentLength = RPFHDR_SIZE;
   locRec.m_componentLocation = static_cast<ossim_uint32>(rpfHdrInfo.getTagDataOffset());
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)<< "rpf hdr offset: " << rpfHdrOffset << "\n";
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 2 location section:
   locRec.m_componentId = OSSIM_RPF_LOCATION_COMPONENT; // 129
   locRec.m_componentLength = LOCATION_SECTION_SIZE;
   locRec.m_componentLocation = LOCATION_SECTION_OFFSET;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 3 boundary rect sub header section:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER; // 148
   locRec.m_componentLength = BOUNDARY_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + LOCATION_SECTION_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Capture the location.
   std::streamoff boundaryRectPosition = locRec.m_componentLocation;
   
   // Record 4 boundary rect table:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_TABLE; // 149
   locRec.m_componentLength = BOUNDARY_RECORD_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 5 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER; // 150
   locRec.m_componentLength = FILE_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_RECORD_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
    
   // Record 6 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION; // 151
   locRec.m_componentLength = 0;  // need to calculate.
   locRec.m_componentLocation = locRec.m_componentLocation + FILE_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Seek back and re-write...
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);
   
   dotTocStr->seekp(boundaryRectPosition, ios::beg);

   // Only writing one entry:
   boundaryRectSectionSubheader->setNumberOfEntries(1);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing boundaryRectSectionSubheader:\n" << *(boundaryRectSectionSubheader.get())
         << "\n";
   }

   //---
   // Write the boundary rectangle section.  This includes the subheader and subsection.
   // These coorespond to location records 3 and 4 above.
   //---
   boundaryRectSectionSubheader->writeStream(*dotTocStr);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) 
         << "Original boundaryRectTable:\n" << *(boundaryRectTable.get()) << "\n";
   }

   ossim_uint32 entry;
   if ( getCorespondingEntry( frameFileSubSection.get(), *dotRpfStr, entry ) )
   {
      ossimRpfBoundaryRectRecord boundaryRectRecord;
      if ( boundaryRectTable->getEntry( entry, boundaryRectRecord) )
      {
         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_DEBUG) 
               << "writing boundaryRectTable:\n" << boundaryRectRecord << "\n";
         }
         
         boundaryRectRecord.writeStream(*dotTocStr);
      }
      else
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not get bounding rect record for entry: ";
         e += ossimString::toString(entry).c_str();
         throw ossimException(e);
      }
   }
   else
   {
      std::string e = MODULE;
      e += " ERROR:\nCould not deduce entry from frame list!";
      throw ossimException(e);
   }

   frameFileSubHeader->setNumberOfIndexRecords( getNumberOfFrames(*dotRpfStr) );
   frameFileSubHeader->setNumberOfPathnameRecords(1);
   const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33;
   frameFileSubHeader->setIndexRecordLength( FRAME_FILE_INDEX_RECORD_LENGTH );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing frameFileSubHeader:\n" << *(frameFileSubHeader.get()) << "\n";
   }
   frameFileSubHeader->writeStream( *dotTocStr );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "writing frameFileSubSection:\n";
   }

   std::streamoff frameFileIndexSectionStartPos = dotTocStr->tellp();
   
   writeFrameFileIndexSection(frameFileSubSection.get(), *dotRpfStr, *dotTocStr);
   
   std::streamoff endOfFilePos = dotTocStr->tellp();

   // Update the location section length for the frame file index section.
   locSec->getLocationRecordList()[5].m_componentLength =
      static_cast<ossim_uint32>(endOfFilePos - frameFileIndexSectionStartPos);

   // Update the length of all location sections.
   locSec->setComponentAggregateLength(
      static_cast<ossim_uint32>(endOfFilePos) - rpfHdr->getLocationSectionLocation() );
   

   fileHdr->setFileLength(static_cast<ossim_uint64>(endOfFilePos));
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);

   ossimNotify(ossimNotifyLevel_DEBUG) << "Wrote file: " << dotTocFile << "\n";

   // Copy the frames to the output directory.
   copyFrames(*dotRpfStr, outputDir);

   // Cleanup:
   delete dotRpfStr;
   dotRpfStr = 0;
   delete dotTocStr;
   dotTocStr =0;
}
コード例 #2
0
ファイル: ossimPngReader.cpp プロジェクト: Dukeke/ossim
void ossimPngReader::setMaxPixelValue()
{
   ossim_uint32 band;
   m_maxPixelValue.resize(m_numberOfInputBands);
   for (band = 0; band < m_numberOfInputBands; ++band)
   {
      m_maxPixelValue[band] = 0.0;
   }
   
   if (png_get_valid(m_pngReadPtr, m_pngReadInfoPtr, PNG_INFO_sBIT ))
   {
      png_color_8p sig_bit;
      png_get_sBIT(m_pngReadPtr, m_pngReadInfoPtr, &sig_bit);
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimPngReader::setMaxPixelValue DEBUG:"
            << "\nsig_bit->red:   " << int(sig_bit->red)
            << "\nsig_bit->green: " << int(sig_bit->green)
            << "\nsig_bit->blue:  " << int(sig_bit->blue)
            << "\nsig_bit->gray:  " << int(sig_bit->gray)            
            << "\nsig_bit->alpa:  " << int(sig_bit->alpha)
            << endl;
      }
      switch (m_pngColorType)
      {
         case PNG_COLOR_TYPE_RGB:           /* RGB */
            m_maxPixelValue[0] = pow(2.0, double(sig_bit->red))-1.0;
            m_maxPixelValue[1] = pow(2.0, double(sig_bit->green))-1.0;
            m_maxPixelValue[2] = pow(2.0, double(sig_bit->blue))-1.0;
            break;
         case PNG_COLOR_TYPE_RGB_ALPHA:     /* RGBA */
            m_maxPixelValue[0] = pow(2.0, double(sig_bit->red))-1.0;
            m_maxPixelValue[1] = pow(2.0, double(sig_bit->green))-1.0;
            m_maxPixelValue[2] = pow(2.0, double(sig_bit->blue))-1.0;
            m_maxPixelValue[3] = pow(2.0, double(sig_bit->alpha))-1.0;
            break;
         case PNG_COLOR_TYPE_GRAY:          /* Grayscale */
            m_maxPixelValue[0] = pow(2.0, double(sig_bit->gray))-1.0;
            break;
         case PNG_COLOR_TYPE_GRAY_ALPHA:    /* Grayscale + alpha */            
            m_maxPixelValue[0] = pow(2.0, double(sig_bit->gray))-1.0;
            m_maxPixelValue[1] = pow(2.0, double(sig_bit->alpha))-1.0;
            break;
         case PNG_COLOR_TYPE_PALETTE:       /* Indexed */
            m_maxPixelValue[0] = 255.0;
            m_maxPixelValue[1] = 255.0;
            m_maxPixelValue[2] = 255.0;
            break;
         default:                   /* Aie! Unknown type */
            break;
      }
   }

   // Sanity check.
   for (ossim_uint32 band = 0; band < m_numberOfInputBands; ++band)
   {
      if (m_maxPixelValue[band] == 0.0)
      {
         if (m_bitDepth <= 8)
         {
            m_maxPixelValue[band] = 255.0;
         }
         else
         {
            m_maxPixelValue[band] = 65535.0;
         }
      }
   }
}
コード例 #3
0
ファイル: ossimPngReader.cpp プロジェクト: Dukeke/ossim
void ossimPngReader::restart()
{
   if ( m_str )
   {
      // Destroy the existing memory associated with png structs.
      if (m_pngReadPtr && m_pngReadInfoPtr)
      {
         png_destroy_read_struct(&m_pngReadPtr, &m_pngReadInfoPtr, NULL);
      }

      m_pngReadPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                            NULL,
                                            NULL,
                                            NULL);
      m_pngReadInfoPtr = png_create_info_struct(m_pngReadPtr);

      if ( setjmp( png_jmpbuf(m_pngReadPtr) ) )
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "Error while reading.  File corrupted?  "
            << theImageFile
            << std::endl;
      
         return;
      }

      // Reset the file pointer.
      m_str->seekg( m_restartPosition, std::ios_base::beg );
   
      //---
      // Pass the static read method to libpng to allow us to use our
      // c++ stream instead of doing "png_init_io (pp, ...);" with
      // c stream.
      //---
      png_set_read_fn( m_pngReadPtr,
                       (png_voidp)m_str,
                       (png_rw_ptr)&ossimPngReader::pngReadData );

      //---
      // Note we won't do png_set_sig_bytes(png_ptr, 8) here because we are not
      // rechecking for png signature.
      //---
      png_read_info(m_pngReadPtr, m_pngReadInfoPtr);

      //---
      // If png_set_expand used:
      // Expand data to 24-bit RGB, or 8-bit grayscale,
      // with alpha if available.
      //---
      bool expandFlag = false;

      if ( m_pngColorType == PNG_COLOR_TYPE_PALETTE )
      {
         expandFlag = true;
      }
      if ( (m_pngColorType == PNG_COLOR_TYPE_GRAY) && (m_bitDepth < 8) )
      {
         expandFlag = true;
      }
      if ( png_get_valid(m_pngReadPtr, m_pngReadInfoPtr, PNG_INFO_tRNS) )
      {
         expandFlag = true;
      }

      //---
      // If png_set_packing used:
      // Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
      //---
      bool packingFlag = false;

      if ( (m_bitDepth < 8) && (m_pngColorType == PNG_COLOR_TYPE_GRAY) )
      {
         packingFlag = true;
      }

      if (expandFlag)
      {
         png_set_expand(m_pngReadPtr);
      }
      if (packingFlag)
      {
         png_set_packing(m_pngReadPtr);
      }

      // Gamma correction.
      //    ossim_float64 gamma;
      //    if (png_get_gAMA(m_pngReadPtr, m_pngReadInfoPtr, &gamma))
      //    {
      //       png_set_gamma(m_pngReadPtr, display_exponent, gamma);
      //    }

      //---
      // Turn on interlace handling... libpng returns just 1 (ie single pass)
      //  if the image is not interlaced
      //---
      png_set_interlace_handling (m_pngReadPtr);

      //---
      // Update the info structures after the transformations take effect
      //---
      png_read_update_info (m_pngReadPtr, m_pngReadInfoPtr);
   
      // We're back on row 0 or first line.
      m_currentRow = 0;
   }
}
コード例 #4
0
void ossimTiledElevationDatabase::mapRegion(const ossimGrect& region)
{
   static const char M[] = "ossimTiledElevationDatabase::mapRegion";
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << M << " entered...\n" << "region: " << region << "\n";
   }
   
   if ( m_connectionString.size() )
   {
      // Put these outside the try block so we can delete if exception thrown.
      ossimFileWalker* fw = 0;
      ossimCallback2wRet<const ossimFilename&, bool&, bool>* cb = 0;

      // Wrap in try catch block as excptions can be thrown under the hood.
      try
      {
         m_requestedRect = region;
         
         ossimFilename f = m_connectionString;
         if ( f.exists() )
         {
            // Walk the directory
            fw = new ossimFileWalker();
            fw->initializeDefaultFilterList();
            cb = new ProcessFileCB(this, &ossimTiledElevationDatabase::processFile);
            fw->registerProcessFileCallback(cb);
            fw->walk(f);

            mapRegion();
         }
         else
         {
            ossimNotify(ossimNotifyLevel_WARN)
               << M << " ERROR: Connection string does not exists: "
               << m_connectionString.c_str()  << endl;
         }
      }
      catch (const ossimException& e)
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "Caught exception: " << e.what() << endl;
         m_entries.clear();
      }

      // cleanup:
      if ( fw )
      {
         delete fw;
         fw = 0;
      }
      if ( cb )
      {
         delete cb;
         cb = 0;
      }
   }

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n";
   }
}
コード例 #5
0
void ossimTiledElevationDatabase::mapRegion()
{
   static const char M[] = "ossimTiledElevationDatabase::mapRegion";
   
   if ( m_entries.size() && ( m_requestedRect.isLonLatNan() == false ) )
   {
      ossimRefPtr<ossimOrthoImageMosaic> mosaic = new ossimOrthoImageMosaic();
      std::vector<ossimTiledElevationEntry>::iterator i = m_entries.begin();
      while ( i != m_entries.end() )
      {
         mosaic->connectMyInputTo( (*i).m_sic.get() );
         ++i;
      }

      // Compute the requested rectangle in view space.
      ossimRefPtr<ossimImageGeometry> geom = mosaic->getImageGeometry();
      if ( geom.valid() )
      {
         ossimDpt ulDpt;
         ossimDpt lrDpt;
         geom->worldToLocal(m_requestedRect.ul(), ulDpt);
         geom->worldToLocal(m_requestedRect.lr(), lrDpt);

         // Expand out to fall on even view coordinates.
         ulDpt.x = std::floor(ulDpt.x);
         ulDpt.y = std::floor(ulDpt.y);
         lrDpt.x = std::ceil(lrDpt.x);
         lrDpt.y = std::floor(lrDpt.y);

         // Get new(expanded) corners in ground space.
         ossimGpt ulGpt;
         ossimGpt lrGpt;
         geom->localToWorld(ulDpt, ulGpt);
         geom->localToWorld(lrDpt, lrGpt);
         theGroundRect = ossimGrect(ulGpt, lrGpt);
            
         // Expanded requested rect in view space.
         ossimIpt ulIpt = ulDpt;
         ossimIpt lrIpt = lrDpt;
         const ossimIrect VIEW_RECT(ulIpt, lrIpt);

         // Get the data.
         ossimRefPtr<ossimImageData> data = mosaic->getTile(VIEW_RECT, 0);
         if ( data.valid() )
         {
            // Initialize the grid:
            const ossimIpt SIZE( data->getWidth(), data->getHeight() );
            const ossimDpt ORIGIN(ulGpt.lon, lrGpt.lat); // SouthWest corner
            const ossimDpt SPACING( (lrGpt.lon-ulGpt.lon)/(SIZE.x-1),
                                    (ulGpt.lat-lrGpt.lat)/(SIZE.y-1) );
            if ( !m_grid ) m_grid = new ossimDblGrid();
            m_grid->initialize(SIZE, ORIGIN, SPACING, ossim::nan());

            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG)
                  << M
                  << "\nrequested view rect: " << VIEW_RECT
                  << "\nexpanded ground rect: " << theGroundRect
                  << "\norigin:  " << ORIGIN
                  << "\nsize:    " << SIZE
                  << "\nspacing: " << SPACING << std::endl;
            }

            // Fill the grid:
            switch( data->getScalarType() )
            {
               case OSSIM_SINT16:
               {
                  fillGrid(ossim_sint16(0), data);
                  break;
               }
               case OSSIM_SINT32:
               {
                  fillGrid(ossim_sint32(0), data);
                  break;
               }
               case OSSIM_FLOAT32:
               {
                  fillGrid(ossim_float32(0), data);
                  break;
               }
               case OSSIM_FLOAT64:
               {
                  fillGrid(ossim_float64(0), data);
                  break;
               }
               case OSSIM_UINT8:
               case OSSIM_SINT8:
               case OSSIM_USHORT11:
               case OSSIM_UINT16:
               case OSSIM_UINT32:
               case OSSIM_NORMALIZED_DOUBLE:
               case OSSIM_NORMALIZED_FLOAT:
               case OSSIM_SCALAR_UNKNOWN:
               default:
               {
                  std::string errMsg = M;
                  errMsg += " ERROR:\nUnhandled scalar type: ";
                  errMsg += data->getScalarTypeAsString().string();
                  throw ossimException(errMsg);
               }
            }
            
         } // if ( data.valid() )

      } // if ( geom.valid() )

   } // if ( m_entries.size() && ...
}
コード例 #6
0
bool ossimGeometricSarSensorModel::loadState(const ossimKeywordlist &kwl,
                                             const char *prefix)
{
   static const char MODULE[] = "ossimGeometricSarSensorModel::loadState";

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   bool result = true;

   // Load the base class;
   if ( ossimSensorModel::loadState(kwl, prefix) == false )
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nossimSensorModel::loadState failed!\n";
      }
      result = false;
   }

   // Load the platform position state.
   if ( !_platformPosition)
   {
      _platformPosition = new PlatformPosition();
   }
   if ( _platformPosition->loadState(kwl, prefix) == false )
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\n_platformPosition->loadState failed!\n";
      }
      result = false;
   }

   // Load the sensor position state.
   if ( !_sensor)
   {
      _sensor = new SensorParams();
   }
   if ( _sensor->loadState(kwl, prefix) == false )
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\n_sensor->loadState failed!\n";
      }
      result = false;
   }

   // Load the ref point.
   if ( !_refPoint)
   {
      _refPoint = new RefPoint();
   }
   if ( _refPoint->loadState(kwl, prefix) == false )
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\n_refPoint->loadState failed!\n";
      }
      result = false;
   }

   const char* lookup = 0;
   ossimString s;

   lookup = kwl.find(prefix, PRODUCT_GEOREFERENCED_FLAG_KW);
   if (lookup)
   {
      s = lookup;
      _isProductGeoreferenced = s.toBool();
   }
   else
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nRequired keyword not found: "
            << PRODUCT_GEOREFERENCED_FLAG_KW << "\n";
      }
      result = false;
   }

   lookup = kwl.find(prefix, OPTIMIZATION_FACTOR_X_KW);
   if (lookup)
   {
      s = lookup;
      _optimizationFactorX = s.toDouble();
   }
   else
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nRequired keyword not found: "
            << OPTIMIZATION_FACTOR_X_KW << "\n";
      }
      result = false;
   }

   lookup = kwl.find(prefix, OPTIMIZATION_FACTOR_Y_KW);
   if (lookup)
   {
      s = lookup;
      _optimizationFactorY = s.toDouble();
   }
   else
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nRequired keyword not found: "
            << OPTIMIZATION_FACTOR_Y_KW << "\n";
      }
      result = false;
   }

   lookup = kwl.find(prefix,OPTIMIZATION_BIAS_X_KW);
   if (lookup)
   {
      s = lookup;
      _optimizationBiasX= s.toDouble();
   }
   else
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nRequired keyword not found: "
            << OPTIMIZATION_BIAS_X_KW << "\n";
      }
      result = false;
   }

   lookup = kwl.find(prefix,OPTIMIZATION_BIAS_Y_KW);
   if (lookup)
   {
      s = lookup;
      _optimizationBiasY = s.toDouble();
   }
   else
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << "\nRequired keyword not found: "
            << OPTIMIZATION_BIAS_X_KW << "\n";
      }
      result = false;
   }

   // if (result && traceDebug())
//    if (result)
//    {
//       ossimNotify(ossimNotifyLevel_DEBUG)
//          << "calling saveState to verify loadState..." << endl;

//       ossimKeywordlist kwl2;
//       saveState(kwl2, 0);

//       ossimNotify(ossimNotifyLevel_DEBUG)
//          << "saveState result after loadState:"  << kwl2 << endl;
//    }

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exit status = " << (result?"true":"false\n")
         << std::endl;
   }

   return result;
}
コード例 #7
0
void ossimImageMpiSWriterSequenceConnection::slaveProcessTiles()
{
#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
    ossimEndian endian;
    ossim_uint32 numberOfTiles    = getNumberOfTiles();
    long currentSendRequest = 0;
    long numberOfTilesSent  = 0;
    int errorValue= 0;
    MPI_Request *requests   = new MPI_Request[theNumberOfTilesToBuffer];
    for (int i = 0; i < theNumberOfTilesToBuffer; ++i)
    {
        requests[i] = MPI_REQUEST_NULL;
    }

    if(traceDebug())
    {
        ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): entering slave and will look at " << numberOfTiles << " tiles" << std::endl;
    }
    while(theCurrentTileNumber < numberOfTiles)
    {
        ossimRefPtr<ossimImageData> data = ossimImageSourceSequencer::getTile(theCurrentTileNumber);

        // if the current send requests have looped around
        // make sure we wait to see if it was sent
        //
        errorValue = MPI_Wait(&requests[currentSendRequest], MPI_STATUS_IGNORE);
        requests[currentSendRequest] = MPI_REQUEST_NULL;
        if(data.valid() &&
                (data->getDataObjectStatus()!=OSSIM_NULL)&&
                (data->getDataObjectStatus()!=OSSIM_EMPTY))
        {
            theOutputTile[currentSendRequest]->setImageRectangle(data->getImageRectangle());
            theOutputTile[currentSendRequest]->initialize();

            theOutputTile[currentSendRequest]->loadTile(data.get());
            theOutputTile[currentSendRequest]->setDataObjectStatus(data->getDataObjectStatus());

            if(traceDebug())
            {
                if(data->getDataObjectStatus() == OSSIM_EMPTY)
                {
                    ossimNotify(ossimNotifyLevel_DEBUG)
                            << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In salve = "
                            << theRank << " tile is empty" << std::endl;
                }
            }
        }
        else
        {
            if(traceDebug())
            {
                if(!data)
                {
                    ossimNotify(ossimNotifyLevel_DEBUG)
                            << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In slave = "
                            << theRank << " ptr is null " << std::endl;
                }
                else
                {
                    ossimNotify(ossimNotifyLevel_DEBUG)
                            << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In slave = " << theRank << " tile is empty" << std::endl;
                }
            }
            theOutputTile[currentSendRequest]->makeBlank();
        }

        void* buf = theOutputTile[currentSendRequest]->getBuf();
        if((endian.getSystemEndianType()!=OSSIM_BIG_ENDIAN)&&
                (theOutputTile[currentSendRequest]->getScalarType()!=OSSIM_UINT8))
        {
            endian.swap(theOutputTile[currentSendRequest]->getScalarType(),
                        buf,
                        theOutputTile[currentSendRequest]->getSize());
        }
        errorValue = MPI_Isend(buf,
                               theOutputTile[currentSendRequest]->getSizeInBytes(),
                               MPI_UNSIGNED_CHAR,
                               0,
                               0,
                               MPI_COMM_WORLD,
                               &requests[currentSendRequest]);
#if 0
        switch(theOutputTile[currentSendRequest]->getScalarType())
        {
        case OSSIM_UINT8:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_UNSIGNED_CHAR,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_SINT8:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_CHAR,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_UINT16:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_UNSIGNED_SHORT,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_SINT16:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_SHORT,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_UINT32:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_UNSIGNED_LONG,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_SINT32:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_LONG,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_FLOAT32:
        case OSSIM_NORMALIZED_FLOAT:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_FLOAT,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        case OSSIM_FLOAT64:
        case OSSIM_NORMALIZED_DOUBLE:
        {
            errorValue = MPI_Isend(buf,
                                   theOutputTile[currentSendRequest]->getSize(),
                                   MPI_DOUBLE,
                                   0,
                                   0,
                                   MPI_COMM_WORLD,
                                   &requests[currentSendRequest]);
            break;
        }
        default:
            break;
        }
#endif
        theCurrentTileNumber += (theNumberOfProcessors-1);
        numberOfTilesSent++;
        currentSendRequest++;
        currentSendRequest %= theNumberOfTilesToBuffer;
    }
    ossim_int32 tempCount = 0;
    // must wait in the correct order
    //
    while(tempCount < theNumberOfTilesToBuffer)
    {
        currentSendRequest++;
        currentSendRequest %= theNumberOfTilesToBuffer;

        errorValue = MPI_Wait(&requests[currentSendRequest], MPI_STATUS_IGNORE);
        ++tempCount;
    }

//   MPI_Waitall(theNumberOfTilesToBuffer,
//               requests,
//               MPI_STATUS_IGNORE);

    delete [] requests;
#  endif
#endif
}
コード例 #8
0
ファイル: ossimGpkgUtil.cpp プロジェクト: bradh/ossim-plugins
bool ossim_gpkg::getTableRows(
   sqlite3* db,
   const std::string& tableName,
   std::vector< ossimRefPtr<ossimGpkgDatabaseRecordBase> >& result )
{
   static const char M[] = "ossim_gpkg::getTableRows";

   bool status = false;
   
   if ( db && tableName.size() )
   {
      const char *zLeftover;      /* Tail of unprocessed SQL */
      sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
      std::string sql = "SELECT * from ";
      sql += tableName;

      int rc = sqlite3_prepare_v2(db,           // Database handle
                                  sql.c_str(),  // SQL statement, UTF-8 encoded
                                  -1,           // Maximum length of zSql in bytes.
                                  &pStmt,       // OUT: Statement handle
                                  &zLeftover);  // OUT: Pointer to unused portion of zSql
      if ( rc == SQLITE_OK )
      {
         bool initStatus = true;
         
         int nCol = sqlite3_column_count( pStmt );
         if ( nCol )
         {
            while( 1 )
            {
               // Read the row:
               rc = sqlite3_step(pStmt);
               if ( rc == SQLITE_ROW )
               {
                  ossimRefPtr<ossimGpkgDatabaseRecordBase> row = getNewTableRecord( tableName );
                  if ( row.valid() )
                  {
                     if ( row->init( pStmt ) )
                     {
                        result.push_back(row);
                     }
                     else
                     {
                        ossimNotify(ossimNotifyLevel_WARN)
                           << M << " init failed!" << std::endl;
                        initStatus = false;
                        break;
                     }
                  }
                  else
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << M << " could not make object for table name: " << tableName
                        << std::endl;
                     initStatus = false;
                     break; 
                  }
               }
               else
               {
                  break;
               }
            }
         }
         if ( initStatus && result.size() )
         {
            status = true;
         }  
      }
      sqlite3_finalize(pStmt);
   }
   
   return status;
   
} // End: ossim_gpks::getTableRows(...)
コード例 #9
0
ファイル: ossimGpkgUtil.cpp プロジェクト: bradh/ossim-plugins
void ossim_gpkg::getTileEntries( sqlite3* db, std::vector<ossimGpkgTileEntry>& entries )
{
   if ( db )
   {
      // Get all the tile matrix sets.  Each set can be concidered an entry.
      
      std::vector<ossimGpkgTileMatrixSetRecord> sets;
      ossim_gpkg::getGpkgRecords(
         db, sets, ossimGpkgTileMatrixSetRecord::getTableName() );

      if ( sets.size() )
      {
         // Get all the tile matrix rows.
         std::vector<ossimGpkgTileMatrixRecord> levels;
         ossim_gpkg::getGpkgRecords(
            db, levels, ossimGpkgTileMatrixRecord::getTableName() );

          // Get all the nsg tile matrix extent rows.
         std::vector<ossimGpkgNsgTileMatrixExtentRecord> extents;
         ossim_gpkg::getGpkgRecords(
            db, extents, ossimGpkgNsgTileMatrixExtentRecord::getTableName() );

         // Get all the srs rows.
         std::vector<ossimGpkgSpatialRefSysRecord> srs;
         ossim_gpkg::getGpkgRecords(
            db, srs, ossimGpkgSpatialRefSysRecord::getTableName() );

         // For each entry captue the tile matrix and srs that belong to entry.
         std::vector<ossimGpkgTileMatrixSetRecord>::const_iterator setIdx = sets.begin();
         while ( setIdx != sets.end() )
         {
            ossimGpkgTileEntry entry;
            entry.setTileMatrixSet(*setIdx);

            // Add tile matrix objects to entry if table_name matches.
            std::vector<ossimGpkgTileMatrixRecord>::const_iterator mIdx = levels.begin();
            while ( mIdx != levels.end() )
            {
               if ( entry.getTileMatrixSet().m_table_name == (*mIdx).m_table_name )
               {
                  // table_name matches...
                  entry.addTileMatrix( (*mIdx) );
               }
               ++mIdx;
            }

            // Add tile matrix extent objects to entry if table_name matches.
            std::vector<ossimGpkgNsgTileMatrixExtentRecord>::const_iterator extIdx = extents.begin();
            while ( extIdx != extents.end() )
            {
               if ( entry.getTileMatrixSet().m_table_name == (*extIdx).m_table_name )
               {
                  // table_name matches...
                  entry.addTileMatrixExtent( (*extIdx) );
               }
               ++extIdx;
            }

            std::vector<ossimGpkgSpatialRefSysRecord>::const_iterator srsIdx = srs.begin();
            while ( srsIdx != srs.end() )
            {
               if (entry.getTileMatrixSet().m_srs_id == (*srsIdx).m_srs_id)
               {
                  // srs id matches...
                  entry.setSrs( (*srsIdx) );
                  break;
               }
               ++srsIdx;
            }

            if ( entry.getTileMatrix().size() )
            {
               // The sort call puts the tile matrix entries in highest zoom to lowest order.
               entry.sortTileMatrix();
               entry.sortTileMatrixExtents();
               
               // Add the entry
               entries.push_back( entry );
            }
            else
            {
               ossimNotify(ossimNotifyLevel_WARN)
                  << "ossim_gpkg::getTileEntries WARNING No levels found for entry!"
                  << std::endl;
            }

            ++setIdx; // Next entry.
         }
      } 
      
   } // Matches: if ( sqlite3* db )
   
} // End: ossim_gpkg::getTileEntries( ... )
コード例 #10
0
bool ossimNitfFile::parseFile(const ossimFilename& file)
{
    if (traceDebug())
    {
        ossimNotify(ossimNotifyLevel_DEBUG)
                << "DEBUG ossimNitfFile::parseFile: "
                << "endtered......"
                << std::endl;
    }
    std::ifstream in(file.c_str(), std::ios::in|std::ios::binary);
    if (in.fail())
    {
        if (traceDebug())
        {
            ossimNotify(ossimNotifyLevel_DEBUG)
                    << "DEBUG ossimNitfFile::parseFile: "
                    << "Could not open file:  " << file.c_str()
                    << "\nReturning..." << std::endl;
        }
        return false;
    }

    if(theNitfFileHeader.valid())
    {
        theNitfFileHeader = 0;
    }

    char temp[10];
    in.read(temp, 9);
    in.seekg(0, std::ios::beg);
    temp[9] ='\0';

    theFilename = file;

    ossimString s(temp);
    if(s == "NITF02.00")
    {
        if(traceDebug())
        {
            ossimNotify(ossimNotifyLevel_DEBUG)
                    << "DEBUG: NITF Version 2.0"
                    << std::endl;
        }
        theNitfFileHeader = new ossimNitfFileHeaderV2_0;
    }
    else if ( (s == "NITF02.10") || (s == "NSIF01.00") )
    {
        if(traceDebug())
        {
            ossimNotify(ossimNotifyLevel_DEBUG)
                    << "DEBUG: NITF Version 2.1"
                    << std::endl;
        }
        theNitfFileHeader = new ossimNitfFileHeaderV2_1;
    }
    else
    {
        if (traceDebug())
        {
            ossimNotify(ossimNotifyLevel_DEBUG)
                    << "DEBUG ossimNitfFile::parseFile: "
                    << "Not an NITF file!"
                    << std::endl;
            ossimNotify(ossimNotifyLevel_DEBUG)
                    << "DEBUG ossimNitfFile::parseFile: returning...........false"
                    << "endtered......"
                    << std::endl;
        }
        return false;
    }

    if(theNitfFileHeader.valid())
    {
        try
        {
            theNitfFileHeader->parseStream(in);
        }
        catch(std::exception& e)
        {
            if (traceDebug())
            {
                ossimNotify(ossimNotifyLevel_WARN)
                        << "ossimNitfFile::parseFile caught exception:\n"
                        << e.what()
                        << std::endl;
            }
            return false;
        }
    }

    if (traceDebug())
    {
        ossimNotify(ossimNotifyLevel_DEBUG)
                << "DEBUG ossimNitfFile::parseFile: returning...........true"
                << std::endl;
    }
    return true;
}
コード例 #11
0
ファイル: ossimGpkgUtil.cpp プロジェクト: bradh/ossim-plugins
bool ossim_gpkg::getTileEntry( sqlite3* db,
                               const std::string& tileTableName,
                               ossimGpkgTileEntry& entry )
{
   bool status = false;
   
   if ( db )
   {
      // Get all the tile matrix set for the tile table name.
      ossimGpkgTileMatrixSetRecord set;
      if ( ossim_gpkg::getGpkgRecord(
              db, set, ossimGpkgTileMatrixSetRecord::getTableName(), tileTableName ) )
      {
         entry.setTileMatrixSet( set );

         // Get all the tile matrix rows.  There's one for each level.
         std::vector<ossimGpkgTileMatrixRecord> levels;
         ossim_gpkg::getGpkgRecords(
            db, levels, ossimGpkgTileMatrixRecord::getTableName(), tileTableName );

         if ( levels.size() )
         {
            // Add tile matrix objects to entry if table_name matches.
            std::vector<ossimGpkgTileMatrixRecord>::const_iterator mIdx = levels.begin();
            while ( mIdx != levels.end() )
            {
               entry.addTileMatrix( (*mIdx) );
               ++mIdx;
            }
            
            // Get the GpkgSpatialRefSys.  Required or we don't go on.
            ossimGpkgSpatialRefSysRecord srs;
            if ( ossim_gpkg::getSrsRecord(
                    db,
                    set.m_srs_id,
                    srs ) )
            {
               entry.setSrs( srs );

               //---
               // At this point we can set the status to true.  The below nsg
               // tile matrix extent is not required.
               //---
               status = true;

               // Add tile matrix extent objects to entry if table_name matches.

               // Get all the nsg tile matrix extent rows.
               std::vector<ossimGpkgNsgTileMatrixExtentRecord> extents;
               ossim_gpkg::getGpkgRecords(
                  db,
                  extents,
                  ossimGpkgNsgTileMatrixExtentRecord::getTableName(),
                  tileTableName );
               std::vector<ossimGpkgNsgTileMatrixExtentRecord>::const_iterator extIdx =
                  extents.begin();
               while ( extIdx != extents.end() )
               {
                  if ( entry.getTileMatrixSet().m_table_name == (*extIdx).m_table_name )
                  {
                     // table_name matches...
                     entry.addTileMatrixExtent( (*extIdx) );
                  }
                  ++extIdx;
               }

               if ( entry.getTileMatrix().size() )
               {
                  // The sort call puts the tile matrix entries in highest zoom to lowest order.
                  entry.sortTileMatrix();
               }
               if ( entry.getTileMatrixExtent().size() )
               {
                  // The sort call puts the tile matrix entries in highest zoom to lowest order.
                  entry.sortTileMatrixExtents();

                  // If we have extents, the size should match the tile matrix size.
                  if ( entry.getTileMatrixExtent().size() != entry.getTileMatrix().size() )
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "ossim_gpkg::getTileEntry WARNING size mismatch between tile matrix"
                        << " and tile matrix extents!\n";
                  }
               }
            }
            else
            {
               ossimNotify(ossimNotifyLevel_WARN)
                  << "ossim_gpkg::getTileEntry WARNING No gpkg_spatial_ref_sys record found for"
                  << " entry!\n";
            }
         }
         else
         {
            ossimNotify(ossimNotifyLevel_WARN)
               << "ossim_gpkg::getTileEntry WARNING No gpkg_tile_matrix records found for entry!"
               << std::endl;
         }
      } 
      
   } // Matches: if ( sqlite3* db )

   return status;
   
} // End: ossim_gpkg::getTileEntry( ... )
コード例 #12
0
void ossimRpfToc::writeFrameFileIndexSection(ossimRpfFrameFileIndexSubsection* frameFileSubSection,
                                             std::ifstream& dotRpfStr,
                                             std::ofstream& dotTocStr)
{
   static const char MODULE[] = "ossimRpfToc::writeFrameFileIndexSection";

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33;
   ossim_uint32 frames = getNumberOfFrames(dotRpfStr);
   ossim_uint32 pathnameRecordOffset = FRAME_FILE_INDEX_RECORD_LENGTH * frames;

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "frames: " << frames << "\n";
   }
   
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }

   dotRpfStr.seekg(0, ios_base::beg);

   std::string line;
   ossimFilename file;
   ossimRpfFrameFileIndexRecord record;
   ossim_uint32 framesWritten = 0;

   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);

   while( dotRpfStr.good() )
   {
      std::getline(dotRpfStr, line);

      if ( dotRpfStr.good() )
      {
         if ( getFile(line, file) )
         {
            if ( frameFileSubSection->getFrameFileIndexRecordFromFile(file.file(), record) )
            {
               // Always single entry.
               record.setBoundaryRecNumber(0);
               
               record.setPathnameRecordOffset(pathnameRecordOffset);
               record.writeStream(dotTocStr);
               ++framesWritten;

               if ( traceDebug() )
               {
                  ossimNotify(ossimNotifyLevel_DEBUG) << "wrote record:\n" << record << "\n";
               }
            }
         }
      }
   }

   // Now set the path record.
   ossimFilename d = file.path();
   ossimString s = "./";
   s += d.file();
   s += "/";
   ossimRpfPathnameRecord pathRecord;
   pathRecord.setPathName(s);
   pathRecord.writeStream(dotTocStr);

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "frames written: " << framesWritten
         << "\nwrote record:\n" << pathRecord
         << "\n";
   }

   dotRpfStr.clear();
   dotRpfStr.seekg(0, ios_base::beg);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl;
   }
}
コード例 #13
0
void ossimRpfToc::buildTocEntryList(ossimRpfHeader* rpfHeader)
{
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimRpfToc::buildTocEntryList: entered.....\n";
   }
   std::ifstream in(m_filename.c_str(), std::ios::in | std::ios::binary);

   if(!in)
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimRpfToc::buildTocEntryList: invalid input leaving..... " << std::endl;
      }
      return;
   }
   
   if(rpfHeader)
   {
      if(traceDebug())
      {
         rpfHeader->print(ossimNotify(ossimNotifyLevel_DEBUG));
      }
      
      deleteTocEntryList();
      ossimRpfBoundaryRectSectionSubheader *boundaryRect =
         rpfHeader->getNewBoundaryRectSectSubheader(in);

      if(boundaryRect)
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Got boundary rect\n";
         }
         std::streamoff current = in.tellg();

         // they give the offset from the
         // end of the boundary subheader to the start of the 
         // entry table.  We have to create an absolute
         // offset.
         current += boundaryRect->getTableOffset();

         // take to the start of the table entries
         in.seekg(current, ios::beg);
         allocateTocEntryList(boundaryRect->getNumberOfEntries());

         // now we can read the entries
         if(m_tocEntryList.size() > 0)
         {
            for(ossim_uint32 index = 0; index < m_tocEntryList.size(); index++)
            {
               m_tocEntryList[index]->parseStream(in, rpfHeader->getByteOrder());
            }
         }
         
         ossimRpfFrameFileIndexSectionSubheader* frameFileIndexHead = rpfHeader->getNewFrameFileIndexSectionSubheader(in);
         // get the offset to the table
         long offsetToIndexSubsection = in.tellg();
         if(frameFileIndexHead)
         {
            ossimRpfFrameFileIndexRecord tempIndexRec;
            ossimRpfPathnameRecord       tempPathNameRec;
            
            ossim_int32 count = frameFileIndexHead->getNumberOfIndexRecords();
            while(count > 0)
            {
               tempIndexRec.parseStream(in, rpfHeader->getByteOrder() );

               // get the path information.  we must seek to a different location
               // within the file.  So we must remember where we currently are at
               std::streamoff currentPosition = in.tellg();
               
               in.seekg(offsetToIndexSubsection + tempIndexRec.getPathnameRecordOffset(), ios::beg);
               tempPathNameRec.parseStream(in, rpfHeader->getByteOrder());

               // We have the root directory where all frame files are subfiles of
//               ossimString rootDirectory(ossimFilename(m_filename.path())+
               // ossimFilename(ossimFilename::thePathSeparator));
               ossimFilename rootDirectory;
               getRootDirectory(rootDirectory);

               // we have the actual path from the root directory to the
               // frame file.  We must separate the two.  There have been
               // occurrences where the path in the A.TOC file
               // is upper case but the path in the directory on the file
               // system is lower case.  This
               // will fool the system in thinking the file does not exist
               // when it actually does.
               ossimString pathToFrameFile( ossimFilename(tempPathNameRec.getPathname()) +
                                              tempIndexRec.getFilename());

               ossimRpfFrameEntry entry(rootDirectory,
                                        pathToFrameFile);
               m_tocEntryList[tempIndexRec.getBoundaryRecNumber()]->setEntry(entry,
                                                                              tempIndexRec.getLocationRowNumber(),
                                                                              tempIndexRec.getLocationColNumber());
               // now go back to where we were
               in.seekg(currentPosition, ios::beg);
               
               --count;
            }
            delete frameFileIndexHead;
            frameFileIndexHead = 0;
         }
      }
      delete boundaryRect;
      boundaryRect = NULL;
   }
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimRpfToc::buildTocEntryList: leaving....." << std::endl;
   }
}
コード例 #14
0
ossimErrorCode ossimRpfToc::parseFile(const ossimFilename &fileName, bool keepFileHeader)
{
   static const char MODULE[] = "ossimRpfToc::parseFile";
   
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered....." << std::endl;
   }

   ossimRefPtr<ossimNitfFile> nitfFile = new ossimNitfFile;

   clearAll();

   nitfFile->parseFile(fileName);

   m_nitfFileHeader = nitfFile->getHeader();

   m_rpfHeader = 0; // ossimRefPtr
   
   if( !m_nitfFileHeader.valid() )
   {
      nitfFile = 0;
      
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << MODULE << " leaving with no nitf header found....." << std::endl;
      }
      return ossimErrorCodes::OSSIM_ERROR;
   }
   
   ossimNitfTagInformation info; 
   m_nitfFileHeader->getTag(info, "RPFHDR");

   if(traceDebug() && (info.getTagName() == "RPFHDR") )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " nitf file header print\n";
      m_nitfFileHeader->print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   if ( !keepFileHeader )
   {
      // we no longer need access to the nitf header.  We got what we needed.
      m_nitfFileHeader = 0;
   }
   nitfFile = 0;
   
   m_filename = fileName;

   if(info.getTagName() == "RPFHDR")
   {
      m_rpfHeader = new ossimRpfHeader;

      std::ifstream in(m_filename.c_str(), std::ios::in|std::ios::binary);
      
      // set the get pointer for the stream to the start
      // of the Rpf header data
      in.seekg(info.getTagDataOffset(), std::ios::beg);
      
      // now get the header data.  We do not need to pass in the byte order.
      // this is grabbed from the first byte of the stream.  To see this,
      // Look at the RpfHeader implementation.
      m_rpfHeader->parseStream(in);

      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << MODULE << " DEBUG: Found RPF HEADER tag\n";
         m_rpfHeader->print( ossimNotify(ossimNotifyLevel_DEBUG) );
      }

   }
   else
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimRpfToc::parseFile: Leaving No RPFHDR tag found" << "\n";
      }
      return ossimErrorCodes::OSSIM_ERROR;
   }
   
   if( m_rpfHeader.valid() )
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Building toc list" << "\n";
      }
      buildTocEntryList( m_rpfHeader.get() );
   }
   else
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimRpfToc::parseFile: Leaving no RPFHDR " << __LINE__ << "\n";
      }
      return ossimErrorCodes::OSSIM_ERROR;
   }
   
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimRpfToc::parseFile: Returning with OK." << std::endl;
   }
   
   return ossimErrorCodes::OSSIM_OK;
}
コード例 #15
0
int
ossimDDFSubfieldDefn::ExtractIntData( const char * pachSourceData,
                                 int nMaxBytes, int * pnConsumedBytes )

{
    switch( pszFormatString[0] )
    {
      case 'A':
      case 'I':
      case 'R':
      case 'S':
      case 'C':
        return atoi(ExtractStringData(pachSourceData, nMaxBytes,
                                      pnConsumedBytes));

      case 'B':
      case 'b':
      {
          unsigned char   abyData[8];

          if( nFormatWidth > nMaxBytes )
          {
              ossimNotify(ossimNotifyLevel_WARN)
                 << "Attempt to extract int subfield %s with format %s\n"
                 << "failed as only %d bytes available.  Using zero."
                 << pszName << pszFormatString << nMaxBytes << std::endl;
              return 0;
          }

          if( pnConsumedBytes != NULL )
              *pnConsumedBytes = nFormatWidth;

          // Byte swap the data if it isn't in machine native format.
          // In any event we copy it into our buffer to ensure it is
          // word aligned.
#ifdef CPL_LSB
          if( pszFormatString[0] == 'B' )
#else            
              if( pszFormatString[0] == 'b' )
#endif            
              {
                  for( int i = 0; i < nFormatWidth; i++ )
                      abyData[nFormatWidth-i-1] = pachSourceData[i];
              }
              else
              {
                  memcpy( abyData, pachSourceData, nFormatWidth );
              }

          // Interpret the bytes of data.
          switch( eBinaryFormat )
          {
            case UInt:
              if( nFormatWidth == 4 )
              {
                 ossim_uint32* ptr = (ossim_uint32*) abyData;
                 return *ptr;
              }
              else if( nFormatWidth == 1 )
              {
                 return( abyData[0] );
              }
              else if( nFormatWidth == 2 )
              {
                 ossim_uint16* ptr = (ossim_uint16*)abyData;
                 return *ptr;
              }
              else
              {
                 // CPLAssert( false );
                 return 0;
              }
              
             case SInt:
                if( nFormatWidth == 4 )
                {
                   ossim_int32* ptr = (ossim_int32 *) abyData;
                   return *ptr;
                }
                else if( nFormatWidth == 1 )
                {
                   signed char* ptr = (signed char *) abyData;
                   return *ptr;
                }
                else if( nFormatWidth == 2 )
                {
                   ossim_int16* ptr = (ossim_int16 *) abyData;
                   return *ptr;
                }
                else
                {
                   // CPLAssert( false );
                   return 0;
                }
                
             case FloatReal:
                if( nFormatWidth == 4 )
                {
                   float* ptr = (float *) abyData;
                   return (int) *ptr;
                }
                else if( nFormatWidth == 8 )
                {
                   double* ptr = (double *) abyData;
                   return (int) *ptr;
                }
                else
                {
                   // CPLAssert( false );
                   return 0;
                }

             case NotBinary:            
             case FPReal:
             case FloatComplex:
                // CPLAssert( false );
                return 0;
          }
          break;
          // end of 'b'/'B' case.
      }
      
       default:
          // CPLAssert( false );
          return 0;
    }
    
    // CPLAssert( false );
    return 0;
}
コード例 #16
0
bool ossimHdfReader::open()
{
   static const char MODULE[] = "ossimHdfReader::open";

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered...\n"
         << "image: " << theImageFile << "\n";
   }

   bool result = false;

   if (!isSupportedExtension())
   {
      return false;
   }

   if (m_entryFileList.size() == 0)
   {
      if(isOpen())
      {
         close();
      }

      m_gdalTileSource = new ossimGdalTileSource;
      m_gdalTileSource->setFilename(theImageFile);

      if ( m_gdalTileSource->open() == false )
      {
         m_gdalTileSource = 0;
         return false;
      }

      std::vector<ossimString> entryStringList;
      if (m_gdalTileSource != 0)
      {
         m_gdalTileSource->getEntryNames(entryStringList);
      }
      
      // bool isSwathImage = false;
      if (entryStringList.size() > 0)
      {
         for (ossim_uint32 i = 0; i < entryStringList.size(); i++)
         {
            m_entryFileList.push_back(i);
         }
      }
      else
      {
        result = false;
      }
   }
      
   //set entry id for the gdal tile source
   if (m_currentEntryRender < m_entryFileList.size())
   {
      
      m_gdalTileSource->setCurrentEntry(m_currentEntryRender);
      m_numberOfBands = m_gdalTileSource->getNumberOfInputBands();

      m_tile = ossimImageDataFactory::instance()->create(this, this);
      m_tile->initialize();
      
      completeOpen();
      result = true;
   }
   else
   {
      result = false;
   }
   
   if (result == false)
   {
      close();
   }
   
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exit status = " << (result?"true":"false\n")
         << std::endl;
   }
   
   return result;
}
コード例 #17
0
int ossimDDFSubfieldDefn::SetFormat( const char * pszFormat )

{
    free( pszFormatString );
    pszFormatString = strdup( pszFormat );

/* -------------------------------------------------------------------- */
/*      These values will likely be used.                               */
/* -------------------------------------------------------------------- */
    if( pszFormatString[1] == '(' )
    {
        nFormatWidth = atoi(pszFormatString+2);
        bIsVariable = nFormatWidth == 0;
    }
    else
        bIsVariable = true;
    
/* -------------------------------------------------------------------- */
/*      Interpret the format string.                                    */
/* -------------------------------------------------------------------- */
    switch( pszFormatString[0] )
    {
      case 'A':
      case 'C':         // It isn't clear to me how this is different than 'A'
        eType = DDFString;
        break;

      case 'R':
        eType = DDFFloat;
        break;
        
      case 'I':
      case 'S':
        eType = DDFInt;
        break;

      case 'B':
      case 'b':
        // Is the width expressed in bits? (is it a bitstring)
        bIsVariable = false;
        if( pszFormatString[1] == '(' )
        {
           // CPLAssert( atoi(pszFormatString+2) % 8 == 0 );
            
            nFormatWidth = atoi(pszFormatString+2) / 8;
            eBinaryFormat = SInt; // good default, works for SDTS.

            if( nFormatWidth < 5 )
                eType = DDFInt;
            else
                eType = DDFBinaryString;
        }
        
        // or do we have a binary type indicator? (is it binary)
        else
        {
            eBinaryFormat = (DDFBinaryFormat) (pszFormatString[1] - '0');
            nFormatWidth = atoi(pszFormatString+2);

            if( eBinaryFormat == SInt || eBinaryFormat == UInt )
                eType = DDFInt;
            else
                eType = DDFFloat;
        }
        break;

      case 'X':
        // 'X' is extra space, and shouldn't be directly assigned to a
        // subfield ... I haven't encountered it in use yet though.
        ossimNotify(ossimNotifyLevel_WARN)
           << "Format type of `%c' not supported.\n"
           << pszFormatString[0] << std::endl;
        
        // CPLAssert( false );
        return false;
        
      default:
        ossimNotify(ossimNotifyLevel_WARN)
           << "Format type of `%c' not recognised.\n"
           << pszFormatString[0] << std::endl;
        
        // CPLAssert( false );
        return false;
    }
    
    return true;
}
コード例 #18
0
bool ossimNdfTileSource::open()
{
   // Ensure header file exists
   if(!theHeaderFile.exists())
   {
      theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
      if ( traceDebug() )
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "ERROR: Missing Header File ("
            << theHeaderFile << ")" << std::endl;
      }
      return false;
   }

   try
   {
      // Validate Header to ensure we support this data type
      ossimNdfHeader lnh(theHeaderFile);
      if(lnh.getErrorStatus())
      {
         theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
         return false;
      }

      // Use General Raster classes to build NLAPS imagery
      ossimGeneralRasterInfo generalRasterInfo;
      if(lnh.getNumOfBands() == 1)
      {
         generalRasterInfo = ossimGeneralRasterInfo(lnh.getImageFileList(),
                                                    OSSIM_UINT8,
                                                    OSSIM_BSQ,
                                                    lnh.getNumOfBands(),
                                                    lnh.getLines(),
                                                    lnh.getSamples(),
                                                    0,
                                                    ossimGeneralRasterInfo::NONE,
                                                    0);
      }
      else
      {
         generalRasterInfo = ossimGeneralRasterInfo(lnh.getImageFileList(),
                                                    OSSIM_UINT8,
                                                    OSSIM_BSQ_MULTI_FILE,
                                                    lnh.getNumOfBands(),
                                                    lnh.getLines(),
                                                    lnh.getSamples(),
                                                    0,
                                                    ossimGeneralRasterInfo::NONE,
                                                    0);
      }
      
      theMetaData.clear();
      theMetaData.setScalarType(OSSIM_UINT8);
      theMetaData.setNumberOfBands(lnh.getNumOfBands());
      m_rasterInfo = generalRasterInfo;
      
      if(initializeHandler())
      {
         completeOpen();
      }
      else
      {
         theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
         return false;
      }  
   }
   catch (const ossimException& e)
   {
      if ( traceDebug() )
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "ossimNdfTileSource::open caught exception:\n"
            << e.what() << std::endl;
      }
      return false;
   }
   
   return true;
}
コード例 #19
0
ファイル: ossim-icp.cpp プロジェクト: whztt07/star_ossim
int main(int argc, char* argv[])
{
    static const char MODULE[] = "icp:main";
    std::string tempString;
    ossimArgumentParser::ossimParameter stringParam(tempString);

    ossimArgumentParser ap(&argc, argv);
    ossimInit::instance()->addOptions(ap);
    ossimInit::instance()->initialize(ap);

    ossimApplicationUsage* au = ap.getApplicationUsage();

    au->setApplicationName(ap.getApplicationName());
    au->setDescription(ap.getApplicationName()+
                       " copies any supported input image format to any supported output image format format");
    au->setCommandLineUsage(ap.getApplicationName()+
                            " [options] <output_type> <input_file> <output_file>");
    au->addCommandLineOption("-h or --help",
                             "Display this information");
    au->addCommandLineOption("-a or --use-scalar-remapper",
                             "Uses scalar remapper, transforms to 8-bit");
    au->addCommandLineOption("-o or --create-overview",
                             "Creates and overview for the output image");
    au->addCommandLineOption("-b or --bands <n,n...>",
                             "uses the specified bands: ex. \"1, 2, 4\" will select bands 1 2 and 4 of the input image.  "
                             "Note: it is 1 based");
    au->addCommandLineOption("-c or --compression-type <type>",
                             "Uses compression.  Currently valid for only tiff output -c jpeg will use jpeg compression");
    au->addCommandLineOption("-e or --entry <n>",
                             "For multi image handlers which entry do you wish to extract");
    au->addCommandLineOption("-g", "Convert to grey scale.");
    au->addCommandLineOption("-q or --compression-quality <n>",
                             "Uses compression.  Valid for jpeg type. default is 75 where 100 is best and 1 is worst");
    au->addCommandLineOption("--pixel-type <type>",
                             "Valid values: area or point, this will determine if the tie point is upper left corner of "
                             "the upper left pixel (area) or the center of the upper left corner (point), default=point. "
                             "NOTE: This option will only affect the tiff writer.");
    au->addCommandLineOption("-r or --res-level <n>",
                             "Which res level to extract from the input: ex -r 1 will get res level 1");
    au->addCommandLineOption("-l or --start-line <n>",
                             "Which start line do you wish to copy from the input. If none is given then 0 is used");
    au->addCommandLineOption("-L or --end-line <n>",
                             "Which end line do you wish to copy from the input.  If none is given then max line is used");
    au->addCommandLineOption("-s or --start-sample <n>",
                             "Which start sample do you wish to copy from the input.  If none is given then 0 is used");
    au->addCommandLineOption("-p or --end-sample <n>",
                             "The end sample you wish to copy from the input. If none is given then max sample is used");
    au->addCommandLineOption("-t or --create-thumbnail <n>",
                             "Takes an argument which is the maximum pixel dimension desired.");
    au->addCommandLineOption("-w or --tile-width <n>",
                             "Defines the tile width for the handlers that support tiled output");

    au->addCommandLineOption("--reader-prop <string>",
                             "Adds a property to send to the reader. format is name=value");

    au->addCommandLineOption("--writer-prop <string>",
                             "Adds a property to send to the writer. format is name=value");

    au->addCommandLineOption("--filter-spec <fname>",
                             "This is an external file spec that describes a chain for filtering the input image.");
    au->addCommandLineOption("--use-mask [<fname>]",
                             "Optionally specify name of mask file to use for masking the input image. If no filename "
                             "given, then the default mask filename is used.");


    if (traceDebug()) CLOG << " Entered..." << std::endl;

    // Keyword list to initialize image writers with.
    ossimKeywordlist kwl;
    const char* PREFIX = "imagewriter.";

    bool        lineEndIsSpecified       = false;
    bool        sampEndIsSpecified       = false;
    bool        lineStartIsSpecified     = false;
    bool        sampStartIsSpecified     = false;
    bool        convert_to_greyscale     = false;
    bool        create_overview          = false;
    bool        create_thumbnail         = false;
    bool        use_band_selector        = false;
    bool        use_scalar_remapper      = false;
    bool        use_mask                 = false;
    ossim_int32 tile_width               = 0;
    ossim_int32 max_thumbnail_dimension  = 0;
    ossim_int32 rr_level                 = 0;
    ossim_int32 line_start               = 0;
    ossim_int32 line_stop                = 0;
    ossim_int32 sample_start             = 0;
    ossim_int32 sample_stop              = 0;
    ossim_int32 cibcadrg_entry           = 0;
    vector<ossimString> band_list(0);
    ossimFilename filterSpec, maskFile;
    std::map<ossimString, ossimString, ossimStringLtstr> readerPropertyMap;
    std::map<ossimString, ossimString, ossimStringLtstr> writerPropertyMap;

    if (ap.read("-h") ||
            ap.read("--help")||(ap.argc() < 2))
    {
        au->write(ossimNotify(ossimNotifyLevel_NOTICE));
        usage(); // for writer output types
        finalize(0);
    }

    while(ap.read("--reader-prop", stringParam))
    {
        std::vector<ossimString> nameValue;
        ossimString(tempString).split(nameValue, "=");
        if(nameValue.size() == 2)
        {
            readerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1])));
        }
    }
    while(ap.read("--writer-prop", stringParam))
    {
        std::vector<ossimString> nameValue;
        ossimString(tempString).split(nameValue, "=");
        if(nameValue.size() == 2)
        {
            writerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1])));
        }
    }
    while(ap.read("-a") ||
            ap.read("--use-scalar-remapper"))
    {
        use_scalar_remapper = true;
    }
    while(ap.read("--filter-spec",stringParam))
    {
        filterSpec = ossimFilename(tempString);
    }

    while(ap.read("--use-mask") ||
            ap.read("--use-mask",stringParam) )
    {
        maskFile = ossimFilename(tempString);
        use_mask = true;
    }

    while(ap.read("-o") ||
            ap.read("--create-overview"))
    {
        create_overview = true;
    }

    while(ap.read("-b", stringParam) ||
            ap.read("--bands", stringParam))
    {
        use_band_selector = true;
        ossimString s = tempString;
        band_list = s.split(",");
    }

    while(ap.read("-c", stringParam) ||
            ap.read("--compression-type", stringParam))
    {
        ossimString s = tempString;
        s.downcase();
        kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_TYPE_KW, s.c_str(), true);
    }

    while(ap.read("-e", stringParam) ||
            ap.read("--entry", stringParam))
    {
        cibcadrg_entry = ossimString(tempString).toInt();
    }

    if ( ap.read("-g") )
    {
        convert_to_greyscale = true;
    }

    while(ap.read("-q", stringParam) ||
            ap.read("--compression-quality", stringParam))
    {
        // Set the jpeg compression quality level.
        kwl.add(PREFIX,
                ossimKeywordNames::COMPRESSION_QUALITY_KW,
                tempString.c_str(),
                true);
    }
    while(ap.read("-r", stringParam) ||
            ap.read("--res-level", stringParam))
    {
        rr_level = ossimString(tempString).toInt();
    }

    while(ap.read("-l", stringParam) ||
            ap.read("--start-line", stringParam))
    {
        lineStartIsSpecified = true;
        line_start = ossimString(tempString).toInt();
    }

    while(ap.read("-L", stringParam) ||
            ap.read("--end-line", stringParam))
    {
        lineEndIsSpecified = true;
        line_stop = ossimString(tempString).toInt();
    }
    while(ap.read("-s", stringParam) ||
            ap.read("--start-sample", stringParam))
    {
        sampStartIsSpecified = true;
        sample_start = ossimString(tempString).toInt();
    }

    while(ap.read("-p", stringParam) ||
            ap.read("--end-sample", stringParam))
    {
        sampEndIsSpecified = true;
        sample_stop = ossimString(tempString).toInt();
    }

    while(ap.read("-t", stringParam) ||
            ap.read("--create-thumbnail", stringParam))
    {
        create_thumbnail = true;
        max_thumbnail_dimension=ossimString(tempString).toInt();
    }

    while(ap.read("-w", stringParam) ||
            ap.read("-tile-width", stringParam))
    {
        tile_width = ossimString(tempString).toInt();
        if ((tile_width % 16) != 0)
        {
            ossimNotify(ossimNotifyLevel_NOTICE)
                    << MODULE << " NOTICE:"
                    << "\nTile width must be a multiple of 16!"
                    << "\nDefaulting to 128"
                    << std::endl;
            tile_width = 0;
        }
    }
    if (ap.read("--pixel-type", stringParam))
    {
        ossimString os = tempString;
        os.downcase();
        if (os.contains("area"))
        {
            kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "area", true);
        }
        else
        {
            kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "point", true);

        }
    }

    ap.reportRemainingOptionsAsUnrecognized();

    // Three required args:  output_type, input file, and output file.
    if (ap.errors())
    {
        ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE));
        finalize(0);
    }
    if (ap.argc() < 4)
    {
        au->write(ossimNotify(ossimNotifyLevel_NOTICE));
        usage(); // for writer output types
        finalize(0);
    }

    //---
    // Set the writer type and the image type.
    //---
    ossimString output_type = ap.argv()[ap.argc()-3];
//   output_type.downcase();


    kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);
    // Get the input file.
    const char* input_file = argv[ap.argc()-2];

    // Get the output file.
    ossimFilename    output_file = argv[ap.argc()-1];

    if (traceDebug())
    {
        CLOG << "DEBUG:"
             << "\noutput type:  "
             << ap.argv()[ap.argc()-3]
             << "\ninput file:   "
             << ap.argv()[ap.argc()-2]
             << "\noutput file:  "
             << ap.argv()[ap.argc()-1]
             << std::endl;

        if (tile_width) ossimNotify(ossimNotifyLevel_NOTICE) << "tile_width:  " << tile_width << std::endl;
    }

    // Get an image handler for the input file.
    ossimRefPtr<ossimImageHandler> ih =
        ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file));

    ossimCibCadrgTileSource* its = PTR_CAST(ossimCibCadrgTileSource, ih.get());

    if (its)
    {
        if (cibcadrg_entry > 0)
        {
            its->setCurrentEntry(cibcadrg_entry);
        }
    }

    if (!ih)
    {
        ossimNotify(ossimNotifyLevel_NOTICE) << "Unsupported image file:  " << input_file
                                             << "\nExiting application..." << std::endl;
        finalize(0);
    }
    if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
    {
        ossimNotify(ossimNotifyLevel_FATAL)
                << "Error reading image:  " << input_file
                << "Exiting application..." << std::endl;
        finalize(1);
    }

    // Set the reader properties if any.
    if ( readerPropertyMap.size() )
    {
        ossimPropertyInterface* pi = (ossimPropertyInterface*)ih.get();
        std::map<ossimString, ossimString, ossimStringLtstr>::iterator iter = readerPropertyMap.begin();
        while(iter != readerPropertyMap.end())
        {
            pi->setProperty(iter->first, iter->second);
            ++iter;
        }
    }

    ih->initialize();
    ossimRefPtr<ossimImageSource> source = ih.get();

    if (traceDebug())
    {
        CLOG << "DEBUG:"
             << "\nImage Handler:  " << ih->getLongName()
             << std::endl;
    }

    if ( convert_to_greyscale )
    {
        ossimRefPtr<ossimRgbToGreyFilter> rgb2grey = new ossimRgbToGreyFilter();
        rgb2grey->connectMyInputTo( source.get() );
        source = rgb2grey.get();
    }

    ossimRefPtr<ossimMaskFilter> mask_filter = 0;
    if (use_mask)
    {
        if (maskFile.empty())
            maskFile = ih->getFilenameWithThisExtension("mask");
        ossimImageHandler* mh = ossimImageHandlerRegistry::instance()->open(maskFile);
        if (mh == NULL)
        {
            ossimNotify(ossimNotifyLevel_FATAL)<<"ossim-icp -- Could not open raster mask file <"
                                               <<maskFile<<">. Maske request will be ignored. Aborting..."<<endl;
            finalize(1);
        }
        mask_filter = new ossimMaskFilter();
        mask_filter->connectMyInputTo(source.get());
        mask_filter->setMaskSource(mh);  // assumes ownership of mask handler object
        source = mask_filter.get();
    }

    ossimRefPtr<ossimBandSelector> bs = 0;
    if(!filterSpec.empty()&&filterSpec.exists())
    {
        ossimKeywordlist kwl;
        if(kwl.addFile(filterSpec))
        {
            ossimRefPtr<ossimObject> input = ossimObjectFactoryRegistry::instance()->createObject(kwl);
            if(input.valid())
            {
                ossimImageSource* inputImageSource = dynamic_cast<ossimImageSource*> (input.get());
                if(inputImageSource)
                {
                    inputImageSource->connectMyInputTo(source.get());
                    source = inputImageSource;
                }
            }
        }
    }
    if (use_band_selector && (source->getNumberOfOutputBands() > 1))
    {
        // Build the band list.
        ossim_uint32 bands = source->getNumberOfOutputBands();
        vector<ossim_uint32> bl;
        ossim_uint32 i;
        for (i=0; i<band_list.size(); ++i)
        {
            bl.push_back(band_list[i].toULong()-1);
        }

        // Check the list.  Make sure all the bands are within range.
        for (i=0; i<bl.size(); ++i)
        {
            if (bl[i] >= bands)
            {
                ossimNotify(ossimNotifyLevel_FATAL)
                        << MODULE << " ERROR:"
                        << "\nBand list range error!"
                        << "\nHighest available band:  " << bands
                        << std::endl;
                finalize(1);
            }
        }

        bs = new ossimBandSelector();
        bs->connectMyInputTo(source.get());
        bs->setOutputBandList(bl);
        bs->enableSource();
        bs->initialize();
        source = bs.get();

        if (traceDebug())
        {
            CLOG << "DEBUG:"
                 << "\nZero based output band list:" << std::endl;
            for (i=0; i<bl.size(); ++i)
            {
                ossimNotify(ossimNotifyLevel_NOTICE)
                        << "   band[" << i << "]:  " << bl[i] << std::endl;
            }
            ossimNotify(ossimNotifyLevel_NOTICE) << std::endl;
        }
    }

    //---
    // Get the image rectangle for the rrLevel selected.
    //---
    ossimIrect output_rect;
    ossimRefPtr<ossimRLevelFilter> rlevelFilter = 0;

    if (create_thumbnail == true)
    {
        rlevelFilter = new ossimRLevelFilter;

        rlevelFilter->connectMyInputTo(source.get());

        source = rlevelFilter.get();
        // Get the rlevel that <= max thumbnail dimension.
        int max   = 0;
        int level = 0;

        while (level < ((ossim_int32)ih->getNumberOfDecimationLevels()-1))
        {
            int lines   = ih->getNumberOfLines(level);
            int samples = ih->getNumberOfSamples(level);
            max = lines > samples ? lines : samples;
            if (max <= max_thumbnail_dimension)
            {
                break;
            }
            level++;
        }

        if (max > max_thumbnail_dimension)
        {
            ossimNotify(ossimNotifyLevel_NOTICE) << " NOTICE:"
                                                 << "\nLowest rlevel not small enough to fulfill "
                                                 << "max_thumbnail_dimension requirement!" << std::endl;
        }

        // Set the reduced res level.  This will override the -r option.
        rr_level = level;
        rlevelFilter->setCurrentRLevel(rr_level);
        if (rr_level)
        {
            rlevelFilter->setOverrideGeometryFlag(true);
        }


        // Set the rectangle to that of the res level.
        output_rect = rlevelFilter->getBoundingRect();

    } // end of "if  (create_thumbnail == true)
    else
    {
        // modified to only do an rlevel if one is requested
        if(rr_level != 0)
        {
            //***
            // Check for a valid reduced resolution level.
            // If the operator entered an invalid rr_level with the -r option,
            // spit out a warning and set to default "0".
            //***
            if (rr_level >= (ossim_int32)(ih->getNumberOfDecimationLevels()))
            {
                ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:"
                                                     << "\n\t Selected res level greater than available res levels."
                                                     << "\n\t Defaulting to res level zero. " << std::endl;
                rr_level = 0;
            }

            rlevelFilter = new ossimRLevelFilter;

            rlevelFilter->connectMyInputTo(source.get());

            source = rlevelFilter.get();

            rlevelFilter->setCurrentRLevel(rr_level);
            if (rr_level)
            {
                rlevelFilter->setOverrideGeometryFlag(true);
            }
        }
        output_rect = source->getBoundingRect(rr_level);

        //***
        // If any of these are true the user wants to cut the rectangle.
        //***
        if ( lineStartIsSpecified || lineEndIsSpecified ||
                sampStartIsSpecified || sampEndIsSpecified)
        {
            if (!lineStartIsSpecified) line_start   = output_rect.ul().y;
            if (!lineEndIsSpecified)   line_stop    = output_rect.lr().y;
            if (!sampStartIsSpecified) sample_start = output_rect.ul().x;
            if (!sampEndIsSpecified)   sample_stop  = output_rect.lr().x;

            //***
            // Check the start and stop points and make sure they are in
            // the right order; if not, swap them.
            //***
            if (line_stop < line_start)
            {
                ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:\n"
                                                     << "\t Line end is less than line start, swapping."
                                                     << std::endl;
                int tmp    = line_start;
                line_start = line_stop;
                line_stop  = tmp;
            }
            if (sample_stop < sample_start)
            {
                ossimNotify(ossimNotifyLevel_WARN)
                        << " WARNING:\n"
                        << "\t Sample end is less than sample start, swapping."
                        << std::endl;
                int tmp      = sample_start;
                sample_start = sample_stop;
                sample_stop  = tmp;
            }

//          if (sample_start > output_rect.ul().x &&
//              sample_start < output_rect.lr().x)
//          {
            output_rect.set_ulx(sample_start);
//          }
//          if (sample_stop > output_rect.ul().x &&
//              sample_start < output_rect.lr().x)
//          {
            output_rect.set_lrx(sample_stop);
//          }
//          if (line_start > output_rect.ul().y &&
//              line_start < output_rect.lr().y)
//          {
            output_rect.set_uly(line_start);
//          }
//          if (line_stop > output_rect.ul().y &&
//              line_start < output_rect.lr().y)
//          {
            output_rect.set_lry(line_stop);
//          }

        } // End of "if ((lineEndIsSpecified) ||..."
    }

    if (traceDebug())
    {
        CLOG << "icp:main debug"
             << "\nrr_level:  " << rr_level
             << "\noutput_rect:   " << output_rect
             << "\nkeyword list:  " << kwl << std::endl;
    }


    ossimRefPtr<ossimImageFileWriter> writer =
        ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);

    if( writer == 0 )
    {
        ossimNotify(ossimNotifyLevel_NOTICE)
                << "\nCould not create writer of type:  "
                << output_type
                << std::endl;
        usage();
        finalize(1);
    }

    writer->connectMyInputTo(0, source.get());

    if (tile_width)
    {
        // Set the tile size...
        writer->setTileSize(ossimIpt(tile_width, tile_width));
    }

    writer->open(output_file);

    // Add a listener to get percent complete.
    ossimStdOutProgress prog(0, true);
    writer->addListener(&prog);

    if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
    {
        if( (ih->getOutputScalarType() != OSSIM_UCHAR) &&
                ((PTR_CAST(ossimJpegWriter, writer.get())) ||
                 use_scalar_remapper))
        {
            writer->setScaleToEightBitFlag(true);
        }

        ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource;
        ossimIpt tileWidthHeight(ih->getImageTileWidth(),
                                 ih->getImageTileHeight());
        // only use the cache if its stripped
        if(static_cast<ossim_uint32>(tileWidthHeight.x) ==
                ih->getBoundingRect().width())
        {
            cache->connectMyInputTo(0, source.get());
            cache->setTileSize(tileWidthHeight);
            writer->connectMyInputTo(0, cache.get());
        }
        else
        {
            writer->connectMyInputTo(0, source.get());
        }
        writer->initialize();
        writer->setAreaOfInterest(output_rect); // Set the output rectangle.

        try
        {
            if ( writerPropertyMap.size() )
            {
                ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get();
                std::map<ossimString, ossimString, ossimStringLtstr>::iterator iter = writerPropertyMap.begin();
                while(iter!=writerPropertyMap.end())
                {
                    propInterface->setProperty(iter->first, iter->second);
                    ++iter;
                }
            }
            writer->execute();
        }
        catch(std::exception& e)
        {
            ossimNotify(ossimNotifyLevel_FATAL)
                    << "icp:main ERROR:\n"
                    << "Caught exception!\n"
                    << e.what()
                    << std::endl;
        }
        catch(...)
        {
            ossimNotify(ossimNotifyLevel_FATAL)
                    << "icp:main ERROR:\n"
                    << "Unknown exception caught!\n"
                    << std::endl;
        }

        cache = 0;
    }
    else
    {
        ossimNotify(ossimNotifyLevel_FATAL)
                << "Error detected in the image writer..."
                << "\nExiting application..." << std::endl;

        finalize(1);
    }

    if (create_overview == true)
    {
        writer->writeOverviewFile();
    }

    finalize(0);
}
コード例 #20
0
ファイル: ossim-pixelflip.cpp プロジェクト: BJangeofan/ossim
int main(int argc, char* argv[])
{
   
#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
   ossimMpi::instance()->initialize(&argc, &argv);
   if (ossimMpi::instance()->getRank() == 0)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "MPI running with "
         << ossimMpi::instance()->getNumberOfProcessors()
         << " processors..." << std::endl;
   }
#  endif
#endif
   
   std::string tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
   
   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" flips any null pixels to a valid pixel");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] <output_type> <input_file> <output_file> <target_value> <replacement_value>");
   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image");
   argumentParser.getApplicationUsage()->addCommandLineOption("-c or --clamp-value", "clamp values (any pixel with value larger than input will be clamped to input)");
   argumentParser.getApplicationUsage()->addCommandLineOption("-m",  "Replacement mode (see notes below)");
   argumentParser.getApplicationUsage()->addCommandLineOption("-w",  "output tile width(only valid with tiled output types).  Must be a multiply of 16");
   
 
   static const char MODULE[] = "pixelflip:main";
   if (traceDebug()) CLOG << " Entered..." << std::endl;
   ossimInit::instance()->initialize(argc, argv);
   // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";
   bool create_overview = false;
   ossim_int32 tile_width = 0;
   double clamp_value = 0.0;
   bool do_clamp = false;
   ossimPixelFlipper::ReplacementMode replacement_mode =
      ossimPixelFlipper::REPLACE_BAND_IF_TARGET;


   if(argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() == 1))
   {
      argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO));
      usage();
      exit(0);
   }
   while(argumentParser.read("-o") || argumentParser.read("--create-overview"))
   {
      create_overview = true;
   }
   while(argumentParser.read("-c", stringParam))
   {
      clamp_value = ossimString(tempString).toDouble();
      do_clamp = true;
   }
   while(argumentParser.read("-m", stringParam))
   {
      ossimString mode = tempString;
      mode.downcase();
      if (mode == "replace_band_if_target")
      {
         replacement_mode = ossimPixelFlipper::REPLACE_BAND_IF_TARGET;
      }
      else if (mode == "replace_band_if_partial_target")
      {
         replacement_mode =
            ossimPixelFlipper::REPLACE_BAND_IF_PARTIAL_TARGET;
      }
      else if (mode == "replace_all_bands_if_partial_target")
      {
         replacement_mode = ossimPixelFlipper::REPLACE_ALL_BANDS_IF_PARTIAL_TARGET;
      }
      else if (mode != "replace_all_targets")
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "Invalid mode:  "
            << mode
            << "\nMode remains:  replace_band_if_target"
            << std::endl;
      }
   }
   while(argumentParser.read("-w", stringParam))
   {
      tile_width = ossimString(tempString).toInt32();
      if (tile_width % 16)
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << " NOTICE:"
            << "\nTile width must be a multiple of 16!"
            << "\nDefaulting to 128"
            << std::endl;
         tile_width = 0;
      }
   }

   if(argumentParser.argc() != 6)
   {
      ossimMpi::instance()->finalize();
      
      exit(0);
   }
   //***
   // Set the writer type and the image type.
   //***
   ossimString output_type = argumentParser.argv()[1];
   output_type.downcase();
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str());
   // Get the input file.
   ossimFilename input_file = argumentParser.argv()[2];
   // Get the output file.
   ossimFilename    output_file = argumentParser.argv()[3];
   // Get the value to replace.
   double target_value = ossimString(argumentParser.argv()[4]).toDouble();
   // Get the replacement value.
   double replacement_value = ossimString(argumentParser.argv()[5]).toDouble();
   bool master = true;

   if (ossimMpi::instance()->getRank() != 0)
   {
      master = false;
   }
   if (master)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "pixelflip settings:"
         << "\noutput type:        " << output_type
         << "\ninput file:         " << input_file
         << "\noutput file:        " << output_file
         << "\ntarget value:       " << target_value
         << "\nreplacement value:  " << replacement_value
         << std::endl;
      if (tile_width)
      {
         ossimNotify(ossimNotifyLevel_INFO)
            << "tile width:         " << tile_width << std::endl;
      }
      if (do_clamp)
      {
          ossimNotify(ossimNotifyLevel_INFO)
             << "clamp value:        " << clamp_value << std::endl;
      }
   }
   // Get an image handler for the input file.
   ossimRefPtr<ossimImageHandler> ih
      = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file));
   if (!ih)
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Unsupported image file:  " << input_file
         << "\nExiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(0);
   }
   // Initialize the
   if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Error reading image:  " << input_file
         << "Exiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(1);
   }
   ih->initialize();
   if (traceDebug())
   {
      CLOG << "DEBUG:"
           << "\nImage Handler:  " << ih->getLongName()
           << std::endl;
   }
   // Capture the bounding rectangle of the image handler.
   ossimIrect output_rect = ih->getBoundingRect(0);
   // hook up the pixel flipper to the image handler.
   ossimRefPtr<ossimPixelFlipper> pf = new ossimPixelFlipper();
   pf->connectMyInputTo(ih.get());
   pf->initialize();
   // Setup the pixel flipper target/replacement values, and replace mode.
   pf->setTargetValue(target_value);
   pf->setReplacementValue(replacement_value);
   pf->setReplacementMode(replacement_mode);
   // Setup pixel flipper clamp value
   if (do_clamp)
   {
      pf->setClampValue(clamp_value);
   }
   if (master)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "replacement mode:   " << pf->getReplacementModeString()
         << std::endl;
   }
   ossimImageSourceSequencer* sequencer = NULL;

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
   // only allocate the slave connection if
   // the number of processors is larger than
   // 1
   //
   if(ossimMpi::instance()->getNumberOfProcessors() > 1)
   {
      if(ossimMpi::instance()->getRank()!=0)
      {
         sequencer = new ossimImageMpiSWriterSequenceConnection(NULL, 4);
      }
      else
      {
         sequencer = new ossimImageMpiMWriterSequenceConnection();
      }
   }
   else
   {
      sequencer = new ossimImageSourceSequencer();
   }
#  else
   // we will just load a serial connection if MPI is not supported.
   sequencer = new ossimImageSourceSequencer(NULL);
#  endif
#else
   sequencer = new ossimImageSourceSequencer(NULL);
#endif
   
   ossimRefPtr<ossimImageWriter> writer
      = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);
   ossimImageFileWriter* fileWriter = PTR_CAST(ossimImageFileWriter, writer.get());
   if( fileWriter == NULL )
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Error making an image writer..."
         << "\nExiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(1);
   }
   // Change out the sequencer...
   fileWriter->changeSequencer(sequencer);
   // Hook up the pixel flipper to the file writer.
   fileWriter->connectMyInputTo(0, pf.get());
   if (tile_width)
   {
      // Set the tile size...
      fileWriter->setTileSize(ossimIpt(tile_width, tile_width));
   }
   fileWriter->open(output_file);
   // Add a listener to get percent complete.
   ossimStdOutProgress prog(0, true);
   fileWriter->addListener(&prog);
   if (fileWriter->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
   {
      fileWriter->initialize();
      fileWriter->setAreaOfInterest(output_rect); // Set the output rectangle.

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
      double start_time = 0.0;
      if(ossimMpi::instance()->getRank() == 0)
      {
         start_time= MPI_Wtime();
      }
#  endif
#endif

      // Filter and write the file...
      fileWriter->execute();

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
      if(ossimMpi::instance()->getRank() == 0)
      {
         double stop_time = MPI_Wtime();
         cout << "Elapsed time: " << (stop_time-start_time) << std::endl;
      }
#  endif
#endif
   }
   else
   {
      cerr << "Error detected in the image writer..."
           << "\nExiting application..." << std::endl;
      exit(1);
   }
   if (create_overview == true)
   {
      fileWriter->writeOverviewFile();
   }

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI   
   ossimMpi::instance()->finalize();
#  endif
#endif
   
   exit(0);
}
コード例 #21
0
int main(int argc, char* argv[])
{
   ossimString tempString1;
   ossimString tempString2;
   ossimString tempString3;
   ossimString tempString4;
   ossimArgumentParser::ossimParameter tempParam1(tempString1);
   ossimArgumentParser::ossimParameter tempParam2(tempString2);
   ossimArgumentParser::ossimParameter tempParam3(tempString3);
   ossimArgumentParser::ossimParameter tempParam4(tempString4);
   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
   bool rpcFlag       = false;
   bool cgFlag       = false;
   bool enableElevFlag = true;
   bool enableAdjustmentFlag = true;
   ossimDrect imageRect;
   double error = .1;

   imageRect.makeNan();
   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName() + " takes an input geometry (or image) and creates a converted output geometry");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName() + " [options] <input file>");
   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->addCommandLineOption("--rpc","Create an RPC projection");
   argumentParser.getApplicationUsage()->addCommandLineOption("--rpc-gridsize","defines the grid size for the rpc estimate default is --rpc-gridsize=\"10 10\"");
   argumentParser.getApplicationUsage()->addCommandLineOption("--noelev","the projection but 0 out the elevation");
   argumentParser.getApplicationUsage()->addCommandLineOption("--disable-adjustments","Current applies to coarse grid.  It will try to make the grid adjustable if the input projection is adjustable");
   argumentParser.getApplicationUsage()->addCommandLineOption("--cg","Create a coarse grid projection");
   argumentParser.getApplicationUsage()->addCommandLineOption("--rect"," 4 values ulx uly width height");
   argumentParser.getApplicationUsage()->addCommandLineOption("--tolerance","Used as an error tolerance.  Currently on coarse grid uses it and is the pixel error for the estimate");
   argumentParser.getApplicationUsage()->addCommandLineOption("--output","Override the default output name");
   
   if (argumentParser.read("-h") || argumentParser.read("--help") || (argumentParser.argc() == 1))
   {
      argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO));
      ossimInit::instance()->finalize();
      exit(0);
   }
   ossimFilename outputFile;
   ossimIpt rpcGridSize(10,10);
   if(argumentParser.read("--tolerance", tempParam1))
   {
      error = tempString1.toDouble();
   }
   
   if (argumentParser.read("--rpc"))
   {
      rpcFlag = true;
   }
   if (argumentParser.read("--rpc-gridsize",tempParam1, tempParam2))
   {
      rpcGridSize.x = tempString1.toInt32();
      rpcGridSize.y = tempString2.toInt32();
      if(rpcGridSize.x < 1)
      {
         rpcGridSize.x = 8;
      }
      if(rpcGridSize.y < 1)
      {
         rpcGridSize.y = rpcGridSize.x;
      }
   }
   if (argumentParser.read("--cg"))
   {
      cgFlag = true;
   }
   if (argumentParser.read("--noelev"))
   {
      enableElevFlag = false;
   }
   if(argumentParser.read("--disable-adjustments"))
   {
      enableAdjustmentFlag = false;
   }
   if(argumentParser.read("--output", tempParam1))
   {
      outputFile = ossimFilename(tempString1);
   }
   if(argumentParser.read("--rect", tempParam1,tempParam2,tempParam3,tempParam4 ))
   {
      double x,y,w,h;
      x = tempString1.toDouble();
      y = tempString2.toDouble();
      w = tempString3.toDouble();
      h = tempString4.toDouble();

      if(w < 1) w = 1;
      if(h < 1) h = 1;
      imageRect = ossimDrect(x,y,x+(w-1), y+(h-1));
   }
   argumentParser.reportRemainingOptionsAsUnrecognized();
   if (argumentParser.errors())
   {
      argumentParser.writeErrorMessages(std::cout);
      exit(0);
   }
   ossimFilename file(argv[1]);
   ossimRefPtr<ossimImageHandler> h = ossimImageHandlerRegistry::instance()->open(file);
   ossimRefPtr<ossimProjection> inputProj = 0;
   ossimKeywordlist kwl;
   ossim_int32 minSpacing = 100;
   ossimRefPtr<ossimImageGeometry> geom;
   if(h.valid())
   {
      geom      = h->getImageGeometry();
      imageRect = h->getBoundingRect();
   }
   else if(!imageRect.hasNans())
   {
      kwl.add(ossimKeywordNames::GEOM_FILE_KW,
              file.c_str());
      inputProj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl);
   }
   if(!geom.valid()||!geom->getProjection())
   {
      ossimNotify(ossimNotifyLevel_WARN) << "Unable to obtain an input projection. Returning " << std::endl;
      argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO));
   }
   else if(!imageRect.hasNans())
   {
      if(outputFile.empty())
      {
         outputFile = file.setExtension("geom");
      }
      if(rpcFlag)
      {
         ossimRefPtr<ossimRpcSolver> solver = new ossimRpcSolver(enableElevFlag);
         
         solver->solveCoefficients(imageRect,
                                  geom.get(),
                                  rpcGridSize.x,
                                  rpcGridSize.y);
         
         ossimRefPtr<ossimImageGeometry> outputProj = solver->createRpcProjection();
         kwl.clear();
         outputProj->saveState(kwl);
         kwl.write(outputFile);
      }
      else if(cgFlag)
      {
         ossimCoarseGridModel::setInterpolationError(error);
         ossimCoarseGridModel::setMinGridSpacing(minSpacing);
         ossimCoarseGridModel cg;
         
         cg.buildGrid(imageRect,
                      inputProj.get(),
                      500.0,
                      enableElevFlag,
                      enableAdjustmentFlag);
         kwl.clear();
         cg.saveState(kwl);
         kwl.write(outputFile);
         cg.saveCoarseGrid(outputFile.setExtension("dat"));
      }
   }
   else
   {
      ossimNotify(ossimNotifyLevel_WARN) << "Unable to find an image rect" << std::endl;
   }
   return 0;
}
コード例 #22
0
ossimRefPtr<ossimImageData> ossimCFARFilter::getTile(const ossimIrect& tileRect,
                                                     ossim_uint32 resLevel)
{
   if(!theInputConnection)
   {
      return theTile;
   }

   if(!isSourceEnabled())
   {
      return theInputConnection->getTile(tileRect, resLevel);
   }

   //---
   // We have a 5x5 matrix so stretch the rect out to cover
   // the required pixels.  We only need 2 pixels to the left
   // and right of the center pixel.
   //---
   ossimIrect newRect(ossimIpt(tileRect.ul().x - 2,
                               tileRect.ul().y - 2),
                      ossimIpt(tileRect.lr().x + 2,
                               tileRect.lr().y + 2));
   
   ossimRefPtr<ossimImageData> data = theInputConnection->getTile(newRect,
                                                                  resLevel);

   if(!data.valid() || !data->getBuf())
   {
      return data;
   }

    // First time through or after an initialize()...
   if (!theTile.valid())
   {
      allocate();
      if (!theTile.valid()) // Should never happen!
      {
         return data;
      }
   }

   // First time through, after an initialize() or a setKernel()...
   if (!theNullPixValue.size())
   {
      computeNullMinMax();
      if (!theNullPixValue.size()) // Should never happen!
      {
         return data;
      }
   }

   theTile->setImageRectangle(tileRect);
   theTile->makeBlank();
   
   switch(data->getScalarType())
   {
      case OSSIM_UCHAR:
      {
         if(data->getDataObjectStatus() == OSSIM_FULL)
         {
            convolveFull(static_cast<ossim_uint8>(0), data, theTile);
         }
         else
         {
            convolvePartial(static_cast<ossim_uint8>(0), data, theTile);
         }
         break;
      }
      case OSSIM_FLOAT: 
      case OSSIM_NORMALIZED_FLOAT:
      {
         if(data->getDataObjectStatus() == OSSIM_FULL)
         {
            convolveFull(static_cast<float>(0), data, theTile);
         }
         else
         {
            convolvePartial(static_cast<float>(0), data, theTile);
         }
         break;
      }
      case OSSIM_USHORT16:
      case OSSIM_USHORT11:
      {
         if(data->getDataObjectStatus() == OSSIM_FULL)
         {
            convolveFull(static_cast<ossim_uint16>(0), data, theTile);
         }
         else
         {
            convolvePartial(static_cast<ossim_uint16>(0), data, theTile);
         }
         break;
      }
      case OSSIM_SSHORT16:
      {
         if(data->getDataObjectStatus() == OSSIM_FULL)
         {
            convolveFull(static_cast<ossim_sint16>(0), data, theTile);
         }
         else
         {
            convolvePartial(static_cast<ossim_sint16>(0), data, theTile);
         }
         break;
      }
      case OSSIM_DOUBLE:
      case OSSIM_NORMALIZED_DOUBLE:
      {
         if(data->getDataObjectStatus() == OSSIM_FULL)
         {
            convolveFull(static_cast<double>(0), data, theTile);
      }
      else
      {
         convolvePartial(static_cast<double>(0), data, theTile);
      }
         break;
      }
      default:
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "ossimCFARFilter::getTile WARNING:\n"
            << "Scalar type = " << theTile->getScalarType()
            << " Not supported by ossimCFARFilter" << endl;
         break;
      }
   }
   theTile->validate();
   
   return theTile;
}
コード例 #23
0
bool ossimTiledElevationDatabase::processFile(const ossimFilename& file,
                                              bool& recurseFlag)
{
   static const char M[] = "ossimTiledElevationDatabase::processFile";
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << M << " entered...\n" << "file: " << file << "\n";
   }
   bool continueFlag = true;

   ossimRefPtr<ossimSingleImageChain> sic = new ossimSingleImageChain();
   if ( sic->open(file, false) ) // False for do not open overviews.
   {
      // Set the directory walker flag.
      recurseFlag = !(isDirectoryBasedImage(sic->getImageHandler()));
     
      ossimRefPtr<ossimImageHandler> ih = sic->getImageHandler();
      if ( ih.valid() && (m_requestedRect.isLonLatNan() == false) )
      {
         ossimRefPtr<ossimImageGeometry> geom = ih->getImageGeometry();
         if ( geom.valid() == false )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nNo image geometry for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg);
         }
         
         ossimRefPtr<ossimProjection> proj = geom->getProjection();
         if ( proj.valid() == false )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nNo image projection for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg);
         }
         
         // Get the bounding rect:
         ossimGrect boundingRect;
         getBoundingRect(geom, boundingRect);
         
         if ( boundingRect.isLonLatNan() )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nBounding rect has nans for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg); 
         }
         
         if ( boundingRect.intersects(m_requestedRect) )
         {
            bool addEntryToList = false;
            
            if ( m_entries.size() == 0 ) // First time through.
            {
               addEntryToList = true;
               m_entryListRect = boundingRect;
               m_referenceProj = proj;
               m_meanSpacing = (geom->getMetersPerPixel().x + geom->getMetersPerPixel().y) / 2.0;
            }
            else 
            {
               addEntryToList = isCompatible( ih.get(), geom.get(), proj.get() );
               if ( addEntryToList )
               {
                  // Expand the rectangle.
                  m_entryListRect.combine(boundingRect);
               }
            }
            
            if ( addEntryToList )
            {
               // If we're keeping it add a cache to the chain.
               sic->addCache();
               
               //---
               // Create the entry and give to addEntry which checks for duplicates in case
               // mapRegion was called consecutively.
               //---
               ossimTiledElevationEntry entry(boundingRect, sic);
               addEntry(entry);

               continueFlag = m_requestedRect.completely_within(m_entryListRect);
            }
         }
      }
      else
      {
         std::string errMsg = M;
         errMsg += " ERROR:\nNo image geometry for image: ";
         errMsg += ih->getFilename().string();
         throw ossimException(errMsg);
      }
   }
   
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << M << " recurseFlag=" << recurseFlag
         << " continueFlag=" << continueFlag << "\n";
   }

   return continueFlag;
}
コード例 #24
0
bool ossimDtedHandler::open(const ossimFilename& file, bool memoryMapFlag)
{
   static const char* MODULE = "ossimDtedHandler::open";
   close();
   theFilename = file;
   m_fileStr.clear();

   m_fileStr.open(file.c_str(), 
                  std::ios::in | std::ios::binary);
   if(!m_fileStr.good())
   {
      return false;
   }
   m_numLonLines = 0;
   m_numLatPoints = 0;
   m_dtedRecordSizeInBytes = 0;
   
   // Attempt to parse.
   m_vol.parse(m_fileStr);
   m_hdr.parse(m_fileStr);
   m_uhl.parse(m_fileStr);
   m_dsi.parse(m_fileStr);
   m_acc.parse(m_fileStr);

   //***
   // Check for errors.  Must have uhl, dsi and acc records.  vol and hdr
   // are for magnetic tape only; hence, may or may not be there.
   //***
   if (m_uhl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR ||
       m_dsi.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR ||
       m_acc.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
         << "DEBUG " << MODULE << ": "
         << "\nError parsing file:  " << file.c_str()
         << "\nPossibly not a dted file."
         << std::endl;
      }
      
      theErrorStatus = ossimErrorCodes::OSSIM_ERROR;
      close();
      return false;
   }
   if(memoryMapFlag)
   {
      m_fileStr.seekg(0);
      m_fileStr.clear();
      m_memoryMap.resize(theFilename.fileSize());
      m_fileStr.read((char*)(&m_memoryMap.front()), (std::streamsize)m_memoryMap.size());
      m_fileStr.close();
   }
   
   m_numLonLines  = m_uhl.numLonLines();
   m_numLatPoints = m_uhl.numLatPoints();
   m_latSpacing   = m_uhl.latInterval();
   m_lonSpacing   = m_uhl.lonInterval();
   m_dtedRecordSizeInBytes = m_numLatPoints*2+ossimDtedRecord::DATA_LENGTH;
   
   m_edition  = m_dsi.edition();
   m_productLevel = m_dsi.productLevel();
   m_compilationDate = m_dsi.compilationDate();
   
   m_offsetToFirstDataRecord = m_acc.stopOffset();
   
   //***
   //  initialize the bounding rectangle:
   //***
   double south_boundary = m_uhl.latOrigin();
   double west_boundary  = m_uhl.lonOrigin();
   double north_boundary = south_boundary + m_latSpacing*(m_numLatPoints-1);
   double east_boundary  = west_boundary  + m_lonSpacing*(m_numLonLines-1);
   
   // For ossimElevCellHandler::pointHasCoverage method.
   theGroundRect = ossimGrect(ossimGpt(north_boundary, west_boundary, 0.0),
                              ossimGpt(south_boundary, east_boundary, 0.0));
   
   m_swCornerPost.lat = south_boundary;
   m_swCornerPost.lon = west_boundary;
   
   //***
   //  Determine the mean spacing:
   //***
   double center_lat = (south_boundary + north_boundary)/2.0;
   theMeanSpacing = (m_latSpacing + m_lonSpacing*ossim::cosd(center_lat))
                     * ossimGpt().metersPerDegree().x / 2.0;
   
   //  Initialize the accuracy values:
   theAbsLE90 = m_acc.absLE();
   theAbsCE90 = m_acc.absCE();
   
   // Set the base class null height value.
   theNullHeightValue = -32767.0;

   //---
   // Commented out as this writes an un-needed file.  (drb 20100611)
   // Get the statistics.
   // gatherStatistics();
   //---

   return true;
}
コード例 #25
0
ossimRefPtr<ossimImageData> ossimBlendMosaic::getTile(
   const ossimIrect& tileRect,
   ossim_uint32 resLevel)
{   
   // ossimIpt origin = tileRect.ul();
   if(!isSourceEnabled())
   {
      return ossimImageMosaic::getTile(tileRect, resLevel);
   }
   
   ossim_uint32 size = getNumberOfInputs();
   if(!theTile.get())
   {
      // try to initialize
      initialize();

      // if we still don't have a buffer
      // then we will leave
      if(!theTile.get())
      {
         return theTile;
      }
   }

   if(size == 0)
   {
      return ossimRefPtr<ossimImageData>();
   }
   if(size == 1)
   {
      return ossimImageMosaic::getTile(tileRect, resLevel);
   }

   theTile->setImageRectangle(tileRect);
   theTile->makeBlank();
   if(theNormResult.valid())
   {
      theNormResult->setImageRectangle(tileRect);
      theNormResult->makeBlank();
   }
   
   switch(theTile->getScalarType())
   {
      case OSSIM_UINT8:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_uint8>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_uint8>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_SINT8:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_sint8>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_sint8>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_FLOAT32: 
      case OSSIM_NORMALIZED_FLOAT:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<float>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<float>(0), tileRect, resLevel);
         }
      }
      case OSSIM_UINT16:
      case OSSIM_USHORT11:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_uint16>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_uint16>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_SINT16:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_sint16>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_sint16>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_SINT32:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_sint32>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_sint32>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_UINT32:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<ossim_uint32>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<ossim_uint32>(0), tileRect,
                               resLevel);
         }
      }
      case OSSIM_FLOAT64:
      case OSSIM_NORMALIZED_DOUBLE:
      {
         if(!hasDifferentInputs())
         {
            return combine(static_cast<double>(0), tileRect, resLevel);
         }
         else
         {
            return combineNorm(static_cast<double>(0), tileRect, resLevel);
         }
      }
      case OSSIM_SCALAR_UNKNOWN:
      default:
      {
         ossimNotify(ossimNotifyLevel_NOTICE)
            << "ossimBlendMosaic::getTile NOTICE:\n"
            << "Scalar type = " << theTile->getScalarType()
            << " Not supported by ossimImageMosaic" << endl;
       }
   }

   return ossimRefPtr<ossimImageData>();   
}
コード例 #26
0
void ossimDtedHandler::gatherStatistics()
{
   //***
   // Check to see if there is a statistics file already.  If so; do a lookup
   // for the min and max values.
   //***
   ossimFilename stats_file = theFilename;//theFilename.path();
   stats_file.setExtension("statistics");
   
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "DEBUG ossimDtedHandler::gatherStatistics(): Looking for "
         << stats_file << " statistics file..." << std::endl;
   }

   ossimKeywordlist kwl;
   const char* min_str = NULL;
   const char* max_str = NULL;

   if (stats_file.exists())
   {
      if (kwl.addFile(stats_file))
      {
         // Look for the min_pixel_value keyword.
         min_str = kwl.find(ossimKeywordNames::MIN_VALUE_KW);
         max_str = kwl.find(ossimKeywordNames::MAX_VALUE_KW);
      }
   }

   if (min_str && max_str)
   {
      theMinHeightAboveMSL = atoi(min_str);
      theMaxHeightAboveMSL = atoi(max_str);
   }
   else if (theComputeStatsFlag&&!m_memoryMap.size())  // Scan the cell and gather the statistics...
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_NOTICE)
            << "NOTICE ossimDtedHandler::gatherStatistics():"
            << " scanning for min/max"
            << "\nThis may take a while..." << std::endl;
      }
      // Start off with the min and max pegged.
      theMinHeightAboveMSL =  32767;
      theMaxHeightAboveMSL = -32767;
      
      // Put the file pointer at the start of the first elevation post.
      m_fileStr.seekg(m_offsetToFirstDataRecord, std::ios::beg);
      
      //---
      // Loop through all records and scan for lowest min and highest max.
      // Each record contains a row of latitude points for a given longitude.
      // There are eight bytes in front of the post and four checksum bytes at
      // the end so ignore them.
      //---
      for (ossim_int32 i=0; i<m_numLonLines; ++i)  // longitude direction
      {
         m_fileStr.seekg(DATA_RECORD_OFFSET_TO_POST, std::ios::cur);
         
         for (ossim_int32 j=0; j<m_numLatPoints; ++j) // latitude direction
         {
            ossim_uint16 us;
            ossim_sint16 ss;
            m_fileStr.read((char*)&us, POST_SIZE);
            ss = convertSignedMagnitude(us);
            if (ss < theMinHeightAboveMSL && ss != NULL_POST)
            {
               theMinHeightAboveMSL = ss;
            }
            if (ss > theMaxHeightAboveMSL)
            {
               theMaxHeightAboveMSL = ss;
            }
         }
         
         m_fileStr.seekg(DATA_RECORD_CHECKSUM_SIZE, std::ios::cur);
      }
      
      // Add the stats to the keyword list.
      kwl.add(ossimKeywordNames::MIN_VALUE_KW, theMinHeightAboveMSL);
      kwl.add(ossimKeywordNames::MAX_VALUE_KW, theMaxHeightAboveMSL);
      
      // Write out the statistics file.
      kwl.write(stats_file.c_str());
   }

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "DEBUG ossimDtedHandler::gatherStatistics:"
         << "\ntheMinHeightAboveMSL:  " << theMinHeightAboveMSL
         << "\ntheMaxHeightAboveMSL:  " << theMaxHeightAboveMSL
         << std::endl;
   }
}
コード例 #27
0
ファイル: ossimPngReader.cpp プロジェクト: Dukeke/ossim
void ossimPngReader::fillTile(const ossimIrect& clip_rect,
                              ossimImageData* tile)
{
   if (!tile || !m_str) return;

   ossimIrect buffer_rect = clip_rect;
   buffer_rect.stretchToTileBoundary(m_cacheSize);
   buffer_rect.set_ulx(0);
   buffer_rect.set_lrx(getImageRectangle(0).lr().x);

   ossim_int32 number_of_cache_tiles = buffer_rect.height()/m_cacheSize.y;

#if 0
   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "tiles high:  " << number_of_cache_tiles
         << endl;
   }
#endif

   ossimIpt origin = buffer_rect.ul();
   
   for (int tileIdx = 0; tileIdx < number_of_cache_tiles; ++tileIdx)
   {
      // See if it's in the cache already.
      ossimRefPtr<ossimImageData> tempTile;
      tempTile = ossimAppFixedTileCache::instance()->
         getTile(m_cacheId, origin);
      if (tempTile.valid())
      {
         tile->loadTile(tempTile.get());
      }
      else
      {
         // Have to read from the png file.
         ossim_uint32 startLine = static_cast<ossim_uint32>(origin.y);
         ossim_uint32 stopLine  = 
            static_cast<ossim_uint32>( min(origin.y+m_cacheSize.y-1,
                                           getImageRectangle().lr().y) );
         ossimIrect cache_rect(origin.x,
                               origin.y,
                               origin.x+m_cacheSize.x-1,
                               origin.y+m_cacheSize.y-1);
         
         m_cacheTile->setImageRectangle(cache_rect);

         if ( !m_cacheTile->getImageRectangle().
              completely_within(getImageRectangle()) )
         {
            m_cacheTile->makeBlank();
         }

         if (startLine < m_currentRow)
         {
            // Must restart the compression process again.
            restart();
         }

         // Gobble any not needed lines.
         while(m_currentRow < startLine)
         {
            png_read_row(m_pngReadPtr, m_lineBuffer, NULL);
            ++m_currentRow;
         }
            
         switch (m_readMode)
         {
            case ossimPngRead8:
            {
               copyLines(ossim_uint8(0), stopLine);
               break;
            }
            case ossimPngRead16:
            {
               copyLines(ossim_uint16(0), stopLine);
               break;
            }
            case ossimPngRead8a:
            {
               if (m_useAlphaChannelFlag)
               {
                  copyLines(ossim_uint8(0), stopLine);
               }
               else
               {
                  // Will burn alpha value into the other bands.
                  copyLinesWithAlpha(ossim_uint8(0), stopLine);
               }
               break;
            }
            case ossimPngRead16a:
            {
               if (m_useAlphaChannelFlag)
               {
                  copyLines(ossim_uint16(0), stopLine); 
               }
               else
               {
                  // Will burn alpha value into the other bands.
                  copyLinesWithAlpha(ossim_uint16(0), stopLine);
               }
               break;
            }
            case ossimPngReadUnknown:
            default:
            {
               break; // should never happen.
            }
         }

         m_cacheTile->validate();
         
         tile->loadTile(m_cacheTile.get());
         
         // Add it to the cache for the next time.
         ossimAppFixedTileCache::instance()->addTile(m_cacheId,
                                                     m_cacheTile);
         
      } // End of reading for png file.
      
      origin.y += m_cacheSize.y;
      
   } // for (int tile = 0; tile < number_of_cache_tiles; ++tile)
   
   tile->validate();
}
コード例 #28
0
int ossimDDFSubfieldDefn::GetDataLength( const char * pachSourceData,
                                    int nMaxBytes, int * pnConsumedBytes )

{
    if( !bIsVariable )
    {
        if( nFormatWidth > nMaxBytes )
        {
            ossimNotify(ossimNotifyLevel_WARN)
               << "Only %d bytes available for subfield %s with\n"
               << "format string %s ... returning shortened data."
               << nMaxBytes << pszName << pszFormatString << std::endl;

            if( pnConsumedBytes != NULL )
                *pnConsumedBytes = nMaxBytes;

            return nMaxBytes;
        }
        else
        {
            if( pnConsumedBytes != NULL )
                *pnConsumedBytes = nFormatWidth;

            return nFormatWidth;
        }
    }
    else
    {
        int     nLength = 0;
        int     bCheckFieldTerminator = true;

        /* We only check for the field terminator because of some buggy 
         * datasets with missing format terminators.  However, we have found
         * the field terminator is a legal character within the fields of
         * some extended datasets (such as JP34NC94.000).  So we don't check
         * for the field terminator if the field appears to be multi-byte
         * which we established by the first character being out of the 
         * ASCII printable range (32-127). 
         */

        if( pachSourceData[0] < 32 || pachSourceData[0] >= 127 )
            bCheckFieldTerminator = false;
        
        while( nLength < nMaxBytes
               && pachSourceData[nLength] != chFormatDelimeter )
        {
            if( bCheckFieldTerminator 
                && pachSourceData[nLength] == OSSIM_DDF_FIELD_TERMINATOR )
                break;

            nLength++;
        }

        if( pnConsumedBytes != NULL )
        {
            if( nMaxBytes == 0 )
                *pnConsumedBytes = nLength;
            else
                *pnConsumedBytes = nLength+1;
        }
        
        return nLength;
    }
}
コード例 #29
0
ファイル: ossimPngReader.cpp プロジェクト: Dukeke/ossim
bool ossimPngReader::initReader()
{
   bool result = true;
   
   ossim_uint32 height    = png_get_image_height(m_pngReadPtr, m_pngReadInfoPtr);
   ossim_uint32 width     = png_get_image_width(m_pngReadPtr, m_pngReadInfoPtr);
   m_bitDepth            = png_get_bit_depth(m_pngReadPtr, m_pngReadInfoPtr);
   m_pngColorType        = png_get_color_type(m_pngReadPtr, m_pngReadInfoPtr);
   
   m_imageRect = ossimIrect(0, 0, width  - 1, height - 1);
   
   if (m_bitDepth == 16)
   {
      // png_set_strip_16 (m_pngReadPtr);
      m_bytePerPixelPerBand = 2;
      m_outputScalarType = OSSIM_UINT16;
   }
   else
   {
      m_bytePerPixelPerBand = 1;
   }

   // Set the read mode from scalar and color type.
   if (m_outputScalarType == OSSIM_UINT8)
   {
      if ( (m_pngColorType == PNG_COLOR_TYPE_RGB_ALPHA) ||
           (m_pngColorType == PNG_COLOR_TYPE_GRAY_ALPHA) )
      {
         m_readMode = ossimPngRead8a;
      }
      else
      {
         m_readMode = ossimPngRead8;
      }
   }
   else
   {
      if ( (m_pngColorType == PNG_COLOR_TYPE_RGB_ALPHA) ||
           (m_pngColorType == PNG_COLOR_TYPE_GRAY_ALPHA) )
      {
         m_readMode = ossimPngRead16a;
      }
      else
      {
         m_readMode = ossimPngRead16;
      }

      // Set the swap flag.  PNG stores data in network byte order(big endian).
      if(ossim::byteOrder() == OSSIM_LITTLE_ENDIAN)
      {
         m_swapFlag = true;
      }
   }
   
   //---
   // If png_set_expand used:
   // Expand data to 24-bit RGB, or 8-bit grayscale,
   // with alpha if available.
   //---
   bool expandFlag = false;

   if ( m_pngColorType == PNG_COLOR_TYPE_PALETTE )
   {
      expandFlag = true;
   }
   if ( (m_pngColorType == PNG_COLOR_TYPE_GRAY) && (m_bitDepth < 8) )
   {
      expandFlag = true;
   }
   if ( png_get_valid(m_pngReadPtr, m_pngReadInfoPtr, PNG_INFO_tRNS) )
   {
      expandFlag = true;
   }

   //---
   // If png_set_packing used:
   // Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
   //---
   bool packingFlag = false;

   if ( (m_bitDepth < 8) && (m_pngColorType == PNG_COLOR_TYPE_GRAY) )
   {
      packingFlag = true;
   }

   if (expandFlag)
   {
       png_set_expand(m_pngReadPtr);
   }
   if (packingFlag)
   {
      png_set_packing(m_pngReadPtr);
   }

   // Gamma correction.
   // ossim_float64 gamma;
   // if (png_get_gAMA(m_pngReadPtr, m_pngReadInfoPtr, &gamma))
   // {
   //    png_set_gamma(png_ptr, display_exponent, gamma);
   // }

   //---
   // Turn on interlace handling... libpng returns just 1 (ie single pass)
   //  if the image is not interlaced
   //---
   m_interlacePasses = png_set_interlace_handling (m_pngReadPtr);

   //---
   // Update the info structures after the transformations take effect
   //---
   png_read_update_info (m_pngReadPtr, m_pngReadInfoPtr);

   // TODO:
   // Add check for image offsets.
   // Add check for resolution.
   // Add check for colormap.

   switch (m_pngColorType)
   {
      case PNG_COLOR_TYPE_RGB:           /* RGB */
      {
         m_numberOfInputBands  = 3;
         m_numberOfOutputBands = 3;
         break;
      }  
      case PNG_COLOR_TYPE_RGB_ALPHA:     /* RGBA */
      {
         m_numberOfInputBands  = 4;
         if (m_useAlphaChannelFlag)
         {
            m_numberOfOutputBands = 4;     
         }
         else
         {
            m_numberOfOutputBands = 3;    
         }         
         break;
      }
      case PNG_COLOR_TYPE_GRAY:          /* Grayscale */
      {
         m_numberOfInputBands = 1;
         m_numberOfOutputBands = 1;
         break;
      }  
      case PNG_COLOR_TYPE_GRAY_ALPHA:    /* Grayscale + alpha */
      {
         m_numberOfInputBands = 2;
         if (m_useAlphaChannelFlag)
         {
            m_numberOfOutputBands = 2;     
         }
         else
         {
            m_numberOfOutputBands = 1;
         }
        break;
      }
     case PNG_COLOR_TYPE_PALETTE:       /* Indexed */
     {
        m_numberOfInputBands  = 3;
        m_numberOfOutputBands = 3;
        break;
     }  
     default:                   /* Unknown type */
     {
        result = false;
     }
   }

   if ( result )
   {
      m_lineBufferSizeInBytes = png_get_rowbytes(m_pngReadPtr, m_pngReadInfoPtr);
      
      // Set the max pixel value.
      setMaxPixelValue();
      
      // Set to OSSIM_USHORT11 for use of specialized tile.
      if (m_maxPixelValue[0] == 2047.0)
      {
         m_outputScalarType = OSSIM_USHORT11;
      }

      // We're on row 0 or first line.
      m_currentRow = 0;
      
      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimPngReader::initReader DEBUG:"
            << "\nm_imageRect:                     " << m_imageRect
            << "\nm_bitDepth:                      " << int(m_bitDepth)
            << "\nm_pngColorType:                  "
            <<  getPngColorTypeString().c_str()
            << "\nm_numberOfInputBands:            " << m_numberOfInputBands
            << "\nm_numberOfOutputBands:           " << m_numberOfOutputBands
            << "\nm_bytePerPixelPerBand:           " << m_bytePerPixelPerBand
            << "\nm_lineBufferSizeInBytes:         " << m_lineBufferSizeInBytes
            << "\nm_interlacePasses:               " << m_interlacePasses
            << "\npalette expansion:                "
            << (expandFlag?"on":"off")
            << "\npacking (1,2,4 bit to one byte):  "
            << (packingFlag?"on":"off")
            << "\nm_readMode:                      " << m_readMode
            << "\nm_swapFlag:                      " << m_swapFlag
            << std::endl;
         
         for (ossim_uint32 band = 0; band < m_numberOfInputBands; ++band)
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "max[" << band << "]:  " << m_maxPixelValue[band]
               << std::endl;
         }
      }
   }

   return result;
   
} // End: ossimPngReader::initReader()
コード例 #30
0
void ossimRpfToc::copyFrames(std::ifstream& dotRpfStr, const ossimFilename& outputDir)
{
   static const char MODULE[] = "ossimRpfToc::copyFrames";

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   ossim_uint32 frames = getNumberOfFrames(dotRpfStr);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "frames to copy: " << frames << "\n";
   }
   
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }

   dotRpfStr.seekg(0, ios_base::beg);

   std::string line;
   ossimFilename file;
   ossimFilename destinationFile;
   ossimFilename subDir;
   ossim_uint32 framesCopied = 0;
            
   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);

   // Get the second line which is first file. 
   std::getline(dotRpfStr, line);

   // Get the file name and make the sub directory if needed.
   if ( getFile(line, file) )
   {
      destinationFile = outputDir;
      subDir = file.path();
      subDir = subDir.file();
      destinationFile = destinationFile.dirCat( subDir );
      
      // This is output_dir/subdir.  See if subdir exist:
      if ( !destinationFile.exists() )
      {
         destinationFile.createDirectory();
      }
   }

   // Start over:
   if ( !dotRpfStr.good() )
   {
      // see if we can clear it.  Someone might have hit end of file(eof).
      dotRpfStr.clear();
   }
   dotRpfStr.seekg(0, ios_base::beg);
   
   // Eat the first line which is the bounding rect line
   std::getline(dotRpfStr, line);
   
   while( dotRpfStr.good() )
   {
      std::getline(dotRpfStr, line);

      if ( dotRpfStr.good() )
      {
         if ( getFile(line, file) )
         {
            destinationFile = outputDir;
            subDir = file.path();
            subDir = subDir.file();
            destinationFile = destinationFile.dirCat( subDir );
            destinationFile = destinationFile.dirCat( file.file() );

            if ( file.copyFileTo(destinationFile) )
            {
               ++framesCopied;
            }
            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG) << "Copied frame: " << destinationFile << "\n";
            }
         }
      }
   }

   ossimNotify(ossimNotifyLevel_NOTICE) << "Frames copied: " << framesCopied << std::endl;

   dotRpfStr.clear();
   dotRpfStr.seekg(0, ios_base::beg);

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl;
   }
}