예제 #1
0
// Returns true if georeferenced ...all geocoded and georeferenced GeoTIFFs qualify
int isGeotiff(const char *file)
{
    TIFF *tiff = NULL;
    GTIF *gtif = NULL;
    int num_tie_points = 0;
    int num_pixel_scales = 0;
    double *tie_point = NULL;
    double *pixel_scale = NULL;

    tiff = XTIFFOpen (file, "r");
    if (tiff != NULL) {
        gtif = GTIFNew (tiff);
    }
    if (gtif) {
        (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &num_tie_points, &tie_point);
        (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &num_pixel_scales, &pixel_scale);
    }

    if (gtif &&
        num_tie_points == 6 && num_pixel_scales == 3 &&
        pixel_scale[0] > 0.0 && pixel_scale[1] > 0.0)
    {
        GTIFFree(gtif);
        XTIFFClose(tiff);
        FREE(tie_point);
        FREE(pixel_scale);
        return 1;
    }

    if (gtif) GTIFFree(gtif);
    if (tiff) XTIFFClose(tiff);
    FREE(tie_point);
    FREE(pixel_scale);
    return 0;
}
예제 #2
0
int main()
{
	char *fname = "newgeo.tif";
	TIFF *tif=(TIFF*)0;  /* TIFF-level descriptor */
	GTIF *gtif=(GTIF*)0; /* GeoKey-level descriptor */
	
	tif=XTIFFOpen(fname,"w");
	if (!tif) goto failure;
	
	gtif = GTIFNew(tif);
	if (!gtif)
	{
		printf("failed in GTIFNew\n");
		goto failure;
	}
	
	SetUpTIFFDirectory(tif);
	SetUpGeoKeys(gtif);
	WriteImage(tif);
	
	GTIFWriteKeys(gtif);
	GTIFFree(gtif);
	XTIFFClose(tif);
	return 0;
	
failure:
	printf("failure in makegeo\n");
	if (tif) TIFFClose(tif);
	if (gtif) GTIFFree(gtif);
	return -1;
}
예제 #3
0
파일: plyflatten.c 프로젝트: cpalmann/s2p
void set_geotif_header(char *tiff_fname, char *utm_zone, float xoff,
		float yoff, float scale)
{
	// open tiff file
	TIFF *tif = XTIFFOpen(tiff_fname, "r+");
	if (!tif)
		fail("failed in XTIFFOpen\n");

	GTIF *gtif = GTIFNew(tif);
	if (!gtif)
		fail("failed in GTIFNew\n");

	// write TIFF tags
	double pixsize[3] = {scale, scale, 0.0};
	TIFFSetField(tif, GTIFF_PIXELSCALE, 3, pixsize);

	double tiepoint[6] = {0.0, 0.0, 0.0, xoff, yoff, 0.0};
	TIFFSetField(tif, GTIFF_TIEPOINTS, 6, tiepoint);

	// write GEOTIFF keys
	int utm_ind = get_utm_zone_index_for_geotiff(utm_zone);
	GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, utm_ind);
	GTIFWriteKeys(gtif);

	// free and close
	GTIFFree(gtif);
	XTIFFClose(tif);
}
예제 #4
0
std::pair<UncompressedImage, GeoQuadrilateral>
LoadGeoTiff(Path path)
{
  TiffLoader tiff(path);

  GeoQuadrilateral bounds;

  {
    auto gtif = GTIFNew(tiff.Get());
    if (gtif == nullptr)
      throw std::runtime_error("Not a GeoTIFF file");

    AtScopeExit(gtif) { GTIFFree(gtif); };

    GTIFDefn defn;
    if (!GTIFGetDefn(gtif, &defn))
      throw std::runtime_error("Failed to parse GeoTIFF metadata");

    int width, height;
    tiff.GetField(TIFFTAG_IMAGEWIDTH, width);
    tiff.GetField(TIFFTAG_IMAGELENGTH, height);

    bounds.top_left = TiffPixelToGeoPoint(*gtif, defn, 0, 0);
    bounds.top_right = TiffPixelToGeoPoint(*gtif, defn, width, 0);
    bounds.bottom_left = TiffPixelToGeoPoint(*gtif, defn, 0, height);
    bounds.bottom_right = TiffPixelToGeoPoint(*gtif, defn, width, height);

    if (!bounds.Check())
      throw std::runtime_error("Invalid GeoTIFF bounds");
  }

  return std::make_pair(LoadTiff(tiff), bounds);
}
예제 #5
0
static void CopyGeoTIFF(TIFF * in, TIFF *out)
{
    GTIF *gtif=(GTIF*)0; /* GeoKey-level descriptor */
    double *d_list = NULL;
    int16   d_list_count;

    /* read definition from source file. */
    gtif = GTIFNew(in);
    if (!gtif)
        return;

    if (TIFFGetField(in, GTIFF_TIEPOINTS, &d_list_count, &d_list))
        TIFFSetField(out, GTIFF_TIEPOINTS, d_list_count, d_list);
    if (TIFFGetField(in, GTIFF_PIXELSCALE, &d_list_count, &d_list))
        TIFFSetField(out, GTIFF_PIXELSCALE, d_list_count, d_list);
    if (TIFFGetField(in, GTIFF_TRANSMATRIX, &d_list_count, &d_list))
        TIFFSetField(out, GTIFF_TRANSMATRIX, d_list_count, d_list);
            
    /* Here we violate the GTIF abstraction to retarget on another file.
       We should just have a function for copying tags from one GTIF object
       to another. */
    gtif->gt_tif = out;
    gtif->gt_flags |= FLAG_FILE_MODIFIED;

    /* Install keys and tags */
    GTIFWriteKeys(gtif);
    GTIFFree(gtif);
    return;
}
예제 #6
0
static void InstallGeoTIFF(TIFF *out)
{
    GTIF *gtif=(GTIF*)0; /* GeoKey-level descriptor */
    FILE *fd;

    gtif = GTIFNew(out);
    if (!gtif)
    {
        printf("failed in GTIFNew\n");
        return;
    }

    if( geofile )
    {
        /* Install keys and tags */
        fd = fopen(geofile,"r");
        if( fd == NULL )
        {
            perror( geofile );
            exit( -1 );
        }
        if (!GTIFImport(gtif,0,fd))
        {
            fprintf(stderr,"Failure in GTIFImport\n");
            exit (-1);
        }
        fclose(fd);
    }
    else if( proj4_string )
    {
        if( !GTIFSetFromProj4(gtif,proj4_string) )
        {
            fprintf(stderr,"Failure in GTIFSetFromProj4\n");
            exit (-1);
        }
    }
    GTIFWriteKeys(gtif);
    GTIFFree(gtif);
    return;
}
예제 #7
0
GTIF* GTIFNewWithMethods(void *tif, TIFFMethod* methods)
{
    GTIF* gt=(GTIF*)0;
    int count,bufcount,index;
    GeoKey *keyptr;
    pinfo_t *data;
    KeyEntry *entptr;
    KeyHeader *header;
    TempKeyData tempData;

    memset( &tempData, 0, sizeof(tempData) );
    gt = (GTIF*)_GTIFcalloc( sizeof(GTIF));
    if (!gt) goto failure;	
	
    /* install TIFF file and I/O methods */
    gt->gt_tif = (tiff_t *)tif;
    memcpy( &gt->gt_methods, methods, sizeof(TIFFMethod) );

    /* since this is an array, GTIF will allocate the memory */
    if ( tif == NULL 
         || !(gt->gt_methods.get)(tif, GTIFF_GEOKEYDIRECTORY, &gt->gt_nshorts, &data ))
    {
        /* No ProjectionInfo, create a blank one */
        data=(pinfo_t*)_GTIFcalloc((4+MAX_VALUES)*sizeof(pinfo_t));
        if (!data) goto failure;	
        header = (KeyHeader *)data;
        header->hdr_version = GvCurrentVersion;
        header->hdr_rev_major = GvCurrentRevision;
        header->hdr_rev_minor = GvCurrentMinorRev;
        gt->gt_nshorts=sizeof(KeyHeader)/sizeof(pinfo_t);
    }
    else
    {
        /* resize data array so it can be extended if needed */
        data = (pinfo_t*) _GTIFrealloc(data,(4+MAX_VALUES)*sizeof(pinfo_t));
    }
    gt->gt_short = data;
    header = (KeyHeader *)data;
	
    if (header->hdr_version > GvCurrentVersion) goto failure;
    if (header->hdr_rev_major > GvCurrentRevision)
    {
        /* issue warning */
    }
	
    /* If we got here, then the geokey can be parsed */
    count = header->hdr_num_keys;

    if (count * sizeof(KeyEntry) >= (4 + MAX_VALUES) * sizeof(pinfo_t)) 
        goto failure; 

    gt->gt_num_keys = count;
    gt->gt_version  = header->hdr_version;
    gt->gt_rev_major  = header->hdr_rev_major;
    gt->gt_rev_minor  = header->hdr_rev_minor;

    bufcount = count+MAX_KEYS; /* allow for expansion */

    /* Get the PARAMS Tags, if any */
    if (tif == NULL
        || !(gt->gt_methods.get)(tif, GTIFF_DOUBLEPARAMS,
                                 &gt->gt_ndoubles, &gt->gt_double ))
    {
        gt->gt_double=(double*)_GTIFcalloc(MAX_VALUES*sizeof(double));
        if (!gt->gt_double) goto failure;	
    }
    else
    {
        /* resize data array so it can be extended if needed */
        gt->gt_double = (double*) _GTIFrealloc(gt->gt_double,
                                               (MAX_VALUES)*sizeof(double));
    }
    if ( tif == NULL
         || !(gt->gt_methods.get)(tif, GTIFF_ASCIIPARAMS,
                                  &tempData.tk_asciiParamsLength,
                                  &tempData.tk_asciiParams ))
    {
        tempData.tk_asciiParams         = 0;
        tempData.tk_asciiParamsLength   = 0;
    }
    else
    {
        /* last NULL doesn't count; "|" used for delimiter */
        --tempData.tk_asciiParamsLength;
    }

    /* allocate space for GeoKey array and its index */
    gt->gt_keys = (GeoKey *)_GTIFcalloc( sizeof(GeoKey)*bufcount);
    if (!gt->gt_keys) goto failure;
    gt->gt_keyindex = (int *)_GTIFcalloc( sizeof(int)*(MAX_KEYINDEX+1));
    if (!gt->gt_keyindex) goto failure;
	
    /*  Loop to get all GeoKeys */
    entptr = ((KeyEntry *)data) + 1;
    keyptr = gt->gt_keys;
    gt->gt_keymin = MAX_KEYINDEX;
    gt->gt_keymax = 0;
    for (index=1; index<=count; index++,entptr++)
    {
        if (!ReadKey(gt, &tempData, entptr, ++keyptr))
            goto failure;
			
        /* Set up the index (start at 1, since 0=unset) */
        gt->gt_keyindex[entptr->ent_key] = index;		
    }

    if( tempData.tk_asciiParams != NULL )
        _GTIFFree( tempData.tk_asciiParams );
	
    return gt;
	
  failure:
    /* Notify of error */
    if( tempData.tk_asciiParams != NULL )
        _GTIFFree( tempData.tk_asciiParams );    
    GTIFFree (gt);
    return (GTIF *)0;
}
예제 #8
0
int isgeotiff(char *inFile)
{
    FILE *fp;
    TIFF *tiff=NULL;
    GTIF *gtif=NULL;
    int isGeotiff = 0;
    char magic[2];

    fp = fopen(inFile, "r");
    if (!fp) {
        char n[1024];
        sprintf(n, "%s.tif", inFile);
        fp = fopen(n, "r");
    }
    if (!fp) {
        char *basename = get_basename(inFile);
        char n[1024];
        sprintf(n, "%s.tif", basename);
        fp = fopen(n, "r");
        FREE(basename);
    }
    if (!fp) {
        char *basename = get_basename(inFile);
        char n[1024];
        sprintf(n, "%s.tiff", basename);
        fp = fopen(n, "r");
        FREE(basename);
    }
    if (fp) {
        magic[0] = fgetc(fp);
        magic[1] = fgetc(fp);
        if ((magic[0] == 'I' && magic[1] == 'I') ||
            (magic[0] == 'M' && magic[1] == 'M')  )
        {
            // Looks like a TIFF file, so let's see if it's a GeoTIFF file
            tiff = XTIFFOpen(inFile, "r");
            if (!tiff) isGeotiff = 0; // Not a TIFF (or GeoTIFF) file ...rare if the magic bytes were correct.
            if (tiff) gtif = GTIFNew(tiff);
            if (tiff && !gtif) isGeotiff = 0; // Usually GTIFNew() succeeds even if not a GeoTIFF ...

            if (tiff && gtif) {
                double *tie_point=NULL;
                double *pixel_scale=NULL;
                int tp_count=0, ps_count=0;
                (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &tp_count, &tie_point);
                (gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &ps_count, &pixel_scale);

                if (tie_point && pixel_scale && tp_count == 6 && ps_count == 3) {
                    // Assume that if tie points and pixel scales exist that the file is a
                    // GeoTIFF ...it's still possible that read_generic_geotiff_metadata() will
                    // fail due to the file only being a georeferenced rather than a geocoded
                    // GeoTIFF, but that's a different problem...
                    isGeotiff = 1;
                }
                FREE(tie_point);
                FREE(pixel_scale);
            }

            if (gtif) GTIFFree(gtif);
            if (tiff) XTIFFClose(tiff);
        }
        fclose(fp);
    }

    return isGeotiff;
}
예제 #9
0
int main(int argc, char *argv[])
{
    char	*fname = NULL;
    TIFF 	*tif=(TIFF*)0;  /* TIFF-level descriptor */
    GTIF	*gtif=(GTIF*)0; /* GeoKey-level descriptor */
    int		i, norm_print_flag = 1, proj4_print_flag = 0;
    int		tfw_flag = 0, inv_flag = 0, dec_flag = 0;

    /*
     * Handle command line options.
     */
    for( i = 1; i < argc; i++ )
    {
        if( strcmp(argv[i],"-no_norm") == 0 )
            norm_print_flag = 0;
        else if( strcmp(argv[i],"-t") == 0 )
        {
            CSVDirName = argv[++i];
            SetCSVFilenameHook( CSVFileOverride );
        }
        else if( strcmp(argv[i],"-tfw") == 0 )
            tfw_flag = 1;
        else if( strcmp(argv[i],"-proj4") == 0 )
            proj4_print_flag = 1;
        else if( strcmp(argv[i],"-i") == 0 )
            inv_flag = 1;
        else if( strcmp(argv[i],"-d") == 0 )
            dec_flag = 1;
        else if( fname == NULL && argv[i][0] != '-' )
            fname = argv[i];
        else
        {
            Usage();
        }
    }

    if( fname == NULL )
        Usage();

    /*
     * Open the file, read the GeoTIFF information, and print to stdout. 
     */

    tif=XTIFFOpen(fname,"r");
    if (!tif) goto failure;
	
    gtif = GTIFNew(tif);
    if (!gtif)
    {
        fprintf(stderr,"failed in GTIFNew\n");
        goto failure;
    }

    if( tfw_flag )
    {
        WriteTFWFile( gtif, fname );

        goto Success;
    }
	
    /* dump the GeoTIFF metadata to std out */

    GTIFPrint(gtif,0,0);

    /*
     * Capture, and report normalized information if requested.
     */

    if( norm_print_flag )
    {
        GTIFDefn	defn;
        
        if( GTIFGetDefn( gtif, &defn ) )
        {
            int		xsize, ysize;
            
            printf( "\n" );
            GTIFPrintDefn( &defn, stdout );

            if( proj4_print_flag )
            {
                printf( "\n" );
                printf( "PROJ.4 Definition: %s\n", GTIFGetProj4Defn(&defn));
            }
            
            TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &xsize );
            TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &ysize );
            GTIFPrintCorners( gtif, &defn, stdout, xsize, ysize, inv_flag, dec_flag );
        }

    }

  Success:
    GTIFFree(gtif);
    XTIFFClose(tif);
    return 0;
		
  failure:
    fprintf(stderr,"failure in listgeo\n");
    if (tif) XTIFFClose(tif);
    if (gtif) GTIFFree(gtif);
    return 1;
}
예제 #10
0
int main(int argc, char *argv[])
{
    char	*fname = NULL;
    char        *outfile = NULL;
    TIFF 	*tif=(TIFF*)0;  /* TIFF-level descriptor */
    GTIF	*gtif=(GTIF*)0; /* GeoKey-level descriptor */
    int		i, j, norm_print_flag = 0, proj4_print_flag = 0;
    int		tfw_flag = 0, inv_flag = 0, dec_flag = 1;
    int         st_test_flag = 0;
    size_t npixels;
    int16* elevations;
    int x, y, skip;
    GTIFDefn	defn;
    FILE* out;

    /*
     * Handle command line options.
     */
    for( i = 1; i < argc; i++ )
    {
        if( fname == NULL && argv[i][0] != '-' )
            fname = argv[i];
        else
        {
            Usage();
        }
    }
    if( fname == NULL)
        Usage();

    skip = 5;

    /*
     * Open the file, read the GeoTIFF information, and print to stdout. 
     */
    int flength = strlen(fname);
    outfile = (char *) malloc(flength);
    strncpy(outfile,fname,flength-4);
    strcat(outfile, ".asc\0");
    out = fopen(outfile, "w");
    printf("Writing to %s\n\n",outfile);
    free(outfile);

    tif=XTIFFOpen(fname,"r");
    if (!tif) goto failure;
    
    gtif = GTIFNew(tif);
    if (!gtif)
      {
	fprintf(stderr,"failed in GTIFNew\n");
	goto failure;
      }
	
    /* dump the GeoTIFF metadata to std out */

    GTIFPrint(gtif,0,0);

    if( GTIFGetDefn( gtif, &defn ) )
      {
	uint32		xsize, ysize;
        
	printf( "\n" );
	GTIFPrintDefn( &defn, stdout );
	
	if( proj4_print_flag )
	  {
	    printf( "\n" );
	    printf( "PROJ.4 Definition: %s\n", GTIFGetProj4Defn(&defn));
	  }
	int count, orient;
	double* data;
	TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &xsize );
	TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &ysize );
	TIFFGetField( tif, TIFFTAG_GEOPIXELSCALE, &count, &data);
	TIFFGetField( tif, TIFFTAG_ORIENTATION, &orient );
	printf("Orientation:%d\n",orient);

	GTIFPrintCorners( gtif, &defn, stdout, xsize, ysize, inv_flag, dec_flag );
	const char* project = "ASTERGDEM";
	const char* yymmdd = "090629";
	double originx, originy;
	GTIFImageToPCS( gtif, &originx, &originy);
	int lat = (int)originy*1000;
	int lon = (int)originx*1000;
	int xmin = 0;
	int ymin = 0;
	int nx = xsize/skip + 1;
	int ny = ysize/skip + 1;
	int dx = 30 * skip;
	int dy = 30 * skip;
	int16 elev = 0;
	fprintf(out, "%12s%12s%7d%7d%7d%7d%7d%7d%7d%7d\n",
	       project, yymmdd, lat, lon, xmin, ymin, nx, ny, dx,dy);
	npixels = xsize * ysize;
	int16* buf;
	tsample_t sample;
	int nbytes;
	nbytes = TIFFScanlineSize(tif);
	buf = (int16*) _TIFFmalloc(nbytes);
	elevations = (int16*) _TIFFmalloc(npixels * sizeof (int16));
	if (elevations != NULL) {
	    for( y = 0; y < ysize; y++ )
	      {
		uint32 row = ysize - 1 - y;
		TIFFReadScanline(tif, buf, row, sample);
		for( x = 0; x < xsize; x++ ) 
		  {
		    elevations[y*xsize + x] = buf[x];
		  }
	      }	    
	  _TIFFfree(buf);
	}
	for( y = 0; y < ysize; y+=skip ) {
	  for( x = 0; x < xsize; x+=skip ) {
	    fprintf(out, "%6d", elevations[y*xsize + x]);
	  }
	  fprintf(out, "\n");
	}
	_TIFFfree(elevations);

      }
    
  Success:
    GTIFFree(gtif);
    if( st_test_flag )
        ST_Destroy( (ST_TIFF *) tif );
    else
        XTIFFClose(tif);
    GTIFDeaccessCSV();
    return 0;
		
  failure:
    fprintf(stderr,"failure in listgeo\n");
    if (tif) XTIFFClose(tif);
    if (gtif) GTIFFree(gtif);
    GTIFDeaccessCSV();
    return 1;
}
예제 #11
0
bool TiffDetails::addGeoKeys(TIFF* pOut, int width, int height, const SessionItem *pItem)
{
   if ((pOut == NULL) || (width == 0) || (height == 0))
   {
      return false;
   }

   const View* pInputView = dynamic_cast<const View*>(pItem);
   if (pInputView == NULL)
   {
      return false;
   }

   RasterElement* pGeoreferencedRaster = NULL; // First raster element we find with georeferencing information
   const ProductView* pView = dynamic_cast<const ProductView*>(pInputView);
   if (pView != NULL)
   {
      AnnotationLayer* pAnno = pView->getLayoutLayer();
      if (pAnno == NULL)
      {
         return false;
      }

      /* NOTE: If we find more than one SpatialDataView with a georeferenced RasterElement, we will only provide
      geo-data for the FIRST one - because two views could theoretically screw up the
      geo-data if one is in Australia and the other in Canada.
      */

      // get all the view objects
      std::list<GraphicObject*> objs;
      pAnno->getObjects(VIEW_OBJECT, objs);

      // for every object, find the data set with a geocoord matrix
      for (std::list<GraphicObject*>::iterator it = objs.begin(); it != objs.end(); ++it)
      {
         GraphicObject* pObj = *it;
         if (pObj != NULL)
         {
            SpatialDataView* pSpView = dynamic_cast<SpatialDataView*>(pObj->getObjectView());
            if (pSpView != NULL)
            {
               LayerList* pLayerList = pSpView->getLayerList();
               if (pLayerList != NULL)
               {
                  RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
                  if (pRaster != NULL && pRaster->isGeoreferenced())
                  {
                     pGeoreferencedRaster = pRaster;
                     break;
                  }
               }
            }
         }
      }
   }

   const SpatialDataView* pSpView = dynamic_cast<const SpatialDataView*>(pInputView);
   if (pSpView != NULL)
   {
      LayerList* pLayerList = pSpView->getLayerList();
      if (pLayerList != NULL)
      {
         RasterElement* pRaster = pLayerList->getPrimaryRasterElement();
         if (pRaster != NULL && pRaster->isGeoreferenced())
         {
            pGeoreferencedRaster = pRaster;
         }
      }
   }

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

   GTIF* pGtif = GTIFNew(pOut);
   if (pGtif == NULL)
   {
      return false;
   }

   LocationType lowerLeft;
   LocationType upperLeft;
   LocationType upperRight;
   LocationType lowerRight;
   pInputView->getVisibleCorners(lowerLeft, upperLeft, upperRight, lowerRight);

   LocationType latLong;
   //get the lat/long's (0,0)
   latLong = pGeoreferencedRaster->convertPixelToGeocoord(upperLeft);
   double ll1y = latLong.mY;               //delta long
   double ll1x = latLong.mX;               //delta lat

   latLong = pGeoreferencedRaster->convertPixelToGeocoord(upperRight);
   double ll2y = latLong.mY;               //long
   double ll2x = latLong.mX;               //lat

   latLong = pGeoreferencedRaster->convertPixelToGeocoord(lowerLeft);
   double ll3y = latLong.mY;               //long
   double ll3x = latLong.mX;               //lat

   //compute transformation Matrix values
   //added slight modification, must divide by magnitude
   double a = (ll2y - ll1y) / width;
   double b = (ll3y - ll1y) / height;
   double d = (ll1y);
   double e = (ll2x - ll1x) / width;
   double f = (ll3x - ll1x) / height;
   double h = (ll1x);

   double tMatrix[16] =
   {
      a,   b,   0.0, d,
      e,   f,   0.0, h,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.0
   };

   TIFFSetField(pOut, GTIFF_TRANSMATRIX, 16, tMatrix);

   GTIFKeySet(pGtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsArea);
   GTIFKeySet(pGtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelGeographic);
   GTIFKeySet(pGtif, GeographicTypeGeoKey, TYPE_SHORT, 1, GCS_WGS_84);

   // Here we violate the GTIF abstraction to retarget on another file.
   // We should just have a function for copying tags from one GTIF object
   // to another.
   pGtif->gt_tif = pOut;
   pGtif->gt_flags |= FLAG_FILE_MODIFIED;

   // Install keys and tags
   GTIFWriteKeys(pGtif);
   GTIFFree(pGtif);
   return true;
}
예제 #12
0
bool	FetchTIFFCornersWithTIFF(TIFF * tiffFile, double corners[8], int& post_pos, int width, int height)
{
	bool retVal = false;
	GTIF * gtif = GTIFNew(tiffFile);
	if (gtif)
	{
//		GTIFPrint(gtif, pm, NULL);

		GTIFDefn 	defn;
        if( GTIFGetDefn( gtif, &defn ) )
        {
        	int xs, ys;
			double xsize,ysize;
            TIFFGetField( tiffFile, TIFFTAG_IMAGEWIDTH, &xs );
            TIFFGetField( tiffFile, TIFFTAG_IMAGELENGTH, &ys );

			uint16 pixel_type;
			double dx=0.0;
			double dy=0.0;

			//If there is the optional width and height
			if(width > 0 && height > 0)
			{
				xsize=width;
				ysize=height;
			}
			else
			{
				xsize=xs;
				ysize=ys;
			}

			if (GTIFKeyGet(gtif,GTRasterTypeGeoKey, &pixel_type, 0, 1) != 1)
				pixel_type=RasterPixelIsArea;

			// If we are a 'point sampled' file, the upper right edge _IS_ the last pixels!  Thus
			// passing in the number of pixels induces an off-by-one.  Cut the size by one to fix this.
			if(pixel_type == RasterPixelIsPoint)
			{
				xsize -= 1.0;
				ysize -= 1.0;
			}

			if(pixel_type==RasterPixelIsArea && post_pos == dem_want_Post)
			{
				// This is an area-pixel DEM, but we are going to reinterpret it via pixel centers.
				// This will INSET the corners of the pixels by 1/2 pixel to the sample centers.
				dx=0.5;
				dy=0.5;
			}

			if(pixel_type==RasterPixelIsPoint && post_pos == dem_want_Area)
			{
				// This is a center post sampled image, but we are going to treat it as area.  Each
				// pixel "sticks out" a bit in its coverage, so extend.
				dx=-0.5;
				dy=-0.5;
			}

			if(post_pos == dem_want_File)
				post_pos = (pixel_type==RasterPixelIsPoint) ? dem_want_Post : dem_want_Area;

        	if (TransformTiffCorner(gtif, &defn,	   dx, ysize-dy, corners[0], corners[1]) &&
	        	TransformTiffCorner(gtif, &defn, xsize-dx, ysize-dy, corners[2], corners[3]) &&
	        	TransformTiffCorner(gtif, &defn,	   dx,		 dy, corners[4], corners[5]) &&
	        	TransformTiffCorner(gtif, &defn, xsize-dx,		 dy, corners[6], corners[7]))
	        {
				// Ben says: we used to snap round.  Since the 'far' tie point is calculated by res * pixels
				// and res might be 1/1200 or 1/1201, we get floating point crud in our tiff calcs.  But
				// if we aren't known to be on 1-degree boundaries, this snap rounding is just wrong.  So:
				// don't round - we need good precision in other places.  Instead, we can round in the raster-import cmd.
//				corners[0]=round_by_parts_guess(corners[0],xs);
//				corners[2]=round_by_parts_guess(corners[2],xs);
//				corners[4]=round_by_parts_guess(corners[4],xs);
//				corners[6]=round_by_parts_guess(corners[6],xs);
//
//				corners[1]=round_by_parts_guess(corners[1],ys);
//				corners[3]=round_by_parts_guess(corners[3],ys);
//				corners[5]=round_by_parts_guess(corners[5],ys);
//				corners[7]=round_by_parts_guess(corners[7],ys);


	        	retVal = true;
	        }
		}
		GTIFFree(gtif);
	}
	return retVal;
}
예제 #13
0
static int
InstallGeoTIFF(const char *geofile, const char *tiffile)
{
    TIFF *tif = (TIFF*)0; /* TIFF-level descriptor */
    GTIF *gtif=(GTIF*)0; /* GeoKey-level descriptor */
    FILE *fp;

    uint16 *panVI = NULL;
    uint16 nKeyCount;
     
    tif = XTIFFOpen(tiffile, "r+");
    if (!tif)
    {
        perror(tiffile);
        fprintf(stderr, "Cannot open TIFF file %s (does not exist or not a valid TIFF file)\n", tiffile);
        return(-1);
    }

    /* If we have existing geokeys, try to wipe them
    by writing a dummy geokey directory. (#2546) */


    if( TIFFGetField( tif, TIFFTAG_GEOKEYDIRECTORY, 
                      &nKeyCount, &panVI ) )
    {
        uint16 anGKVersionInfo[4] = { 1, 1, 0, 0 };
        double  adfDummyDoubleParams[1] = { 0.0 };

        TIFFSetField( tif, TIFFTAG_GEOKEYDIRECTORY, 
                      4, anGKVersionInfo );
        TIFFSetField( tif, TIFFTAG_GEODOUBLEPARAMS, 
                      1, adfDummyDoubleParams );
        TIFFSetField( tif, TIFFTAG_GEOASCIIPARAMS, "" );
    }

    gtif = GTIFNew(tif);
    if (!gtif)
    {
        fprintf(stderr, "Internal error (GTIFNew)\n");
        return(-2);
    }
 
    /* Read GeoTIFF projection information from geofile */
    fp = fopen(geofile, "r");
    if( fp == NULL )
    {
        perror( geofile );
        fprintf(stderr, "Cannot open projection definition file %s\n", geofile);
        return(-3);
    }
    if (!GTIFImport(gtif, 0, fp))
    {
        fprintf(stderr,"Projection definition file is not valid (%s)\n", geofile);
        return(-4);
    }
    fclose(fp);
 
    /* Install GeoTIFF keys into the TIFF file */
    GTIFWriteKeys(gtif);
 
    /* Clean up */
    GTIFFree(gtif);
    TIFFRewriteDirectory(tif);
    XTIFFClose(tif);
    return(0);
}
예제 #14
0
bool DEM::readDem(char* fname) 
{

    demFilename = fname;
    TIFF 	*tif=(TIFF*)0;  /* TIFF-level descriptor */
    GTIF	*gtif=(GTIF*)0; /* GeoKey-level descriptor */
    int	proj4_print_flag = 0;
    int	inv_flag = 0, dec_flag = 1;
    int      st_test_flag = 0;
    GTIFDefn	defn;

    /*
     * Open the file, read the GeoTIFF information, and print some info to stdout. 
     */
	
    tif=XTIFFOpen(fname,"r");
    if (!tif) goto failure;
    
    gtif = GTIFNew(tif);
    if (!gtif)
	{
		fprintf(stderr,"failed in GTIFNew\n");
		goto failure;
	}
	
    /* dump the GeoTIFF metadata to std out */
	
    GTIFPrint(gtif,0,0);
	
    if( GTIFGetDefn( gtif, &defn ) )
	{
		printf( "\n" );
		GTIFPrintDefn( &defn, stdout );
		
		if( proj4_print_flag )
		{
			printf( "\n" );
			printf( "PROJ.4 Definition: %s\n", GTIFGetProj4Defn(&defn));
		}
		int count, orient;
		double* data;
		TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &xsize );
		TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &ysize );
		TIFFGetField( tif, TIFFTAG_GEOPIXELSCALE, &count, &data);
		TIFFGetField( tif, TIFFTAG_ORIENTATION, &orient );
		printf("Orientation:%d\n",orient);
		
		GTIFPrintCorners( gtif, &defn, stdout, xsize, ysize, inv_flag, dec_flag );
		double originx = 0.0;
		double originy = ysize;
		GTIFImageToPCS( gtif, &originx, &originy);
		refLat = originy;
		refLon = originx;
		npixels = xsize * ysize;
		int16* buf;
		tsample_t sample;
		int nbytes;
		nbytes = TIFFScanlineSize(tif);
		buf = (int16*) _TIFFmalloc(nbytes);
		elevations = (int16*) _TIFFmalloc(npixels * sizeof (int16));
		if (elevations != NULL) {
			for(unsigned int y = 0; y < ysize; y++ )
			{
				uint32 row = ysize - 1 - y;
				TIFFReadScanline(tif, buf, row, sample);
				for(unsigned int x = 0; x < xsize; x++ ) 
				{
					elevations[y*xsize + x] = buf[x];
				}
			}	    
			_TIFFfree(buf);
		}
		_TIFFfree(elevations);
		
	}
    

    GTIFFree(gtif);
    if( st_test_flag )
        ST_Destroy( (ST_TIFF *) tif );
    else
        XTIFFClose(tif);
    GTIFDeaccessCSV();
    return true;
	
failure:
    fprintf(stderr,"failure in listgeo\n");
    if (tif) XTIFFClose(tif);
    if (gtif) GTIFFree(gtif);
    GTIFDeaccessCSV();
    return false;
}
예제 #15
0
void import_radarsat2(const char *inBaseName, radiometry_t radiometry,
		      const char *outBaseName, int ampOnly)
{
  FILE *fp;
  radarsat2_meta *radarsat2;
  meta_parameters *meta;
  char **inDataNames=NULL, inDataName[1024], *inMetaName=NULL;
  char *outDataName=NULL, str[512];
  float *amp = NULL, *phase = NULL, *tmp = NULL, re, im;
  int band, sample;

  // Check radiometry
  if (radiometry != r_AMP) {
    asfPrintWarning("Radiometry other than AMPLITUDE is currently not "
		    "supported.\n");
    radiometry = r_AMP;
  }
  
  if (!fileExists(inBaseName))
    inMetaName = appendExt(inBaseName, ".xml");
  else {
    inMetaName = (char *) MALLOC(sizeof(char)*1024);
    strcpy(inMetaName, inBaseName);
  }
  outDataName = appendExt(outBaseName, ".img");

  radarsat2 = read_radarsat2_meta(inMetaName);
  asfPrintStatus("   DataType: %s, ProductType: %s\n",
		 radarsat2->dataType, radarsat2->productType);
  if (strcmp_case(radarsat2->dataType, "COMPLEX") != 0)
    asfPrintError("Currently only complex data supported!\n");
  meta = radarsat2meta(radarsat2);
  meta_write(meta, outDataName);

  // Let's check the GeoTIFF data.
  // Unfortunately, there is no identifier in the GeoTIFF that would identify
  // the data as Radarsat-2 data.
  //
  // The only thing that we can actually do is to look whether the data in the
  // GeoTIFF file fit the general bill. We can the image dimensions. The data
  // needs to have 2 bands (I and Q) and 16 bit. The citation geokey needs to
  // be the really non-descriptive "Uncorrected Satellite Data".

  TIFF *tiff = NULL;
  GTIF *gtif = NULL;
  data_type_t data_type;
  short sample_format, bits_per_sample, planar_config;
  short num_bands;
  int is_scanline_format, is_palette_color_tiff, wrong=FALSE;
  char *error_message = (char *) MALLOC(sizeof(char)*2048);

  inDataNames = extract_band_names(meta->general->basename, 
				   meta->general->band_count);
  fp = FOPEN(outDataName, "wb");

  int band_count = radarsat2->band_count;
  if (ampOnly) {
    strcpy(meta->general->bands, "AMP");
    meta->general->band_count = 1;
    band_count = 1;
  }
  for (band=0; band<band_count; band++) {

    // path from the xml (metadata) file
    char *path = get_dirname(inBaseName);
    if (strlen(path)>0) {
      strcpy(inDataName, path);
      if (inDataName[strlen(inDataName)-1] != '/')
        strcat(inDataName, "/");
    }
    else
      strcpy(inDataName, "");
    free(path);
    strcat(inDataName, inDataNames[band]);

    tiff = XTIFFOpen(inDataName, "r");
    if (!tiff)
      asfPrintError("Could not open data file (%s)\n", inDataName);
    gtif = GTIFNew(tiff);
    if (!gtif)
      asfPrintError("Could not read GeoTIFF keys from data file (%s)\n",
		    inDataName);

    // Check image dimensions
    uint32 tif_sample_count;
    uint32 tif_line_count;

    TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &tif_line_count);
    TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &tif_sample_count);
    if ((meta->general->sample_count != tif_sample_count) ||
	(meta->general->line_count != tif_line_count))
      asfPrintError(error_message, 
		    "Problem with image dimensions. Was looking for %d lines "
		    "and %d samples.\nFound %ld lines and %ld samples instead!"
		    "\n", 
		    meta->general->line_count, meta->general->sample_count, 
		    tif_line_count, tif_sample_count);

    // Check general TIFF tags
    get_tiff_data_config(tiff, &sample_format, &bits_per_sample, &planar_config,
			 &data_type, &num_bands, &is_scanline_format, 
			 &is_palette_color_tiff, REPORT_LEVEL_WARNING);

    // The specs say the data is supposed to be unsigned but it is not.
    // Let is pass as long as we are talking about integer data here
    strcpy(error_message, "");
    if (sample_format != SAMPLEFORMAT_UINT && 
	sample_format != SAMPLEFORMAT_INT) {
      strcat(error_message, 
	     "Problem with sampling format. Was looking for integer, ");
      if (sample_format == SAMPLEFORMAT_COMPLEXIEEEFP)
	strcat(error_message, "found complex floating point instead!\n");
      else if (sample_format == SAMPLEFORMAT_COMPLEXINT)
	strcat(error_message, "found complex integer instead!\n");
      else if (sample_format == SAMPLEFORMAT_IEEEFP)
	strcat(error_message, "found floating point instead!\n");
      else if (sample_format == SAMPLEFORMAT_VOID)
	strcat(error_message, "found void instead!\n");
      wrong = TRUE;
    }
    if (bits_per_sample != 16) {
      sprintf(str, "Problem with bits per sample. Was looking for 16, found %d "
	      "instead!\n", bits_per_sample);
      strcat(error_message, str);
      wrong = TRUE;
    }
    if (data_type != INTEGER16) {
      strcat(error_message, "Problem with data type. Was looking INTEGER16, ");
      if (data_type == ASF_BYTE)
	strcat(error_message, "found BYTE instead!\n");
      else if (data_type == INTEGER32)
	strcat(error_message, "found INTEGER32 instead!\n");
      else if (data_type == REAL32)
	strcat(error_message, "found REAL32 instead!\n");
      else if (data_type == REAL64)
	strcat(error_message, "found REAL64 instead!\n");
      else if (data_type == COMPLEX_BYTE)
	strcat(error_message, "found COMPLEX_BYTE instead!\n");
      else if (data_type == COMPLEX_INTEGER16)
	strcat(error_message, "found COMPLEX_INTEGER16 instead!\n");
      else if (data_type == COMPLEX_INTEGER32)
	strcat(error_message, "found COMPLEX_INTEGER32 instead!\n");
      else if (data_type == COMPLEX_REAL32)
	strcat(error_message, "found COMPLEX_REAL32 instead!\n");
      else if (data_type == COMPLEX_REAL64)
	strcat(error_message, "found COMPLEX_REAL64 instead!\n");
      wrong = TRUE;
    }
    if (num_bands != 2) {
      sprintf(str, "Problem with number of bands. Was looking for 2, "
	      "found %d instead!\n", num_bands);
      strcat(error_message, str);
      wrong = TRUE;
    }
    if (wrong)
      asfPrintError(error_message);

    // Check GTCitationGeoKey
    char *citation = NULL;
    int citation_length, typeSize;
    tagtype_t citation_type;

    citation_length = GTIFKeyInfo(gtif, GTCitationGeoKey, &typeSize,
				  &citation_type);
    if (citation_length > 0) {
      citation = (char *) MALLOC(citation_length * typeSize);
      GTIFKeyGet(gtif, GTCitationGeoKey, citation, 0, citation_length);
      if (citation && 
	  strcmp_case(citation, "UNCORRECTED SATELLITE DATA") != 0) {
	asfPrintError("Problem with GTCitationGeoKey. Was looking for "
		      "'Uncorrected Satellite Data',\nfound '%s' instead!\n", 
		      citation);
      }
    }
    else
      asfPrintError("Problem with GTCitationGeoKey. Was looking for "
		    "'Uncorrected Satellite Data',\ndid not find any key!\n");

    tiff_type_t tiffInfo;
    get_tiff_type(tiff, &tiffInfo);
    if (tiffInfo.format != SCANLINE_TIFF &&
	tiffInfo.format != STRIP_TIFF    &&
	tiffInfo.format != TILED_TIFF)
      asfPrintError("Can't read the GeoTIFF file (%s). Unrecognized TIFF "
		    "type!\n", inDataNames[band]);

    // If we made it here, we are reasonably sure that we have the file that
    // we are looking for.
    asfPrintStatus("\n   Importing %s ...\n", inDataNames[band]);

    uint32 scanlineSize = TIFFScanlineSize(tiff);
    tdata_t *tiff_real_buf = _TIFFmalloc(scanlineSize);
    tdata_t *tiff_imag_buf = _TIFFmalloc(scanlineSize);
    if (!tiff_real_buf || !tiff_imag_buf)
      asfPrintError("Can't allocate buffer for reading TIFF lines!\n");

    amp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);
    phase = (float *) MALLOC(sizeof(float)*meta->general->sample_count);

    // Check whether we need to flip the image in any fashion
    int flip_vertical = FALSE;
    if (strcmp_case(radarsat2->lineTimeOrdering, "DECREASING") == 0) {
      asfPrintStatus("   Data will be flipped vertically while ingesting!\n");
      flip_vertical = TRUE;
    }
    int flip_horizontal = FALSE;
    if (strcmp_case(radarsat2->pixelTimeOrdering, "DECREASING") == 0) {
      asfPrintStatus("   Data will be flipped horizontally while ingesting!\n");
      flip_horizontal = TRUE;
    }
    if (flip_horizontal)
      tmp = (float *) MALLOC(sizeof(float)*meta->general->sample_count);

    // FIXME: still need to implement flipping vertically
    // Read file line by line
    uint32 row;
    int sample_count = meta->general->sample_count;
    int line_count = meta->general->line_count;
    for (row=0; row<(uint32)meta->general->line_count; row++) {
      asfLineMeter(row, meta->general->line_count);
      if (flip_vertical) {
	switch (tiffInfo.format) 
	  {
	  case SCANLINE_TIFF:
	    TIFFReadScanline(tiff, tiff_real_buf, line_count-row-1, 0);
	    TIFFReadScanline(tiff, tiff_imag_buf, line_count-row-1, 1);
	    break;
	  case STRIP_TIFF:
	    ReadScanline_from_TIFF_Strip(tiff, tiff_real_buf, 
					 line_count-row-1, 0);
	    ReadScanline_from_TIFF_Strip(tiff, tiff_imag_buf, 
					 line_count-row-1, 1);
	    break;
	  case TILED_TIFF:
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_real_buf, 
					   line_count-row-1, 0);
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_imag_buf, 
					   line_count-row-1, 1);
	    break;
	  default:
	    asfPrintError("Can't read this TIFF format!\n");
	    break;
	  }
      }
      else {
	switch (tiffInfo.format) 
	  {
	  case SCANLINE_TIFF:
	    TIFFReadScanline(tiff, tiff_real_buf, row, 0);
	    TIFFReadScanline(tiff, tiff_imag_buf, row, 1);
	    break;
	  case STRIP_TIFF:
	    ReadScanline_from_TIFF_Strip(tiff, tiff_real_buf, row, 0);
	    ReadScanline_from_TIFF_Strip(tiff, tiff_imag_buf, row, 1);
	    break;
	  case TILED_TIFF:
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_real_buf, row, 0);
	    ReadScanline_from_TIFF_TileRow(tiff, tiff_imag_buf, row, 1);
	    break;
	  default:
	    asfPrintError("Can't read this TIFF format!\n");
	    break;
	  }
      }
      for (sample=0; sample<sample_count; sample++) {
	switch (sample_format)
	  {
	  case SAMPLEFORMAT_UINT:
	    re = (float)(((uint16*)tiff_real_buf)[sample]);
	    im = (float)(((uint16*)tiff_imag_buf)[sample]);
	    break;
	  case SAMPLEFORMAT_INT:
	    re = (float)(((int16*)tiff_real_buf)[sample]);
	    im = (float)(((int16*)tiff_imag_buf)[sample]);
	    break;
	  }
	amp[sample] = sqrt(re*re + im*im);
	phase[sample] = atan2(im, re);
      }
      if (flip_horizontal) {
	for (sample=0; sample<sample_count; sample++)
	  tmp[sample] = amp[sample];
	for (sample=0; sample<sample_count; sample++)
	  amp[sample] = tmp[sample_count-sample-1];
      }
	  
      put_band_float_line(fp, meta, band*2, (int)row, amp);
      if (!ampOnly)
	put_band_float_line(fp, meta, band*2+1, (int)row, phase);
    }
      
    FREE(amp);
    FREE(phase);
    if (tmp)
      FREE(tmp);
    _TIFFfree(tiff_real_buf);
    _TIFFfree(tiff_imag_buf);
    GTIFFree(gtif);
    XTIFFClose(tiff);
  }

  // update the name field with directory name
  char *path = get_dirname(inBaseName);
  if (strlen(path)<=0)
    path = g_get_current_dir();
  char *p = path, *q = path;
  while (q) {
    if ((q = strchr(p, DIR_SEPARATOR)) != NULL)
      p = q+1;
  }
  sprintf(meta->general->basename, "%s", p);
  FREE(path);
  meta_write(meta, outDataName);

  meta_free(meta);
  FREE(radarsat2);
  FCLOSE(fp);
}