Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
  // Allocate some memory
  char *inFile = (char *) MALLOC(sizeof(char)*512);
  char *outFile = (char *) MALLOC(sizeof(char)*512);

  // Parse command line
  if (argc < 3) {
    printf("Insufficient arguments.\n"); 
    usage(argv[0]);
  }  
  strcpy(inFile, argv[1]);
  strcpy(outFile, argv[2]);
  int grid_line_count = atoi(argv[3]);

  asfSplashScreen (argc, argv);

  // Deal with metadata
  meta_parameters *metaIn = meta_read(inFile);
  meta_parameters *metaOut = meta_read(inFile);
  int nl = metaIn->general->line_count;
  int ns = metaIn->general->sample_count;
  metaOut->general->data_type = ASF_BYTE;
  meta_write(metaOut, outFile);

  // Replace image with grid
  float on_grid = 0.0;
  float off_grid = 255.0;
  float *outLine = (float *) MALLOC(sizeof(float)*ns);
  float *inLine = (float *) MALLOC(sizeof(float)*ns);

  FILE *fpIn = FOPEN(appendExt(inFile, ".img"), "rb");
  FILE *fpOut = FOPEN(appendExt(outFile, ".img"), "wb");
  int ii, kk;;
  for (ii=0; ii<nl; ii++) {
    get_float_line(fpIn, metaIn, ii, inLine);
    for (kk=0; kk<ns; kk++) {
      if (ii == 0 || ii == nl -1 || ii % (ns/grid_line_count) == 0)
	outLine[kk] = on_grid;
      else if (kk % (ns/grid_line_count) == 0)
	outLine[kk] = on_grid;
      else
	outLine[kk] = off_grid;
    }
    outLine[0] = outLine[ns-1] = on_grid;
    put_float_line(fpOut, metaOut, ii, outLine);
    asfLineMeter(ii, nl);
  }

  // Clean up
  FREE(inFile);
  FREE(outFile);
  meta_free(metaIn);
  meta_free(metaOut);

  exit(0);
}
Ejemplo n.º 2
0
static void ingest_polarimetry_data(char *inFile, char *inBaseName, 
				    char *outFile, char band, int create)
{
  FILE *fpIn, *fpOut;
  meta_parameters *meta = NULL;
  char tmp[10];
  int ii, kk;
  float *power = NULL;
  char *byteBuf = NULL;
  
  fpIn = FOPEN(inFile, "rb");
  append_ext_if_needed(outFile, ".img", NULL);
  if (create)
    fpOut = FOPEN(outFile, "wb");
  else
    fpOut = FOPEN(outFile, "ab");
  
  if (create) {
    meta = import_airsar_meta(inFile, inBaseName, TRUE);
    meta->general->data_type = REAL32;
    meta->general->band_count = 1;
    sprintf(meta->general->bands, "AMP-%c", band);
    meta->general->image_data_type = IMAGE_LAYER_STACK;
  }
  else {
    meta = meta_read(outFile);
    meta->general->band_count += 1;
    sprintf(tmp, ",AMP-%c", band);
    strcat(meta->general->bands, tmp);
  }      

  power = (float *) MALLOC(sizeof(float)*meta->general->sample_count);
  byteBuf = (char *) MALLOC(sizeof(char)*10);
  airsar_header *header = read_airsar_header(inFile);
  long offset = header->first_data_offset;
  FSEEK(fpIn, offset, SEEK_SET);
  for (ii=0; ii<meta->general->line_count; ii++) {
    for (kk=0; kk<meta->general->sample_count; kk++) {
      FREAD(byteBuf, sizeof(char), 10, fpIn);
      power[kk] = sqrt(((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]));
    }
    put_float_line(fpOut, meta, ii, power);
    asfLineMeter(ii, meta->general->line_count);
  }
  FCLOSE(fpIn);
  FCLOSE(fpOut);
  meta_write(meta, outFile);
  if (power)
    FREE(power);
  if (byteBuf)
    FREE(byteBuf);
  if (meta)
    meta_free(meta);
}
Ejemplo n.º 3
0
int
dem_to_mask(char *inDemFile, char *outMaskFile, float cutoff)
{
    meta_parameters *inDemMeta = meta_read(inDemFile);
    meta_parameters *outDemMeta = meta_read(inDemFile);

    // out metadata will differ from in only in the data type
    outDemMeta->general->data_type = ASF_BYTE;

    int x_size = inDemMeta->general->sample_count;
    int y_size = inDemMeta->general->line_count;

    float *maskbuffer = MALLOC(sizeof(float) * x_size);
    float *floatbuffer = MALLOC(sizeof(float) * x_size);

    FILE *in = fopenImage(inDemFile, "rb");
    FILE *out = fopenImage(outMaskFile, "wb");

    float mv = masked_value();
    float umv = unmasked_value();

    int y,x;
    for (y=0; y<y_size; y++) 
    {
        get_float_line(in, inDemMeta, y, floatbuffer);

        for (x=0; x < x_size; x++)            
            maskbuffer[x] = floatbuffer[x] <= cutoff ? mv : umv;

        put_float_line(out, outDemMeta, y, maskbuffer);
        asfLineMeter(y, y_size);
    }

    FCLOSE(in);
    FCLOSE(out);

    FREE(floatbuffer);
    FREE(maskbuffer);

    meta_write(outDemMeta, outMaskFile);

    meta_free(inDemMeta);
    meta_free(outDemMeta);

    asfPrintStatus("Created Mask file '%s' from DEM '%s'.\n",
                   outMaskFile, inDemFile);

    return 0;
}
Ejemplo n.º 4
0
void import_gridfloat(char *inBaseName, char *outBaseName)
{
    int i, j;
    int column_count, row_count;
    char *flt_file = appendExt(inBaseName, ".flt");

    // create the metadata
    char *meta_filename = appendExt(outBaseName, ".meta");

    asfPrintStatus("Building %s ...\n", meta_filename);

    meta_parameters *meta = read_meta_gridfloat_ext(inBaseName, flt_file,
						    &column_count, &row_count);

    meta_write(meta, meta_filename);

    // Now read/write the actual data.  Read as INT16, cast to
    // floats so we can use put_float_line (which will write
    // INT16 data, since we asked for it in the metadata)
    char *data_filename = appendExt(outBaseName, ".img");

    asfPrintStatus("Reading %s, writing %s ...\n", flt_file, data_filename);

    float *floats = MALLOC(sizeof(float)*column_count);
    FILE *fp = FOPEN(flt_file, "rb");
    FILE *out = FOPEN(data_filename, "wb");

    for (i=0; i<row_count; ++i) {
        FREAD(floats, sizeof(float), column_count, fp);
	//if (msbfirst) {
            for (j=0; j<column_count; ++j) {
                big32(floats[j]);
            }
	    //}
        put_float_line(out, meta, i, floats);
        asfLineMeter(i,row_count);
    }

    fclose(fp);
    fclose(out);

    free(data_filename);
    free(floats);

    free(flt_file);
}
Ejemplo n.º 5
0
int dem2phase(char *demFile, char *baseFile, char *phaseFile)
{
  int x, y, start_sample, start_line, line_count, sample_count;
  double k, *phase2elevBase, *sinFlat, *cosFlat, xScale, yScale;
  baseline base;
  meta_parameters *meta;
  FILE *fpDem, *fpPhase;
  float *phase,*dem;
  
  meta = meta_read(demFile);
  start_sample = meta->general->start_sample;
  start_line = meta->general->start_line;
  xScale = meta->sar->sample_increment;
  yScale = meta->sar->line_increment;
  line_count = meta->general->line_count;
  sample_count = meta->general->sample_count;
  
  meta_write(meta, phaseFile);
  
  // Allocate some memory
  phase = (float *)MALLOC(sizeof(float)*sample_count);
  dem =(float *)MALLOC(sizeof(float)*sample_count);
 
  // Get wavenumber
  k = meta_get_k(meta);
  
  // Read in baseline values
  base = read_baseline(baseFile);

  // Open files  
  fpDem = fopenImage(demFile, "rb");
  fpPhase = fopenImage(phaseFile,"wb");
  
  /* calculate the sine of the incidence angle across cols*/
  sinFlat = (double *)MALLOC(sizeof(double)*sample_count);
  cosFlat = (double *)MALLOC(sizeof(double)*sample_count);
  phase2elevBase = (double *)MALLOC(sizeof(double)*sample_count);
  for (x=0; x<sample_count; x++) {
    int img_x = x*xScale + start_sample;
    double incid = meta_incid(meta, 0.0, (float)img_x);
    double flat = meta_flat(meta, 0.0, (float)img_x);
    sinFlat[x] = sin(flat);
    cosFlat[x] = cos(flat);
    phase2elevBase[x] = 
      meta_get_slant(meta, 0.0, (float)img_x) * sin(incid)/(2.0*k);
  }
  
  
  // Loop through each row and calculate height
  for (y=0;y<line_count;y++) {
    double Bn_y, Bp_y;
    
    // Read in data 
    get_float_line(fpDem, meta, y, dem);
    
    // Calculate baseline for this row
    meta_interp_baseline(meta, base, y*(int)yScale+start_line, &Bn_y, &Bp_y);
    
    // Step through each pixel in row
    for (x=0; x<sample_count; x++)
      phase[x] = dem[x]/phase2elevBase[x]*(-Bp_y*sinFlat[x]-Bn_y*cosFlat[x]);
    put_float_line(fpPhase, meta, y, phase);
    asfLineMeter(y, line_count);
  }
  asfPrintStatus("Wrote %d lines of simulated phase data.\n\n", line_count);
  
  // Clean up
  FREE(phase);
  FREE(dem);
  FCLOSE(fpPhase);
  FCLOSE(fpDem);

  return(0);
}
Ejemplo n.º 6
0
static int gr2sr_pixsiz_imp(const char *infile, const char *outfile,
                            float srPixSize, int apply_pp_earth_radius_fix)
{
  meta_parameters *inMeta, *outMeta;

  int   np, nl;         /* in number of pixels,lines       */
  int   onp, onl;       /* out number of pixels,lines      */
  int   nBands;         /* number of bands in input/output */
  int   ii;
  float *gr2sr;    /* GR 2 SR resampling vector for Range  */
  int   *lower;    /* floor of gr2sr vector                */
  int   *upper;    /* ceiling of gr2sr vector              */
  float *ufrac;    /* Upper fraction from gr2sr vector     */
  float *lfrac;    /* Lower fraction from gr2sr vector     */

  float *inBuf;          /* Input buffer                  */
  float *outBuf;         /* Output buffer                 */
  FILE  *fpi, *fpo;      /* File pointers                 */
  int   line;            /* Loop counter                  */
  int   band;            /* Loop counter                  */
  char  *iimgfile;       /* .img input file               */
  char  *oimgfile;       /* .img output file              */
 
  gr2sr = (float *) MALLOC(sizeof(float) * MAX_IMG_SIZE);
  upper = (int *) MALLOC(sizeof(int) * MAX_IMG_SIZE);
  lower = (int *) MALLOC(sizeof(int) * MAX_IMG_SIZE);
  ufrac = (float *) MALLOC(sizeof(float) * MAX_IMG_SIZE);
  lfrac = (float *) MALLOC(sizeof(float) * MAX_IMG_SIZE);

  inMeta = meta_read(infile);

  if (srPixSize < 0) {
    /*
      In an e-mail from Rick:
       Slant Range Pixel Size = C (speed of light) / [SampleRate (sample 
       rate) * 2,000,000.]

       SampleRate can be extracted from the L1 metadata :
          RNG CMPLX SAMPLE RATE        18.9599991

       The meta->sar->range_sampling_rate is 10^6 times the value above,
       so we use C/(2*meta->sar->range_sampling_rate)
    */
    int osc = inMeta->sar->original_sample_count;
    if (osc < 0) osc = inMeta->general->sample_count;
    srPixSize = SPD_LIGHT / ((2.0 * inMeta->sar->range_sampling_rate) *
      inMeta->general->sample_count / osc);
  }

  nl = inMeta->general->line_count;
  np = inMeta->general->sample_count;
  nBands = inMeta->general->band_count;

  char **band_name = extract_band_names(inMeta->general->bands, nBands);

  onl=nl;
  gr2sr_vec(inMeta, srPixSize, gr2sr, apply_pp_earth_radius_fix);
  
  /* Determine the output image size */
  onp = 0;
  for (ii=0; ii<MAX_IMG_SIZE; ii++) {
     if (gr2sr[ii]<np) onp=ii; /* gr input still in range-- keep output */
     else break; /* gr input is off end of image-- stop sr output */
  }
  asfPrintStatus("Input image is %dx%d\n", nl, np);
  asfPrintStatus("Output image will be %dx%d\n", onl, onp);
  
  /* Split gr2sr into resampling coefficients */
  for (ii=0; ii<onp; ii++) {
     lower[ii] = (int) gr2sr[ii];
     upper[ii] = lower[ii] + 1;
     ufrac[ii] = gr2sr[ii] - (float) lower[ii];
     lfrac[ii] = 1.0 - ufrac[ii];
     if (lower[ii]>=np) lower[ii]=np-1; /* range clip */
     if (upper[ii]>=np) upper[ii]=np-1; /* range clip */
  }
  
  outMeta = meta_read(infile);
  outMeta->sar->slant_shift += ((inMeta->general->start_sample)
                                * inMeta->general->x_pixel_size);
  outMeta->general->start_sample = 0.0;
  outMeta->sar->sample_increment = 1.0;
  outMeta->sar->image_type       = 'S';
  outMeta->general->x_pixel_size = srPixSize;
  outMeta->general->sample_count = onp;
  if (outMeta->sar){
    update_doppler(np, onp, gr2sr, outMeta);
  }

  iimgfile = replExt(infile, "img");
  oimgfile = replExt(outfile, "img");

  fpi = FOPEN(iimgfile,"rb");
  fpo = FOPEN(oimgfile,"wb");
  inBuf = (float *) MALLOC (np*sizeof(float));
  outBuf = (float *) MALLOC (onp*sizeof(float));

  for (band = 0; band < nBands; band++) {
    if (inMeta->general->band_count != 1)
      asfPrintStatus("Converting to slant range: band %s\n", band_name[band]);
    for (line = 0; line < onl; line++) {
      get_float_line(fpi, inMeta, line + band*onl, inBuf);
      for (ii=0; ii<onp; ii++) { /* resample to slant range */
         outBuf[ii] = inBuf[lower[ii]]*lfrac[ii]+inBuf[upper[ii]]*ufrac[ii];
      }
      put_float_line(fpo,outMeta,line + band*onl,outBuf);
      asfLineMeter(line,onl);
    }
  }

  for (ii=0; ii < inMeta->general->band_count; ii++)
    FREE(band_name[ii]);
  FREE(band_name);

  meta_write(outMeta, outfile);
  meta_free(inMeta);
  meta_free(outMeta);

  FREE(ufrac);
  FREE(lfrac);
  FREE(gr2sr);
  FREE(upper);
  FREE(lower);

  FREE(inBuf);
  FREE(outBuf);
  FCLOSE(fpi);
  FCLOSE(fpo);
  FREE(iimgfile);
  FREE(oimgfile);

  return TRUE;
}
Ejemplo n.º 7
0
static int save_as_asf(ImageInfo *ii,
                       const char *out_file, int what_to_save,
                       int strict_boundary, int load)
{
    // See if we can open the output file up front
    FILE *outFp = fopen(out_file, "wb");
    if (!outFp) {
        // failed to open the output file!
        char errbuf[1024];
        snprintf(errbuf, 1024, "Failed to open %s: %s", out_file,
            strerror(errno));
        message_box(errbuf);
        strcat(errbuf, "\n");
        printf("%s", errbuf);
        return FALSE; // failure
    }

    assert (g_poly->n > 0);
    assert (crosshair_line > 0 && crosshair_samp > 0);

    meta_parameters *meta = ii->meta;

    // figure out where to chop
    int line_min, line_max, samp_min, samp_max, nl, ns;
    compute_extent(meta, &line_min, &line_max, &samp_min, &samp_max,
        &nl, &ns);

    // generate metadata
    char *out_metaname = appendExt(out_file, ".meta");
    printf("Generating %s...\n", out_metaname);

    // data will be saved as floating point, except scaled pixel values,
    // which we can make bytes.
    data_type_t data_type = REAL32;
    if (what_to_save == SCALED_PIXEL_VALUE)
      data_type = ASF_BYTE;

    meta_parameters *out_meta =
      build_metadata(meta, out_file, nl, ns, line_min, samp_min, data_type,
                     what_to_save);

    // put_float_line() will always dump BYTE data if the optical block
    // is present... we want to be in control of the data type, so we must
    // wipe out this block
    if (out_meta->optical) {
      FREE(out_meta->optical);
      out_meta->optical=NULL;
    }

    if (what_to_save == LAT_LON_2_BAND) {
      out_meta->general->band_count = 2;
      strcpy(out_meta->general->bands, "LAT,LON");
    }

    // define clipping region, if necessary
    double xp[MAX_POLY_LEN+2], yp[MAX_POLY_LEN+2];
    int i,j,n=0;

    if (strict_boundary)
        define_clipping_region(meta, &n, xp, yp);

    float ndv = 0;
    if (meta_is_valid_double(out_meta->general->no_data))
        ndv = out_meta->general->no_data;
    else if (strict_boundary) // need to set a no data value in this case
        out_meta->general->no_data = 0.;

    meta_write(out_meta, out_metaname);

    // now actually write the data
    printf("Generating %s...\n", out_file);

    if (what_to_save == LAT_LON_2_BAND) {
      // dump a 2-band image, lat & lon data
      float *lats = MALLOC(sizeof(float)*ns);
      float *lons = MALLOC(sizeof(float)*ns);
      for (i=0; i<nl; ++i) {
        int l = line_min+i;
        for (j=0; j<ns; ++j) {
            int s = samp_min+j;
            if (!strict_boundary || pnpoly(n, xp, yp, s, l)) {
                double lat, lon;
                meta_get_latLon(meta, l, s, 0, &lat, &lon);
                lats[j] = (float)lat;
                lons[j] = (float)lon;
            }
            else {
                lats[j] = ndv;
                lons[j] = ndv;
            }
        }
        put_band_float_line(outFp, out_meta, 0, i, lats);
        put_band_float_line(outFp, out_meta, 1, i, lons);
        asfLineMeter(i,nl);
      }
      free(lats);
      free(lons);
    }
    else {
      // normal case
      float *buf = MALLOC(sizeof(float)*ns);
      for (i=0; i<nl; ++i) {
        int l = line_min+i;
        for (j=0; j<ns; ++j) {
            int s = samp_min+j;
            float val;
            if (!strict_boundary || pnpoly(n, xp, yp, s, l)) {
                val = get_data(ii, what_to_save, l, s);
            }
            else {
                val = ndv;
            }
            buf[j] = val;
        }
        put_float_line(outFp, out_meta, i, buf);
        asfLineMeter(i,nl);
      }
      free(buf);
    }
    fclose(outFp);
    meta_free(out_meta);

    // load the generated file if we were told to
    if (load)
        load_file(out_file);

    return TRUE;
}
Ejemplo n.º 8
0
int fftMatch_opt(char *inFile1, char *inFile2, float *offsetX, float *offsetY)
{ 
  // Generate temporary directory
  char tmpDir[1024];
  char metaFile[1024], outFile[1024], sarFile[1024], opticalFile[1024];
  char *baseName = get_basename(inFile1);
  strcpy(tmpDir, baseName);
  strcat(tmpDir, "-");
  strcat(tmpDir, time_stamp_dir());
  create_clean_dir(tmpDir);
  
  // Cutting optical to SAR extent
  asfPrintStatus("Cutting optical to SAR extent ...\n");
  sprintf(metaFile, "%s.meta", inFile1);
  sprintf(outFile, "%s%c%s_sub.img", tmpDir, DIR_SEPARATOR, inFile2);
  trim_to(inFile2, outFile, metaFile);
  
  // Clipping optical image including blackfill
  asfPrintStatus("\nClipping optical image including blackfill ...\n");
  meta_parameters *metaOpt = meta_read(outFile);
  meta_parameters *metaSAR = meta_read(metaFile);
  int line_count = metaSAR->general->line_count;
  int sample_count = metaSAR->general->sample_count;
  float *floatLine = (float *) MALLOC(sizeof(float)*sample_count);
  unsigned char *byteLine = (unsigned char *) MALLOC(sizeof(char)*sample_count);
  FILE *fpOptical = FOPEN(outFile, "rb");
  sprintf(sarFile, "%s.img", inFile1);
  FILE *fpSAR = FOPEN(sarFile, "rb");
  sprintf(outFile, "%s%c%s_mask.img", tmpDir, DIR_SEPARATOR, inFile2);
  sprintf(metaFile, "%s%c%s_mask.meta", tmpDir, DIR_SEPARATOR, inFile2);
  FILE *fpOut = FOPEN(outFile, "wb");
  int ii, kk;
  for (ii=0; ii<line_count; ii++) {
    get_float_line(fpSAR, metaSAR, ii, floatLine);
    get_byte_line(fpOptical, metaOpt, ii, byteLine);
    for (kk=0; kk<sample_count; kk++) {
      if (!FLOAT_EQUIVALENT(floatLine[kk], 0.0))
        floatLine[kk] = (float) byteLine[kk];
    }
    put_float_line(fpOut, metaSAR, ii, floatLine);
  }
  FCLOSE(fpOptical);
  FCLOSE(fpSAR);
  FCLOSE(fpOut);
  meta_write(metaSAR, metaFile);

  // Edge filtering optical image
  asfPrintStatus("\nEdge filtering optical image ...\n");
  sprintf(opticalFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile2);
  kernel_filter(outFile, opticalFile, SOBEL, 3, 0, 0);

  // Edge filtering SAR image
  asfPrintStatus("\nEdge filtering SAR image ...\n");
  sprintf(sarFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile1);
  kernel_filter(inFile1, sarFile, SOBEL, 3, 0, 0);

  // FFT matching on a grid
  asfPrintStatus("\nFFT matching on a grid ...\n");
  float certainty;
  fftMatch_proj(sarFile, opticalFile, offsetX, offsetY, &certainty);

  // Clean up
  remove_dir(tmpDir);

  return (0);
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
	int x, y;
	int maskflag=0;
	unsigned char *mask;
	double k;
	double *phase2elevBase,*sinFlat,*cosFlat;
	char datafile[256], basefile[256], outfile[256];
	char maskfile[256];
	int nrows,ncols; 
	float *f_coh;
	float *f_eleverr;
	float percent=0.0;
	double init_err=DEFAULT_ERROR;
	FILE *fdata, *fmask, *fout;
	meta_parameters *meta;
	baseline base;


/* Parse command line arguments */
	logflag=FALSE;
	while (currArg < (argc-NUM_ARGS)) {
	   char *key = argv[currArg++];
	   if (strmatch(key,"-log")) {
	      CHECK_ARG(1);
	      strcpy(logFile,GET_ARG(1));
	      fLog = FOPEN(logFile, "a");
	      logflag=TRUE;
	   }
	   else if (strmatch(key, "-mask")) {
	      CHECK_ARG(1);
	      strcpy(maskfile, GET_ARG(1));
	      maskflag = TRUE;
	   }
	   else if (strmatch(key,"-i")) {
	      CHECK_ARG(1);
	      init_err = atof(GET_ARG(1));
	      init_err *= init_err;
	   }
	   else {
	      printf("\n**Invalid option:  %s\n",argv[currArg-1]);
	      usage(argv[0]);
	   }
	}
	if ((argc-currArg) < NUM_ARGS) {
	   printf("Insufficient arguments.\n");
	   usage(argv[0]);
	}

	create_name(datafile, argv[currArg], ".img");
	strcpy(basefile, argv[currArg+1]);
	strcpy(outfile, argv[currArg+2]);

	asfSplashScreen(argc, argv);

/* Get appropriate metadata */
	meta = meta_read(datafile);
	nrows = meta->general->line_count;
	ncols = meta->general->sample_count;
	meta->general->data_type = REAL32;
	meta_write(meta, outfile);
	k  = meta_get_k(meta);    /* wave number*/
	
/* Allocate space for vectors, matricies, and stuff*/
	mask = (unsigned char *)MALLOC(sizeof(unsigned char)*ncols);
	f_coh = (float *)MALLOC(sizeof(float)*ncols);
	f_eleverr = (float *)MALLOC(sizeof(float)*ncols);
	sinFlat = (double *)MALLOC(sizeof(double)*ncols);
	cosFlat = (double *)MALLOC(sizeof(double)*ncols);
	phase2elevBase = (double *)MALLOC(sizeof(double)*ncols);

/* Open data file & get seed phase*/
	fdata = fopenImage(datafile, "rb");
	fout = fopenImage(outfile,"wb");
	if (maskflag) fmask = fopenImage(maskfile,"rb");
	
/* Read in baseline values*/
	base = read_baseline(basefile);

/* Obtain information from metadata*/
	for (x=0;x<ncols;x++)
	{
		int img_x = x * meta->sar->sample_increment
		            + meta->general->start_sample;
		double incid=meta_incid(meta,0,img_x);
		double flat=meta_flat(meta,0,img_x);
		sinFlat[x]=sin(flat);
		cosFlat[x]=cos(flat);
		phase2elevBase[x]=meta_get_slant(meta,0,img_x)*sin(incid)/(2.0*k);
	}

/* Loop through each row & calculate height*/
	for (y=0;y<nrows;y++) {
		double Bn_y,Bp_y;

		/* Report progress */
		if ((y*100/nrows)>percent) {
		  printf("\r   Completed %3.0f percent", percent);
		  fflush(NULL);
		  percent+=5.0;
		}

		/* read in data */
		if (maskflag)
			ASF_FREAD(mask,sizeof(unsigned char),ncols,fmask);
		get_float_line(fdata, meta, y, f_coh);
		
		/* calculate baseline for this row*/
		meta_interp_baseline(meta, base,
			y*meta->sar->line_increment+meta->general->start_line+1,
			&Bn_y, &Bp_y);
		
		/* step through each pixel in row*/
		for (x=0;x<ncols;x++) {
			if ((mask[x] == 0x10 && maskflag) || (!maskflag)) {
				double tmp,tmp1,sigma_height;
				tmp = phase2elevBase[x]/(-Bp_y*sinFlat[x]-Bn_y*cosFlat[x]);
				tmp1 = (FLOAT_EQUALS_ZERO(f_coh[x])) 
					    ? 0.0 : sqrt((1-f_coh[x])/f_coh[x]);
				sigma_height = tmp*tmp1;
				f_eleverr[x] = (float)sqrt( init_err +
					sigma_height*sigma_height );
			}
			else
				f_eleverr[x] = -1.0;
		}
		put_float_line(fout, meta, y, f_eleverr);
	}
	printf("\r   Completed 100 percent\n\n");
	sprintf(logbuf, "   Wrote %lld bytes of data\n\n",
	        (long long)(nrows*ncols*4));
	printf("%s", logbuf);
	if (logflag) { printLog(logbuf); }
	
	/* free memory & scram*/
	meta_free(meta);
	FREE(mask);
	FREE(f_coh);
	FREE(f_eleverr);
	FREE(sinFlat);
	FREE(cosFlat);
	FREE(phase2elevBase);
	FCLOSE(fdata);
	FCLOSE(fout);
	if (maskflag) FCLOSE(fmask);

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 10
0
int asf_igram_coh(int lookLine, int lookSample, int stepLine, int stepSample,
		  char *masterFile, char *slaveFile, char *outBase,
		  float *average)
{
  char ampFile[255], phaseFile[255]; //, igramFile[512];
  char cohFile[512], ml_ampFile[255], ml_phaseFile[255]; //, ml_igramFile[512];
  FILE *fpMaster, *fpSlave, *fpAmp, *fpPhase, *fpCoh, *fpAmp_ml, *fpPhase_ml;
  int line, sample_count, line_count, count;
  float	bin_high, bin_low, max=0.0, sum_a, sum_b, ampScale;
  double hist_sum=0.0, percent, percent_sum;
  long long hist_val[HIST_SIZE], hist_cnt=0;
  meta_parameters *inMeta,*outMeta, *ml_outMeta;
  complexFloat *master, *slave, *sum_igram, *sum_ml_igram;
  float *amp, *phase, *sum_cpx_a, *sum_cpx_b, *coh, *pCoh;
  float *ml_amp, *ml_phase;

  // FIXME: Processing flow with two-banded interferogram needed - backed out
  //        for now
  create_name(ampFile, outBase,"_igram_amp.img");
  create_name(phaseFile, outBase,"_igram_phase.img");
  create_name(ml_ampFile, outBase,"_igram_ml_amp.img");
  create_name(ml_phaseFile, outBase,"_igram_ml_phase.img");
  //create_name(igramFile, outBase,"_igram.img");
  //create_name(ml_igramFile, outBase, "_igram_ml.img");
  //sprintf(cohFile, "coherence.img");
  create_name(cohFile, outBase, "_coh.img");

  // Read input meta file
  inMeta = meta_read(masterFile);
  line_count = inMeta->general->line_count; 
  sample_count = inMeta->general->sample_count;
  ampScale = 1.0/(stepLine*stepSample);

  // Generate metadata for single-look images 
  outMeta = meta_read(masterFile);
  outMeta->general->data_type = REAL32;

  // Write metadata for interferometric amplitude
  outMeta->general->image_data_type = AMPLITUDE_IMAGE;
  meta_write(outMeta, ampFile);

  // Write metadata for interferometric phase
  outMeta->general->image_data_type = PHASE_IMAGE;
  meta_write(outMeta, phaseFile);

  /*
  // Write metadata for interferogram
  outMeta->general->image_data_type = INTERFEROGRAM;
  outMeta->general->band_count = 2;
  strcpy(outMeta->general->bands, "IGRAM-AMP,IGRAM-PHASE");
  meta_write(outMeta, igramFile);
  */	
     
  // Generate metadata for multilooked images
  ml_outMeta = meta_read(masterFile);
  ml_outMeta->general->data_type = REAL32;
  ml_outMeta->general->line_count = line_count/stepLine;
  ml_outMeta->general->sample_count = sample_count/stepSample;
  ml_outMeta->general->x_pixel_size *= stepSample;
  ml_outMeta->general->y_pixel_size *= stepLine;
  ml_outMeta->sar->multilook = 1;
  ml_outMeta->sar->line_increment   *= stepLine;
  ml_outMeta->sar->sample_increment *= stepSample;
  // FIXME: This is the wrong increment but create_dem_grid does not know any
  //        better at the moment.
  //ml_outMeta->sar->line_increment = 1;
  //ml_outMeta->sar->sample_increment = 1;

  // Write metadata for multilooked interferometric amplitude
  ml_outMeta->general->image_data_type = AMPLITUDE_IMAGE;
  meta_write(ml_outMeta, ml_ampFile);

  // Write metadata for multilooked interferometric phase
  ml_outMeta->general->image_data_type = PHASE_IMAGE;
  meta_write(ml_outMeta, ml_phaseFile);

  // Write metadata for coherence image
  ml_outMeta->general->image_data_type = COHERENCE_IMAGE;
  meta_write(ml_outMeta, cohFile);

  /*
  // Write metadata for multilooked interferogram
  ml_outMeta->general->image_data_type = INTERFEROGRAM;
  strcpy(ml_outMeta->general->bands, "IGRAM-AMP,IGRAM-PHASE");
  ml_outMeta->general->band_count = 2;
  meta_write(ml_outMeta, ml_igramFile);
  */

  // Allocate memory
  master = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count*lookLine);
  slave = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count*lookLine);
  amp = (float *) MALLOC(sizeof(float)*sample_count*lookLine);
  phase = (float *) MALLOC(sizeof(float)*sample_count*lookLine);
  ml_amp = (float *) MALLOC(sizeof(float)*sample_count/stepSample);
  ml_phase = (float *) MALLOC(sizeof(float)*sample_count/stepSample);
  coh = (float *) MALLOC(sizeof(float)*sample_count/stepSample);
  sum_cpx_a = (float *) MALLOC(sizeof(float)*sample_count);
  sum_cpx_b = (float *) MALLOC(sizeof(float)*sample_count);
  sum_igram = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count);
  sum_ml_igram = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count);

  // Open files
  fpMaster = FOPEN(masterFile,"rb");
  fpSlave = FOPEN(slaveFile,"rb");
  fpAmp = FOPEN(ampFile,"wb");
  fpPhase = FOPEN(phaseFile,"wb");
  fpAmp_ml = FOPEN(ml_ampFile,"wb");
  fpPhase_ml = FOPEN(ml_phaseFile,"wb");
  //FILE *fpIgram = FOPEN(igramFile, "wb");
  //FILE *fpIgram_ml = FOPEN(ml_igramFile, "wb");
  fpCoh = FOPEN(cohFile,"wb");

  // Initialize histogram
  for (count=0; count<HIST_SIZE; count++) hist_val[count] = 0;

  asfPrintStatus("   Calculating interferogram and coherence ...\n\n");

  for (line=0; line<line_count; line+=stepLine)
  {
    register int offset, row, column, limitLine;
    double igram_real, igram_imag;
    int inCol;
    limitLine=MIN(lookLine, line_count-line);

    printf("Percent completed %3.0f\r",(float)line/line_count*100.0);

    pCoh = coh;

    // Read in the next lines of data
    get_complexFloat_lines(fpMaster, inMeta, line, limitLine, master);
    get_complexFloat_lines(fpSlave, inMeta, line, limitLine, slave);

    // Add the remaining rows into sum vectors
    offset = sample_count;
    for (column=0; column<sample_count; column++)
    {
      offset = column;
      sum_cpx_a[column] = 0.0;
      sum_cpx_b[column] = 0.0;
      sum_igram[column].real = 0.0;
      sum_igram[column].imag = 0.0;
      sum_ml_igram[column].real = 0.0;
      sum_ml_igram[column].imag = 0.0;
      igram_real = 0.0;
      igram_imag = 0.0;

      for (row=0; row<limitLine; row++)
      {
	// Complex multiplication for interferogram generation
	igram_real = master[offset].real*slave[offset].real + 
	  master[offset].imag*slave[offset].imag;
        igram_imag = master[offset].imag*slave[offset].real - 
	  master[offset].real*slave[offset].imag;
        amp[offset] = sqrt(igram_real*igram_real + igram_imag*igram_imag);
        if (FLOAT_EQUIVALENT(igram_real, 0.0) || 
	    FLOAT_EQUIVALENT(igram_imag, 0.0))
	  phase[offset]=0.0;
        else
	  phase[offset] = atan2(igram_imag, igram_real);

       	sum_cpx_a[column] += AMP(master[offset])*AMP(master[offset]);
      	sum_cpx_b[column] += AMP(slave[offset])*AMP(slave[offset]);
       	sum_igram[column].real += igram_real;
	sum_igram[column].imag += igram_imag;
	if (line % stepLine == 0 && row < stepLine) {
	  sum_ml_igram[column].real += igram_real;
	  sum_ml_igram[column].imag += igram_imag;
	}

	offset += sample_count;
      }

      ml_amp[column] = 
	sqrt(sum_ml_igram[column].real*sum_ml_igram[column].real + 
	     sum_ml_igram[column].imag*sum_ml_igram[column].imag)*ampScale;
      if (FLOAT_EQUIVALENT(sum_ml_igram[column].real, 0.0) || 
	  FLOAT_EQUIVALENT(sum_ml_igram[column].imag, 0.0))
	ml_phase[column] = 0.0;
      else
	ml_phase[column] = atan2(sum_ml_igram[column].imag, 
				 sum_ml_igram[column].real);
    }

    // Write single-look and multilooked amplitude and phase
    put_float_lines(fpAmp, outMeta, line, stepLine, amp);
    put_float_lines(fpPhase, outMeta, line, stepLine, phase);
    put_float_line(fpAmp_ml, ml_outMeta, line/stepLine, ml_amp);
    put_float_line(fpPhase_ml, ml_outMeta, line/stepLine, ml_phase);
    //put_band_float_lines(fpIgram, outMeta, 0, line, stepLine, amp);
    //put_band_float_lines(fpIgram, outMeta, 1, line, stepLine, phase);
    //put_band_float_line(fpIgram_ml, ml_outMeta, 0, line/stepLine, ml_amp);
    //put_band_float_line(fpIgram_ml, ml_outMeta, 1, line/stepLine, ml_phase);

    // Calculate the coherence by adding from sum vectors
    for (inCol=0; inCol<sample_count; inCol+=stepSample)
    {
      register int limitSample = MIN(lookSample,sample_count-inCol);
      sum_a = 0.0;
      sum_b = 0.0;
      igram_real = 0.0;
      igram_imag = 0.0;

      // Step over multilook area and sum output columns
      for (column=0; column<limitSample; column++)
      {
	igram_real += sum_igram[inCol+column].real;
	igram_imag += sum_igram[inCol+column].imag;				
	sum_a += sum_cpx_a[inCol+column];
	sum_b += sum_cpx_b[inCol+column];
      }

      if (FLOAT_EQUIVALENT((sum_a*sum_b), 0.0))
	*pCoh = 0.0;
      else 
      {
	*pCoh = (float) sqrt(igram_real*igram_real + igram_imag*igram_imag) /
	  sqrt(sum_a * sum_b);
	if (*pCoh>1.0001)
	{ 
	  printf("   coh = %f -- setting to 1.0\n",*pCoh);
	  printf("   You shouldn't have seen this!\n");
	  printf("   Exiting.\n");
          exit(EXIT_FAILURE);
	  *pCoh=1.0;
	}
      }
     pCoh++;
    } 

    // Write out values for coherence
    put_float_line(fpCoh, ml_outMeta, line/stepLine, coh);

    // Keep filling coherence histogram
    for (count=0; count<sample_count/stepSample; count++)
    {
      register int tmp;
      tmp = (int) (coh[count]*HIST_SIZE); /* Figure out which bin this value is in */
      /* This shouldn't happen */
      if(tmp >= HIST_SIZE)
	tmp = HIST_SIZE-1;
      if(tmp < 0)
	tmp = 0;
      
      hist_val[tmp]++;        // Increment that bin for the histogram
      hist_sum += coh[count];   // Add up the values for the sum
      hist_cnt++;             // Keep track of the total number of values
      if (coh[count]>max) 
	max = coh[count];  // Calculate maximum coherence
    }
  } // End for line

  printf("Percent completed %3.0f\n",(float)line/line_count*100.0);

  // Sum and print the statistics
  percent_sum = 0.0;
  printf("   Coherence  :  Occurrences  :  Percent\n");
  printf("   ---------------------------------------\n");
  for (count=0; count<HIST_SIZE; count++) {
    bin_low  = (float)(count)/(float)HIST_SIZE;
    bin_high = (float)(count+1)/(float)HIST_SIZE;
    percent  = (double)hist_val[count]/(double)hist_cnt;
    percent_sum += (float)100*percent;
    printf("   %.2f -> %.2f :   %.8lld       %2.3f \n",
		   bin_low,bin_high, (long long) hist_val[count],100*percent);
  }
  *average = (float)hist_sum/(float)hist_cnt;
  printf("   ---------------------------------------\n");
  printf("   Maximum Coherence: %.3f\n", max);
  printf("   Average Coherence: %.3f  (%.1f / %lld) %f\n", 
		 *average,hist_sum, hist_cnt, percent_sum);

  // Free and exit
  FREE(master); 
  FREE(slave);
  FREE(amp); 
  FREE(phase);
  FREE(ml_amp); 
  FREE(ml_phase); 
  FREE(coh); 
  FCLOSE(fpMaster); 
  FCLOSE(fpSlave);
  FCLOSE(fpAmp); 
  FCLOSE(fpPhase);
  FCLOSE(fpAmp_ml); 
  FCLOSE(fpPhase_ml);
  //FCLOSE(fpIgram);
  //FCLOSE(fpIgram_ml);
  FCLOSE(fpCoh); 
  meta_free(inMeta);
  meta_free(outMeta);
  meta_free(ml_outMeta);
  return(0);
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    if (argc != 8) usage();

    int type = 0; // 0=?, 1=sinc, 2=pole, 3=pyr

    char *in = argv[6];
    char *out = argv[7];

    int line = atoi(argv[2]);
    int samp = atoi(argv[3]);
    int radius = atoi(argv[4]);
    float height = atof(argv[5]);

    if (strcmp(argv[1], "-sinc")==0) type=1;
    if (strcmp(argv[1], "-pole")==0) type=2;
    if (strcmp(argv[1], "-pyr")==0) type=3;
    if (type==0) { printf("Unknown pole type.\n"); usage(); }

    printf("Adding a pole:\n");
    printf("  Center point: (%d,%d)\n", line, samp);
    printf("  Radius: %d\n", radius);
    printf("  Height: %f\n", height);
    if (type!=2)
        printf("    Note that the height value is **added** to the existing "
               "terrain height.\n\n");

    printf("  Input file: %s\n", in);
    printf("  Output file: %s\n", out);

    printf("  Pole type: %s\n", argv[1]+1);

    meta_parameters *meta = meta_read(in);
    int ns = meta->general->sample_count;
    int nl = meta->general->line_count;

    FILE *inDEM = fopenImage(in, "rb");
    FILE *outDEM = fopenImage (out, "wb");

    float *demLine = (float*)MALLOC(sizeof(float)*ns);

    int i,l;
    for (l = 0; l < nl; ++l) {
        get_float_line(inDEM, meta, l, demLine);
        for (i = 0; i < ns; ++i) {
            double x;

            // sinc and pole use circular posts, real distance
            // pyr uses distance measured along the gridlines
            if (type==1 || type==2)
                x = hypot(i-samp, l-line);
            else if (type == 3)
                x = dmax(fabs(i-samp),fabs(l-line));

            if (x < (double)radius) {
                if (type==1) { // sinc
                    if (i==samp && l==line)
                        demLine[i] = height;
                    else {
                        x *= M_PI/radius;
                        demLine[i] += height * sin(x)/x;
                    }
                } else if (type==2) { // pole
                    demLine[i] = height;
                } else if (type==3) { // pyr
                    demLine[i] += height * (radius-x)/radius;
                } else {
                    printf("Impossible: type=%d\n", type);
                    exit(1);
                }
            }
        }
        put_float_line(outDEM, meta, l, demLine);
        asfLineMeter(l,nl);
    }

    meta_write(meta, out);
    fclose(inDEM);
    fclose(outDEM);
    return 0;
}
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{
  meta_parameters *meta, *meta_old, *meta_stat;
	char fnm1[BUF],fnm2[BUF],fnm3[BUF],fnm4[BUF];
	char imgfile[BUF],metaFile[BUF],cmd[BUF],metaIn[BUF],metaOut[BUF];
	FILE *fiamp, *fiphase, *foamp, *fophase, *flas;
	int ll=0, ls=1;   /* look line and sample */
	int sl=STEPLINE, ss=STEPSAMPLE;   /* step line and sample */
	int i,line, sample;
	int row, col, ampFlag = 0;
	long long nitems, newitems, inWid, inLen, outWid, outLen;
	long long ds/*,samplesRead*/;       /* input data size, number of samples read so far.*/
	long long red_offset, grn_offset, blu_offset;
	register float *ampIn, *phaseIn, ampScale;
	float *ampOut, *phaseOut,*ampBuf,Sin[256],Cos[256];
	float avg, percent=5.0;
	RGBDATA *table, *imgData;
	Uchar *redPtr, *grnPtr, *bluPtr;
	complexFloat z;
	struct DDR newddr;
	register float tmp,zImag,zReal,ampI;
	register int index,offset;
	const float convers=256.0/(2*3.14159265358979);
   
	logflag = 0;

  /* parse command line */
  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatch(key,"-log")) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = 1;
    }
    else if (strmatch(key,"-look")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&ll,&ls)) {
        printf("   ***ERROR: -look '%s' does not look like line x sample (e.g. '10x2').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-step")) {
      CHECK_ARG(1);
      if (2!=sscanf(GET_ARG(1),"%dx%d",&sl,&ss)) {
        printf("   ***ERROR: -step '%s' does not look like line x sample (e.g. '5x1').\n",GET_ARG(1));
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-meta")) {
      CHECK_ARG(1);
      if (1!=sscanf(GET_ARG(1),"%s",metaFile)) {
        printf("   ***ERROR: Could not open '%s'.\n",GET_ARG(1));
        usage(argv[0]);
      }
      strcat(metaFile, "");
      ls = ss = 1;
      ll = sl = lzInt(metaFile, "sar.look_count:", NULL);
    }
    else if (strmatch(key,"-amplitude")) {
      printf("   Will remove amplitude part of color image\n");
      ampFlag = 1;
    }
    else {printf("\n   ***Invalid option:  %s\n",argv[currArg-1]); usage(argv[0]);}
  }
  if ((argc-currArg) < 2) {printf("   Insufficient arguments.\n"); usage(argv[0]);}

	system("date");
	printf("Program: multilook\n\n");
	if (logflag) {
	  StartWatchLog(fLog);
	  printLog("Program: multilook\n\n");
	}

	/* Create filenames and open files for reading */
  	create_name(fnm1,argv[currArg],"_amp.img");
  	create_name(fnm2,argv[currArg],"_phase.img");
	meta_stat = meta_read(fnm1);
	meta_old = meta_read(fnm2);
	meta = meta_read(fnm2);
  	create_name(fnm3,argv[++currArg],"_amp.img");
  	create_name(fnm4,argv[currArg],"_phase.img");
  	create_name(imgfile,argv[currArg],"_rgb.img");
	create_name(metaOut,argv[currArg],"_rgb.meta");
 	
	inWid = meta->general->sample_count;
	inLen = meta->general->line_count;
  	meta->general->sample_count /= ss;
  	meta->general->line_count /= sl;
	outWid = meta->general->sample_count;
	outLen = meta->general->line_count;
  
	/* Create new metadata file for the amplitude and phase.*/
	meta->sar->line_increment = 1;
	meta->sar->sample_increment = 1;
	meta->sar->azimuth_time_per_pixel *= sl;
	meta->general->x_pixel_size *= ss;
	meta->general->y_pixel_size *= sl;
	create_name(metaIn,argv[currArg],"_amp.meta");
	meta_write(meta, metaIn);
	create_name(metaIn,argv[currArg],"_phase.meta");
	meta_write(meta, metaIn);

        meta2ddr(meta, &newddr);

	/* Create 3-band image's DDR.
	   Currently metadata file don't know anything about multiband imagery.
	   We will need to convert the current version for single band amplitude
	   image back to metadata version 0.9 and change a couple of values 
	sprintf(cmd, "convert_meta %s 1.3 %s 0.9", metaIn, metaOut);
	asfSystem(cmd);
        */
	
	newddr.dtype=EBYTE;
	newddr.nbands=3;
	c_putddr(imgfile,&newddr);
  
	fiamp = fopenImage(fnm1,"rb");
	fiphase = fopenImage(fnm2,"rb");
	foamp = fopenImage(fnm3,"wb");
	fophase = fopenImage(fnm4,"wb");
	flas = fopenImage(imgfile,"wb");

	/*
	* create data buffers 
	*/
	for (i=0;i<256;i++)
	{
		float phas=((float)i)/256.0*(2*3.14159265358979);
		Sin[i]=sin(phas);
		Cos[i]=cos(phas);
	}
  
	/* set data variables */
	ampScale = 1.0/(ll*ls);
	nitems   = (ll-sl)*inWid;
	newitems = sl*inWid;
  
	ds       = sizeof(float);
	ampIn    = (float *)MALLOC(ds*(newitems+nitems+ls));
	phaseIn  = (float *)MALLOC(ds*(newitems+nitems+ls));
	ampOut   = (float *)MALLOC(ds*outWid);
	ampBuf   = (float *)MALLOC(ds*outWid);
	phaseOut = (float *)MALLOC(ds*outWid);
	table    = (RGBDATA *)MALLOC(sizeof(RGBDATA)*MAXENTRIES);
	imgData  = (RGBDATA *)MALLOC(sizeof(RGBDATA)*outWid);
	redPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	grnPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	bluPtr   = (Uchar *)MALLOC(sizeof(Uchar)*outWid);
	
        /* calculate mean value */
        if (meta_stat->stats)
          avg = meta_stat->stats->band_stats[0].mean;
        else {
          sprintf(cmd, "stats -overmeta -overstat \"%s\"\n", fnm1);
          asfSystem(cmd);
          meta_free(meta_stat);
          meta_stat = meta_read(fnm1);
          avg = meta_stat->stats->band_stats[0].mean;
        }

	/* create a colortable to be used with c2i */
	colortable(table);
  
	/* start conversion */
/*	printf("   Skipping every %d col and %d row\n",ss,sl);
	printf("   Looking at every %d col and %d row\n",ls,ll);*/
  	printf("   Input is %lld lines by %lld samples\n",inLen,inWid);
	printf("   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	if (logflag) {
  	  sprintf(logbuf, "   Input is %lld lines by %lld samples\n",inLen,inWid);
	  printLog(logbuf);
	  sprintf(logbuf, "   Ouput is %lld lines by %lld samples\n\n",outLen,outWid);
	  printLog(logbuf);
	}
 	
	/*
	* Run through all lines in which data needs to be read so that
	* amount of data will be equal to ll * inWid.
	*/
	for(line=0; line<outLen; line++)
	{

		/* Read in a ll*inWid size chunk */
		get_float_lines(fiamp, meta_old, line*sl, ll, ampIn);
		get_float_lines(fiphase, meta_old, line*sl, ll, phaseIn);

		/* begin adding data */
		for (sample=0; sample<outWid; sample++)
		{ 
			tmp = 0.0, zReal=0.0, zImag=0.0;
			/* add up looking area */
			for (col=0;col<ls;col++)
			{
				offset=sample*ss+col;
				for (row=0;row<ll;row++)
				{
					ampI=ampIn[offset];
					index=0xFF&((int)(phaseIn[offset]*convers));
					tmp += ampI * ampI;
					zReal += ampI * Cos[index];
					zImag += ampI * Sin[index];
					offset+=inWid;
 				}
			}
     
			/* get phase from complex values */
			z.real=zReal;
			z.imag=zImag;
			/* place in output buffer */
		/*	ampOut[sample] = sqrt(tmp*ampScale); */
			ampOut[sample] = Cabs(z)*ampScale; 
			phaseOut[sample] = Cphase(z);
			if(!ampFlag)
				ampBuf[sample]=ampOut[sample];
			else
				ampBuf[sample]=avg*1.5;		
		}
    
		/* convert amp & phase to RGB. */
		if (!c2i(ampBuf,phaseOut,imgData,table,outWid,avg))
			Exit("ml: Error in c2i()");

		/* write out data to file */
		put_float_line(foamp, meta, line, ampOut);
		put_float_line(fophase, meta, line, phaseOut);

		if ((line*100/outLen)>percent) {
			printf("   Completed %3.0f percent\n", percent);
			percent+=5.0;
		}
		
		for (i=0;i<outWid;i++)
		{
			redPtr[i] = imgData[i].red;
			grnPtr[i] = imgData[i].green;
			bluPtr[i] = imgData[i].blue;
		} 
		red_offset=(long long)(line*outWid);
		grn_offset=(long long)(line*outWid+outWid*outLen);
		blu_offset=(long long)(line*outWid+(2*outWid*outLen));

		FSEEK64(flas,red_offset,SEEK_SET);
		ASF_FWRITE(redPtr,1,outWid,flas);
		FSEEK64(flas,grn_offset,SEEK_SET);
		ASF_FWRITE(grnPtr,1,outWid,flas);
		FSEEK64(flas,blu_offset,SEEK_SET);
		ASF_FWRITE(bluPtr,1,outWid,flas);
    
		/* reposition data for next read */
		for (i=0;i<nitems;i++)
		{
			ampIn[i] = ampIn[i + newitems];
			phaseIn[i] = phaseIn[i + newitems];
		}
		
	}
  
	/* 
	* free up unneeded memory and prepare to write 
	* a 3 sequential band image
	*/
/*	printf("\n\tdone with multilook\n");
	printf("writing out LAS/RGB image file\n");*
	printf("   Completed 100 percent\n\n   Wrote %lld bytes of data\n\n", 
	       (long long)(outLen*outWid*4));
	if (logflag) {
	  sprintf(logbuf, "   Wrote %lld bytes of data\n\n", 
		  (long long)(outLen*outWid*4));
	  printLog(logbuf);
	  StopWatchLog(fLog);
	  FCLOSE(fLog);
	}
*/

	FREE(ampIn);
	FREE(phaseIn);
	FREE(ampOut);
        FREE(ampBuf);
	FREE(phaseOut);
	FREE(table);
	FCLOSE(fiamp);
	FCLOSE(fiphase);
	FCLOSE(foamp);
	FCLOSE(fophase);
  
	/* free all memory, close files, print out time elapsed */
	FREE(redPtr);
	FREE(grnPtr);
	FREE(bluPtr);
	FREE(imgData);
	FCLOSE(flas);

        meta_free(meta);
        meta_free(meta_stat);
        meta_free(meta_old);

	return 0;
}
Ejemplo n.º 13
0
int geoid_adjust(const char *input_filename, const char *output_filename)
{
  char *input_img = appendExt(input_filename, ".img");
  char *input_meta = appendExt(input_filename, ".meta");

  char *output_img = appendExt(output_filename, ".img");
  char *output_meta = appendExt(output_filename, ".meta");

  if (!fileExists(input_img))
    asfPrintError("File not found: %s\n", input_img);
  if (!fileExists(input_meta))
    asfPrintError("File not found: %s\n", input_meta);

  meta_parameters *meta = meta_read(input_meta);
  int nl = meta->general->line_count;
  int ns = meta->general->sample_count;
  int ii, jj;

  FILE *fpIn = FOPEN(input_img, "rb");
  FILE *fpOut = FOPEN(output_img, "wb");
  float *buf;

  // Two ways we can do this:
  //   1) call meta_get_latLon at every point
  //   2) call meta_get_latLon at certain points and interpolate between
  // We will use the first when we have a lat/lon image, and the second for
  // everything else.
  int latlon_image = meta->projection &&
                     meta->projection->type == LAT_LONG_PSEUDO_PROJECTION;

  double avg = 0.0;
  int num=0;

  asfPrintStatus("Performing geoid correction.\n");
  asfPrintStatus(" Input file: %s\n", input_filename);
  asfPrintStatus(" Output file: %s\n", output_filename);

  if (latlon_image) {
    asfPrintStatus("Lat/Lon image, not using mapping interpolation.\n");
    buf = MALLOC(sizeof(float)*ns);
    for (ii=0; ii<nl; ++ii) {
      get_float_line(fpIn, meta, ii, buf);
      for (jj=0; jj<ns; ++jj) {
        double lat, lon;
        meta_get_latLon(meta, ii, jj, 0, &lat, &lon);
        if (buf[jj] > -900 && buf[jj] != meta->general->no_data)
        {
          float ht = get_geoid_height(lat,lon);
          buf[jj] += ht;
          avg += ht;
          ++num;
        }
      }
      put_float_line(fpOut, meta, ii, buf);
      asfLineMeter(ii,nl);
    }
  }
  else {
    asfPrintStatus("Not a Lat/Lon image, using mapping interpolation.\n");
    double tol = .0001;
    int size = find_grid_size(meta, 512, .1*tol);

    int test_mode = 1;
    buf = MALLOC(sizeof(float)*ns*size);

    // these are for tracking the quality of the bilinear interp
    // not used if test_mode is false
    int num_out_of_tol = 0;
    int num_checked = 0;
    int num_bad = 0;
    double max_err = 0;
    double avg_err = 0;

    for (ii=0; ii<nl; ii += size) {
      int line_lo = ii;
      int line_hi = ii + size;

      if (ii+size >= nl)
        size = nl-ii;

      get_float_lines(fpIn, meta, ii, size, buf);

      for (jj=0; jj<ns; jj += size) {
        double lats[4], lons[4];

        int samp_lo = jj;
        int samp_hi = jj + size;

        get_interp_params(meta, line_lo, line_hi, samp_lo, samp_hi, lats, lons);

        int iii, jjj;
        for (iii=0; iii<size; ++iii) {
          for (jjj=0; jjj<size && jj+jjj<ns; ++jjj) {
            int kkk = iii*ns + jj + jjj;
            assert(kkk < ns*size);

            double lat, lon;
            xy_interp(ii+iii, jj+jjj, line_lo, line_hi, samp_lo, samp_hi, lats, lons,
                      &lat, &lon);

            // random checking of the quality of our interpolations
            if (test_mode && iii%11==0 && jjj%13==0) {
              double real_lat, real_lon;
              img_to_latlon(meta, ii+iii, jj+jjj, &real_lat, &real_lon);
              double err = hypot(real_lat - lat, real_lon - lon);

              avg_err += err;
              if (err > max_err)
                max_err = err;

              if (err > .1*tol) {
                asfPrintStatus("Out of tolerance at %d,%d: (%f,%f) vs (%f,%f) -> %f\n",
                               ii+iii, jj+jjj, lat, lon, real_lat, real_lon,
                               err);
                ++num_out_of_tol;
              }
              if (err > tol) {
                asfPrintStatus("Error is larger than %f!\n", .01*tol);
                ++num_bad;
              }
              ++num_checked;
            }

            if (buf[kkk] > -900 && buf[kkk] != meta->general->no_data)
            {
              float ht = get_geoid_height(lat,lon);
              buf[kkk] += ht;
              avg += ht;
              ++num;
            }
          }  
        }
      }
      put_float_lines(fpOut, meta, ii, size, buf);
      asfPrintStatus("Completed %.1f%%  \r", 100.*ii/(double)nl);
    }
    asfPrintStatus("Completed 100%%   \n");
  }

  avg /= (double)(num);
  asfPrintStatus("Average correction: %f\n", avg);

  meta_write(meta, output_meta);
  meta_free(meta);

  FCLOSE(fpIn);
  FCLOSE(fpOut);

  FREE(buf);
  FREE(input_img);
  FREE(input_meta);
  FREE(output_img);
  FREE(output_meta);

  // success
  return 0;
}
Ejemplo n.º 14
0
int multilook(char *inFile, char *outFile, char *metaFile, char *overlay)
{
  meta_parameters *metaIn, *metaOut;
  char inAmp[255], inPhase[255], outAmp[255], outPhase[255], outRGB[255];
  FILE *fpAmpIn, *fpPhaseIn, *fpAmpOut, *fpPhaseOut, *fpRGB, *fpOverlay;
  int look_line, look_sample, step_line, step_sample, i,line, sample, row, col;
  long long nitems, newitems, in_sample_count, in_line_count, out_sample_count;
  long long out_line_count, ds;
  register float *ampIn, *phaseIn, ampScale;
  float *ampOut, *phaseOut, *rgb, *scaleIn, Sin[256],Cos[256], scale;
  complexFloat z;
  register float tmp,zImag,zReal,ampI;
  register int index,offset;
  const float convers=256.0/(2*3.14159265358979);
  
  // Create filenames and open files for reading
  create_name(inAmp, inFile, "_amp.img");
  create_name(inPhase, inFile, "_phase.img");
  metaIn = meta_read(inPhase);
  metaOut = meta_read(inPhase);
  // FIXME: Should write out two-banded file. Too much to fix in the rest of
  //        the unwrapping code. Leaving that for clean up after the course.
  create_name(outAmp, outFile, "_amp.img");
  create_name(outPhase, outFile, "_phase.img");
  create_name(outRGB, outFile, "_phase_rgb.img");
  metaIn = meta_read(inFile);
  metaOut = meta_read(inFile);

  // Create new metadata file for the amplitude and phase.
  look_sample = step_sample = 1;
  look_line = step_line = metaOut->sar->look_count;  
  in_sample_count = metaIn->general->sample_count;
  in_line_count = metaIn->general->line_count;
  metaOut->general->sample_count /= step_sample;
  metaOut->general->line_count /= step_line;
  out_sample_count = metaOut->general->sample_count;
  out_line_count = metaOut->general->line_count;
  metaOut->sar->multilook = 1;
  metaOut->sar->line_increment = 1;
  metaOut->sar->sample_increment = 1;
  metaOut->sar->azimuth_time_per_pixel *= step_line;
  metaOut->general->x_pixel_size *= step_sample;
  metaOut->general->y_pixel_size *= step_line;
  meta_write(metaOut, outAmp);
  meta_write(metaOut, outPhase);
  //meta_write(metaOut, outFile);
  meta_write(metaOut, outRGB);
  
  // Open the files
  fpAmpIn = fopenImage(inAmp, "rb");
  fpPhaseIn = fopenImage(inPhase, "rb");
  fpAmpOut = fopenImage(outAmp, "wb");
  fpPhaseOut = fopenImage(outPhase, "wb");
  //FILE *fpIn = fopenImage(inFile, "rb");
  //FILE *fpOut = fopenImage(outFile, "wb");
  fpRGB = fopenImage(outRGB, "wb");
  if (overlay)
    fpOverlay = fopenImage(overlay, "rb");
  
  for (i=0;i<256;i++) {
    float phas=((float)i)/256.0*(2*3.14159265358979);
    Sin[i]=sin(phas);
    Cos[i]=cos(phas);
  }
  
  // Set data variables
  ampScale = 1.0/(look_line*look_sample);
  nitems   = (look_line-step_line)*in_sample_count;
  newitems = step_line*in_sample_count;
  
  ds       = sizeof(float);
  ampIn    = (float *)MALLOC(ds*(newitems+nitems+look_sample));
  phaseIn  = (float *)MALLOC(ds*(newitems+nitems+look_sample));
  if (overlay)
    scaleIn  = (float *)MALLOC(ds*(newitems+nitems+look_sample));
  ampOut   = (float *)MALLOC(ds*out_sample_count);
  rgb      = (float *)MALLOC(ds*out_sample_count);
  phaseOut = (float *)MALLOC(ds*out_sample_count);
  
  // Let the user know what's happening  
  asfPrintStatus("Input is %lld lines by %lld samples\n",
		 in_line_count, in_sample_count);
  asfPrintStatus("Ouput is %lld lines by %lld samples\n\n",
		 out_line_count,out_sample_count);
  
  // Get to work
  for(line=0; line<out_line_count; line++) {
    
    get_float_lines(fpAmpIn, metaIn, line*step_line, look_line, ampIn);
    get_float_lines(fpPhaseIn, metaIn, line*step_line, look_line, phaseIn);
    //get_band_float_lines(fpIn, metaIn, 0, line*step_line, look_line, ampIn);
    //get_band_float_lines(fpIn, metaIn, 1, line*step_line, look_line, 
    //			 phaseIn);
    if (overlay)
      get_float_lines(fpOverlay, metaOut, line, 1, scaleIn);
    
    // Begin adding data
    for (sample=0; sample<out_sample_count; sample++) { 
      tmp = 0.0, zReal=0.0, zImag=0.0;
      // Add up looking area
      for (col=0; col<look_sample; col++) {
	offset=sample*step_sample+col;
	for (row=0; row<look_line; row++) {
	  ampI = ampIn[offset];
	  index = 0xFF&((int)(phaseIn[offset]*convers));
	  tmp += ampI * ampI;
	  zReal += ampI * Cos[index];
	  zImag += ampI * Sin[index];
	  offset += in_sample_count;
	}
      }
      
      // Get phase from complex values
      z.real = zReal;
      z.imag = zImag;

      ampOut[sample] = Cabs(z)*ampScale; 
      phaseOut[sample] = Cphase(z);
      if (overlay)
	scale = scaleIn[sample];
      else
	scale = 1.0;
      if (phaseOut[sample] < 0.0)
	rgb[sample] = (phaseOut[sample] + M_PI) * scale;
      else
	rgb[sample] = phaseOut[sample] * scale;
    }
    
    // Write out data to file
    //put_band_float_line(fpOut, metaOut, 0, line, ampOut);
    //put_band_float_line(fpOut, metaOut, 1, line, phaseOut);
    put_float_line(fpAmpOut, metaOut, line, ampOut);
    put_float_line(fpPhaseOut, metaOut, line, phaseOut);
    put_float_line(fpRGB, metaOut, line, rgb);
    
    asfLineMeter(line, out_line_count);
        
    // Reposition data for next read
    for (i=0;i<nitems;i++) {
      ampIn[i] = ampIn[i + newitems];
      phaseIn[i] = phaseIn[i + newitems];
    }
  }
  
  // Clean up
  FREE(ampIn);
  FREE(phaseIn);
  FREE(ampOut);
  FREE(rgb);
  FREE(phaseOut);
  if (overlay) {
    FREE(scaleIn);
    FCLOSE(fpOverlay);
  }
  FCLOSE(fpAmpIn);
  FCLOSE(fpPhaseIn);
  FCLOSE(fpAmpOut);
  FCLOSE(fpPhaseOut);
  //FCLOSE(fpIn);
  //FCLOSE(fpOut);
  FCLOSE(fpRGB);
  
  meta_free(metaIn);
  meta_free(metaOut);

  // Export a color version of the interferogram to JPEG
  create_name(outPhase, outFile, "_phase_rgb");
  check_return(asf_export_with_lut(JPEG, SIGMA, "interferogram.lut", 
				   outPhase, outPhase),
	       "colorized interferogram (asf_export)");

  return 0;
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[])
{

  int op;
  long point_size;
  long x_size, y_size, line,blockSize,xpos;
  FILE *in, *out;
  meta_parameters *inMeta, *outMeta;
  char infile[BUF];
  char outfile[BUF];
  char  *maskbuffer;
  float *floatbuffer;
  float arga,argb;
   if (argc<5) usage();
   
   point_size = 1;
  create_name (infile, argv[1], ".img");
  create_name (outfile,argv[2], ".img");
  inMeta = meta_read(argv[1]);
  outMeta = meta_read(argv[1]);
  x_size = inMeta->general->sample_count;
  y_size = inMeta->general->line_count;
//  printf(" x_size = %d y_size = %d \n \n ", x_size, y_size);
//  printf("target line is number %d \n",tline);
  
  floatbuffer = MALLOC (sizeof(float) * inMeta->general->sample_count  * 1);
  maskbuffer = MALLOC (sizeof(float) * inMeta->general->sample_count * 1);
  
//  printf(" created memory buffer \n");
  in = fopenImage(infile, "rb");
  out = fopenImage(outfile, "wb");
  outMeta->general->data_type = ASF_BYTE;
  //TODO better argument conversion
  // now work out what operation we are doing
  arga = atof(argv[4]);
  argb = 0;
  if (strcmp(argv[3], "gt") >= 0)
  {
	  if (strchr(argv[3], 'e') != NULL)
  {
	   op = 0;
  }
  else 
  {
	   op = 1;
  }
  }
  
  if (strcmp(argv[3], "lt") >= 0)
  {
	  if (strchr(argv[3], 'e') != NULL)
  {
	  op = 2;
  }
  else 
  {
	   op = 3;
  }
  }	
			
  if (strchr(argv[3],'=') != NULL)
	op = 4;
			
  if (strcmp(argv[3],"...") == 0)
  {
	  argb = atof(argv[5]);
	  op = 5;
  }
  
  // now process the image
  
  for (line=0; line <= y_size ; line++) 
  	{
	   blockSize = get_float_line(in,inMeta,line,floatbuffer);
	   printf(".");
	   for (xpos=0; xpos < x_size; xpos++)
		   maskbuffer[xpos] = mask_expression(op, floatbuffer[xpos], arga, argb); // does the actual data validation
           put_float_line(out, outMeta, line, maskbuffer);

	   // blockSize = put_float_line(out,outMeta,line,maskbuffer);
  	}
  
  meta_write(outMeta, outfile);
  meta_free(inMeta);
  meta_free(outMeta);
  
  FCLOSE(in);
  FCLOSE(out);
  FREE(floatbuffer);
  FREE(maskbuffer);
  return(0);
}
Ejemplo n.º 16
0
/*
  writePatch:
  Outputs one full patch of data to the given file.
*/
void writePatch(const patch *p,const satellite *s,meta_parameters *meta,
    const file *f,int patchNo)
{
  int outLine;       /* Counter for line base output */
  FILE *fp_amp,*fp_cpx;  /* File pointers for the amplitude and  complex outputs*/
  FILE *fp_pwr,*fp_sig;  /* File pointers for the power and Sigma_0 outputs */
  FILE *fp_gam,*fp_bet;  /* File pointers for the Gamma_0 and Beta_0 outputs */
  complexFloat *outputBuf; /* Buffer for one line of patch = n_range    */
  complexFloat *mlBuf;   /* Buffer for multilooking the amplitude image */
  float *amps;           /* Output Amplitude  = n_az/nlooks X n_range */
  float *pwrs;       /* Output power */
  char *openMode="ab";   /* Normally append output.*/
  int mlCount=0;     /* Counter for setting up the multilook buffer */
  int writeNoiseTable=0; /* Flag to determine whether to write the noise table and
                antenna pattern */
  int off_slc = f->n_az_valid * (patchNo-1);
  int off_ml = f->n_az_valid * (patchNo-1) / (f->nlooks);

  if (patchNo==1)
    openMode="wb";   /* for first patch, truncate output. */

  if ((patchNo==1) && (s->vecLen!=0))
    writeNoiseTable=1;  /* If first patch AND antenna pattern correction,
               write the noise table */

  update_status("Range-doppler done");
  if (!quietflag) printf("   WRITING PATCH OUT...\n");
  elapse(0);

  /* Allocate buffer space  ------------------------*/
  amps = (float *) MALLOC(p->n_range*sizeof(float));
  pwrs = (float *) MALLOC(p->n_range*sizeof(float));

  outputBuf = (complexFloat *)MALLOC(p->n_range*sizeof(complexFloat));
  mlBuf = (complexFloat *)MALLOC(p->n_range*f->nlooks*sizeof(complexFloat));

  /* Fill in metadata */
  meta_get_latLon(meta, meta->general->line_count/2,
          meta->general->sample_count/2, 0.0,
          &(meta->general->center_latitude),
          &(meta->general->center_longitude));

  meta_parameters *metaCpx=meta_copy(meta);
  metaCpx->general->data_type = COMPLEX_REAL32;
  metaCpx->general->image_data_type = COMPLEX_IMAGE;
  metaCpx->general->radiometry = r_AMP;
  metaCpx->general->line_count = f->n_az_valid * patchNo;
  metaCpx->general->sample_count = p->n_range;
  meta_get_latLon(metaCpx, metaCpx->general->line_count/2,
          metaCpx->general->sample_count/2, 0.0,
          &(metaCpx->general->center_latitude),
          &(metaCpx->general->center_longitude));
  metaCpx->general->start_line = f->firstLineToProcess + s->dop_precomp + 1;
  metaCpx->general->start_sample = f->skipFile + 1;
  metaCpx->general->x_pixel_size = f->rngpix;
  metaCpx->general->y_pixel_size = f->azpix;
  meta_write(metaCpx, f->out_cpx);
  fp_cpx=fopenImage(f->out_cpx,openMode);

  meta_parameters *metaAmp=meta_copy(metaCpx);
  metaAmp->general->data_type = REAL32;
  metaAmp->general->image_data_type = AMPLITUDE_IMAGE;
  metaAmp->general->radiometry = r_AMP;
  metaAmp->general->line_count = f->n_az_valid / f->nlooks * patchNo;
  metaAmp->general->y_pixel_size *= f->nlooks;
  metaAmp->sar->azimuth_time_per_pixel *= f->nlooks;
  meta_write(metaAmp, f->out_amp);
  fp_amp=fopenImage(f->out_amp,openMode);

  meta_parameters *metaPower=0, *metaSigma=0, *metaGamma=0, *metaBeta=0;
  if (s->imageType.power) {
    metaPower=meta_copy(metaAmp);
    metaPower->general->image_data_type = AMPLITUDE_IMAGE;
    metaPower->general->radiometry = r_POWER;
    meta_write(metaPower, f->out_pwr);
    fp_pwr=fopenImage(f->out_pwr,openMode);
  }
  if (s->imageType.sigma) {
    metaSigma=meta_copy(metaAmp);
    metaSigma->general->image_data_type = AMPLITUDE_IMAGE;
    metaSigma->general->radiometry = r_SIGMA;
    meta_write(metaSigma, f->out_sig);
    fp_sig=fopenImage(f->out_sig,openMode);
  }
  if (s->imageType.gamma) {
    metaGamma=meta_copy(metaAmp);
    metaGamma->general->image_data_type = AMPLITUDE_IMAGE;
    metaGamma->general->image_data_type = r_GAMMA;
    meta_write(metaGamma, f->out_gam);
    fp_gam=fopenImage(f->out_gam,openMode);
  }
  if (s->imageType.beta) {
    metaBeta=meta_copy(metaAmp);
    metaBeta->general->image_data_type = AMPLITUDE_IMAGE;
    metaBeta->general->radiometry = r_BETA;
    meta_write(metaBeta, f->out_bet);
    fp_bet=fopenImage(f->out_bet,openMode);
  }

  /* This gets messy */
  for (outLine = 0; outLine < f->n_az_valid; outLine++)
  {
      int j; /* loop counter */
      int base = f->firstOutputLine+outLine; /* loop counter for transposed data */

      if(writeNoiseTable==1) {
          if (!quietflag) printf("   Writing .noise and .ant files\n");
      }

      /* Print statement for the antenna pattern correction option */
      if(s->vecLen==0) {
          if(!quietflag && (outLine % 1024 == 0)) {
              printf("   ...Writing Line %i\n",outLine);
          }
      }
      if(s->vecLen!=0) {
          if(!quietflag && (outLine % 1024 == 0)) {
              printf("   ...Writing Line %i and applying Antenna Pattern Correction\n",
                     outLine);
          }
      }

      /* Fill up the buffers */
      for (j=0; j<p->n_range; j++,base+=p->n_az)
      {
          outputBuf[j] = p->trans[base];

          /* For speed, if we aren't correcting the antenna pattern,
             write the multi-look buffer now */
          if(s->vecLen==0)
          {
              mlBuf[j+mlCount*p->n_range].real = outputBuf[j].real;
              mlBuf[j+mlCount*p->n_range].imag = outputBuf[j].imag;
          }
      }

      /* Apply the Antenna Pattern Correction if desired */
      if(s->vecLen!=0)
      {

          /* On the first time through, write out the noise table */
          if(writeNoiseTable==1)
          {
              writeTable(meta,s,p->n_range);
              writeNoiseTable=0;
          }

          antptn_correct(meta,outputBuf,base,p->n_range,s);
          if(!quietflag && (j==0)) printf("   Correcting Line %d\n",outLine);

          /* Otherwise, write the multi-look buffer now */
          for(j=0;j<p->n_range;j++)
          {
              mlBuf[j+mlCount*p->n_range].real = outputBuf[j].real;
              mlBuf[j+mlCount*p->n_range].imag = outputBuf[j].imag;
          }
      }

      put_complexFloat_line(fp_cpx, metaCpx, outLine+off_slc, outputBuf);
      mlCount+=1;
      /* Multilook takes f->nlooks lines of data and averages them together,
         and writes one line on return */
      if(mlCount==f->nlooks)
      {
          /* multilook on the power image, then use the power image to generate
             an amplitude, and all other detected images from the command line.
             Be careful because I recycle amps after writing out the line of
             amplitude data, and it gets used as the sigma_0, beta_0, and gamma_0
             line. It my be confusing, but it uses less memory.*/
          multilook(mlBuf,p->n_range,f->nlooks,pwrs);
          intensity(p->n_range,pwrs,amps);

          put_float_line(fp_amp, metaAmp, outLine/f->nlooks+off_ml, amps);

          if (s->imageType.power) {
              put_float_line(fp_pwr, metaPower, outLine/f->nlooks+off_ml, pwrs);
          }
          if (s->imageType.sigma)
          {
              calculateRCS(SIGMA_0, meta, pwrs, amps,
                           base-mlCount/2, p->n_range,s);
              put_float_line(fp_sig, metaSigma, outLine/f->nlooks+off_ml, amps);
          }
          if (s->imageType.gamma)
          {
              calculateRCS(GAMMA_0, meta, pwrs, amps,
                           base-mlCount/2, p->n_range,s);
              put_float_line(fp_gam, metaGamma, outLine/f->nlooks+off_ml, amps);
          }
          if (s->imageType.beta)
          {
              calculateRCS(BETA_0, meta, pwrs, amps,
                           base-mlCount/2, p->n_range,s);
              put_float_line(fp_bet, metaBeta, outLine/f->nlooks+off_ml, amps);
          }

          mlCount=0;
      }
  }
  FCLOSE(fp_cpx);
  FCLOSE(fp_amp);
  if (s->imageType.power)
    FCLOSE(fp_pwr);
  if (s->imageType.sigma)
    FCLOSE(fp_sig);
  if (s->imageType.gamma)
    FCLOSE(fp_gam);
  if (s->imageType.beta)
    FCLOSE(fp_bet);

  if (!quietflag) printf("\n");
  if (logflag) printLog("\n");
  if (!quietflag) {
    printf("   AMPLITUDE IMAGE FINISHED: Wrote %i lines and %i samples\n",
           f->n_az_valid/f->nlooks,p->n_range);
    printf("   PATCH FINISHED: Wrote %i lines of %i samples (float)\n\n",
           f->n_az_valid,p->n_range);
  }
  FREE((void *)amps);
  FREE((void *)pwrs);
  FREE((void *)outputBuf);
  FREE((void *)mlBuf);
  meta_free(metaAmp);
  meta_free(metaCpx);
  if (metaPower) meta_free(metaPower);
  if (metaSigma) meta_free(metaSigma);
  if (metaGamma) meta_free(metaGamma);
  if (metaBeta)  meta_free(metaBeta);
  if (!quietflag) elapse(1);
}
Ejemplo n.º 17
0
// Main program body.
int
main (int argc, char *argv[])
{
  int currArg = 1;
  int NUM_ARGS = 2;

  handle_license_and_version_args(argc, argv, ASF_NAME_STRING);
  asfSplashScreen(argc, argv);

  if (argc<2)
      usage(ASF_NAME_STRING);
  else if (strmatches(argv[1],"-help","--help",NULL))
      print_help();

  while (currArg < (argc-NUM_ARGS)) {
    char *key = argv[currArg++];
    if (strmatches(key,"-help","--help",NULL)) {
        print_help(); // doesn't return
    }
    else if (strmatches(key,"-log","--log",NULL)) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = TRUE;
    }
    else if (strmatches(key,"-quiet","--quiet","-q",NULL)) {
      quietflag = TRUE;
    }
    else {
      --currArg;
      break;
    }
  }

  if ((argc-currArg) < NUM_ARGS) {
    printf("Insufficient arguments.  Expected %d, got %d.\n",
           NUM_ARGS, argc-currArg);
    usage(argv[0]);
  } else if ((argc-currArg) > NUM_ARGS) {
    printf("Unknown argument: %s\n", argv[currArg]);
    usage(argv[0]);
  }

  char *in_file = argv[currArg];
  char *out_file = argv[currArg+1];

  char *in_img = appendExt(in_file, ".img");
  char *out_img = appendExt(out_file, ".img");
  char *in_meta = appendExt(in_file, ".meta");
  char *out_meta = appendExt(out_file, ".meta");

  meta_parameters *meta = meta_read(in_meta);
  if (!meta) asfPrintError("Failed to read metadata for: %s\n", in_file);

  FILE *ifp = FOPEN(in_img, "r");
  FILE *ofp = FOPEN(out_img, "w");
  float *buf = MALLOC(sizeof(float)*meta->general->sample_count);

  int ii,jj;
  for (ii=0; ii<meta->general->line_count; ++ii) {
    get_float_line(ifp, meta, ii, buf);
    for (jj=0; jj<meta->general->sample_count; ++jj) {
      if (buf[jj] < 0) {
        buf[jj] = 0;
      } else {
        buf[jj] = sqrt(buf[jj]);
      }
    }
    put_float_line(ofp, meta, ii, buf);
    asfLineMeter(ii,meta->general->line_count);
  }

  FCLOSE(ifp);
  FCLOSE(ofp);
  FREE(buf);

  if (meta->stats) { 
    FREE(meta->stats);
    meta->stats = NULL;
  }
 
  meta_write(meta, out_meta);
  meta_free(meta);

  FREE(in_img);
  FREE(out_img);
  FREE(in_meta);
  FREE(out_meta);

  asfPrintStatus("Done.\n");
  return EXIT_SUCCESS;
}
Ejemplo n.º 18
0
static void ingest_insar_data(char *inFile, char *inBaseName, char *band,
			      int size, int line_count, char *outFile, 
			      int create)
{
  airsar_header *header;
  meta_parameters *metaIn = NULL, *metaOut = NULL;
  FILE *fpIn, *fpOut;
  int ii, kk, line_offset;
  float *floatBuf;
  char tmp[10];
  
  fpIn = FOPEN(inFile, "rb");
  append_ext_if_needed(outFile, ".img", NULL);
  if (create)
    fpOut = FOPEN(outFile, "wb");
  else
    fpOut = FOPEN(outFile, "ab");

  if (create) {
    metaOut = import_airsar_meta(inFile, inBaseName, TRUE);
    metaOut->general->data_type = REAL32;
    metaOut->general->band_count = 1;
    sprintf(metaOut->general->bands, "%s", band);
    metaOut->general->image_data_type = IMAGE_LAYER_STACK;
  }
  else {
    metaOut = meta_read(outFile);
    metaOut->general->band_count += 1;
    sprintf(tmp, ",%s", band);
    strcat(metaOut->general->bands, tmp);
  }      

  header = read_airsar_header(inFile);
  metaIn = import_airsar_meta(inFile, inBaseName, TRUE);
  line_offset = header->first_data_offset/metaIn->general->sample_count/size;
  metaIn->general->line_count = line_count + line_offset;
  if (size == 2)
    metaIn->general->data_type = INTEGER16;
  else if (size == 1)
    metaIn->general->data_type = ASF_BYTE;
  floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count);
  for (ii=0; ii<line_count; ii++) {
    get_float_line(fpIn, metaIn, ii+line_offset, floatBuf);
    if (strcmp_case(band, "DEM") == 0) {
      for (kk=0; kk<metaIn->general->sample_count; kk++)
	floatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment +
	  metaIn->airsar->elevation_offset;
    }
    put_float_line(fpOut, metaOut, ii, floatBuf);
    asfLineMeter(ii, line_count);
  }
  FCLOSE(fpIn);
  FCLOSE(fpOut);
  meta_write(metaOut, outFile);

  if (floatBuf)
    FREE(floatBuf);
  if (metaIn)
    meta_free(metaIn);
  if (metaOut)
    meta_free(metaOut);
}
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
  FILE *fpIn, *fpOut, *fpInList, *fpOutList, *fpXml;
  meta_parameters *meta;
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;
  
  // Parse command line args
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if (strmatch(key,"-log")) {
      sprintf(logFile, "%s", argv[currArg]);
      logflag = 1;
    }
    else {
      printf("\n   ***Invalid option:  %s\n\n",
	     argv[currArg-1]);
      usage(argv[0]);
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  
  asfSplashScreen(argc, argv);
  
  char *listInFile = (char *) MALLOC(sizeof(char)*(strlen(argv[1])+1));
  strcpy(listInFile, argv[1]);
  char *outFile = (char *) MALLOC(sizeof(char)*(strlen(argv[2])+1));
  strcpy(outFile, argv[2]);
  
  // Setup file names
  char outDirName[512], outFileName[512];
  split_dir_and_file(outFile, outDirName, outFileName);
  char *tmpDir = (char *) MALLOC(sizeof(char)*512);
  sprintf(tmpDir, "%smeasures-", outDirName);
  char *tsdir = time_stamp_dir();
  strcat(tmpDir, tsdir);
  FREE(tsdir);
  create_clean_dir(tmpDir);
  char *isoStr = iso_date();

  // Read header information
  char inFile[512], imgFile[768], metaFile[768];
  char listOutFile[768], citation[50], start[30], end[30], first[30];
  char header[120], baseName[512], dirName[512], ext[5];
  float x_pix, y_pix, x_map_ll, y_map_ll, x_map_ur, y_map_ur, inc, cat;
  double lat, lon, height, x, y, z;
  int ii, kk, nFiles=0, num = 1, sample_count, line_count;
  image_data_type_t image_data_type;
  sprintf(listOutFile, "%s%crgps.xml", tmpDir, DIR_SEPARATOR);

  // Preparing map projection information
  project_parameters_t pps;
  projection_type_t proj_type;
  datum_type_t datum;
  spheroid_type_t spheroid;
  read_proj_file("polar_stereographic_north_ssmi.proj", 
     &pps, &proj_type, &datum, &spheroid);
  pps.ps.false_easting = 0.0;
  pps.ps.false_northing = 0.0;
  meta_projection *proj = meta_projection_init();
  proj->type = proj_type;
  proj->datum = HUGHES_DATUM;
  proj->spheroid = HUGHES_SPHEROID;
  proj->param = pps;
  strcpy(proj->units, "meters");
  proj->hem = 'N';
  spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);
  FREE(proj);

  // Set up supplemental file names: water mask, lat/lon, x/y grids
  char maskFile[768], latFile[768], lonFile[768], xFile[768], yFile[768]; 
  sprintf(maskFile, "%s%cwater_mask.img", tmpDir, DIR_SEPARATOR);
  sprintf(latFile, "%s%clatitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(lonFile, "%s%clongitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(xFile, "%s%cxgrid.img", tmpDir, DIR_SEPARATOR);
  sprintf(yFile, "%s%cygrid.img", tmpDir, DIR_SEPARATOR);

  // Generating output XML file
  fpInList = FOPEN(listInFile, "r");
  fpOutList = FOPEN(listOutFile, "w");
  fprintf(fpOutList, "<netcdf>\n");
  fprintf(fpOutList, "  <data>\n");
  fprintf(fpOutList, "    <latitude>%s</latitude>\n", latFile);
  fprintf(fpOutList, "    <longitude>%s</longitude>\n", lonFile);
  fprintf(fpOutList, "    <xgrid>%s</xgrid>\n", xFile);
  fprintf(fpOutList, "    <ygrid>%s</ygrid>\n", yFile);
  fprintf(fpOutList, "    <mask>%s</mask>\n", maskFile);
  
  julian_date jdStart, jdEnd, jdRef;
  hms_time hms;
  hms.hour = 0;
  hms.min = 0;
  hms.sec = 0.0;

  asfPrintStatus("Working through the file list:\n");
  int myrFlag=FALSE, divFlag=FALSE, vrtFlag=FALSE, shrFlag=FALSE;
  int firstYear, firstDay, startYear, startDay, endYear, endDay;
  double westBoundLon, eastBoundLon, northBoundLat, southBoundLat;
  double minLat=90.0, maxLat=-90.0, minLon=180.0, maxLon=-180.0;

  while (fgets(inFile, 512, fpInList)) {

    chomp(inFile);
    char inDirName[512], inFileName[512];
    split_dir_and_file(inFile, inDirName, inFileName);

    // Preparing map projection information
    project_parameters_t pps;
    projection_type_t proj_type;
    datum_type_t datum;
    spheroid_type_t spheroid;
    read_proj_file("polar_stereographic_north_ssmi.proj", 
       &pps, &proj_type, &datum, &spheroid);
    pps.ps.false_easting = 0.0;
    pps.ps.false_northing = 0.0;
    meta_projection *proj = meta_projection_init();
    proj->type = proj_type;
    proj->datum = HUGHES_DATUM;
    proj->spheroid = HUGHES_SPHEROID;
    proj->param = pps;
    strcpy(proj->units, "meters");
    proj->hem = 'N';
    spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);

    // Sort out dates
    startYear = subInt(inFileName, 0, 4);
    startDay = subInt(inFileName, 4, 3);
    endYear = subInt(inFileName, 8, 4);
    endDay = subInt(inFileName, 12, 3);
    if (nFiles == 0) {
      firstYear = startYear;
      firstDay = startDay;
    }
    sprintf(citation, "%d%03d to %d%03d", startYear, startDay, endYear, endDay);
    rgps2iso_date(startYear, (double) startDay, start);
    rgps2iso_date(endYear, (double) endDay, end);
    rgps2iso_date(firstYear, (double) firstDay, first);
    
    // Read header information
    FILE *fpIn = FOPEN(inFile, "r");
    fgets(header, 100, fpIn);
    sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
      &x_map_ur, &y_map_ur);
    fgets(header, 100, fpIn);
    int params = sscanf(header, "%f %f %d %d", 
      &inc, &cat, &sample_count, &line_count);
    if (params == 3) {
      sscanf(header, "%f %d %d", &cat, &sample_count, &line_count);
      inc = 0;
    }
    else if (params == 2) {
      sscanf(header, "%d %d", &sample_count, &line_count);
      inc = 0;
      cat = 1;
    }
    num = (int) cat;
    if (num > 1)
      asfPrintError("Multiband imagery (%s) not supported for netCDF "
        "generation!\n", inFile);

    /*  
    printf("x_pix: %f, y_pix: %f\n", x_pix, y_pix);
    printf("x_map_ll: %f, y_map_ll: %f\n", x_map_ll, y_map_ll);
    printf("x_map_ur: %f, y_map_ur: %f\n", x_map_ur, y_map_ur);
    printf("sample_count: %d, line_count: %d\n\n", sample_count, line_count);
    */
      
    // Check extension
    split_base_and_ext(inFileName, 1, '.', baseName, ext);
    asfPrintStatus("Processing %s ...\n", inFileName);
    sprintf(imgFile, "%s%c%s_%s.img", tmpDir, DIR_SEPARATOR, baseName, &ext[1]);
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    jdRef.year = firstYear;
    jdRef.jd = 1;
    jdStart.year = startYear;
    jdStart.jd = startDay;
    jdEnd.year = endYear;
    jdEnd.jd = endDay;
    double startSec = date2sec(&jdStart, &hms) - date2sec(&jdRef, &hms);
    double endSec = date2sec(&jdEnd, &hms) - date2sec(&jdRef, &hms);
    if (strcmp_case(ext, ".MYR") == 0) {
      fprintf(fpOutList, "    <multiyear_ice_fraction start=\"%.0f\" end=\"%.0f"
        "\">%s</multiyear_ice_fraction>\n", startSec, endSec, imgFile);
      image_data_type = MULTIYEAR_ICE_FRACTION;
      myrFlag = TRUE;
    }
    else if (strcmp_case(ext, ".DIV") == 0) {
      fprintf(fpOutList, "    <divergence start=\"%.0f\" end=\"%.0f\">%s"
        "</divergence>\n", startSec, endSec, imgFile);
      image_data_type = DIVERGENCE;
      divFlag = TRUE;
    }
    else if (strcmp_case(ext, ".VRT") == 0) {
      fprintf(fpOutList, "    <vorticity start=\"%.0f\" end=\"%.0f\">%s"
        "</vorticity>\n", startSec, endSec, imgFile);
      image_data_type = VORTICITY;
      vrtFlag = TRUE;
    }
    else if (strcmp_case(ext, ".SHR") == 0) {
      fprintf(fpOutList, "    <shear start=\"%.0f\" end=\"%.0f\">%s</shear>", 
        startSec, endSec, imgFile);
      image_data_type = SHEAR;
      shrFlag = TRUE;
    }

    // Generate basic metadata
    meta = raw_init();
    meta->general->line_count = line_count;
    meta->general->sample_count = sample_count;
    meta->general->band_count = 1;
    meta->general->data_type = REAL32;
    meta->general->image_data_type = image_data_type;
    strcpy(meta->general->basename, inFile);
    meta->general->x_pixel_size = x_pix*1000.0;
    meta->general->y_pixel_size = y_pix*1000.0;
    meta->general->start_line = 0;
    meta->general->start_sample = 0;
    meta->general->no_data = MAGIC_UNSET_DOUBLE;
    strcpy(meta->general->sensor, "RGPS MEaSUREs");
    char *tmp = image_data_type2str(meta->general->image_data_type);
    sprintf(meta->general->bands, "%s", lc(tmp));
    FREE(tmp);
    sprintf(meta->general->acquisition_date, "%s", baseName);
    
    // Sort out map projection
    proj->startX = x_map_ll*1000.0;
    proj->startY = y_map_ur*1000.0;
    proj->perX = x_pix*1000.0;
    proj->perY = -y_pix*1000.0;
    meta->projection = proj;
    meta_write(meta, metaFile);
    strcpy(meta->general->bands, "water mask");
    sprintf(metaFile, "%s%cwater_mask.meta", tmpDir, DIR_SEPARATOR);
    meta_write(meta, metaFile);  
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);

    // Write gridded data to ASF internal format
    fpOut = FOPEN(imgFile, "wb");
    for (ii=0; ii<line_count; ii++) {
      for (kk=0; kk<sample_count; kk++) {
	      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
	      ieee_big32(floatBuf[kk]);
        if (floatBuf[kk] > 10000000000.0 || 
          FLOAT_EQUIVALENT(floatBuf[kk], 10000000000.0))
          floatBuf[kk] = MAGIC_UNSET_DOUBLE;
      }
      put_float_line(fpOut, meta, line_count-ii-1, floatBuf);
    }
    FCLOSE(fpOut);
    FREE(floatBuf);
    
    double lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4;
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ll*1000.0, 0.0, 
      &lat1, &lon1, &height);
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ur*1000.0, 0.0, 
      &lat2, &lon2, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ur*1000.0, 0.0, 
      &lat3, &lon3, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ll*1000.0, 0.0, 
      &lat4, &lon4, &height);
    westBoundLon = minValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    eastBoundLon = maxValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    northBoundLat = maxValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    southBoundLat = minValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    if (westBoundLon < minLon)
      minLon = westBoundLon;
    if (eastBoundLon > maxLon)
      maxLon = eastBoundLon;
    if (southBoundLat < minLat)
      minLat = southBoundLat;
    if (northBoundLat > maxLat)
      maxLat = northBoundLat;

    meta_free(meta);
    nFiles++;
  }
  FCLOSE(fpInList);
  
  fprintf(fpOutList, "  </data>\n");
  fprintf(fpOutList, "  <metadata>\n");
  fprintf(fpOutList, "    <time>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">T"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <bounds type=\"string\" definition=\"variable "
    "containing data range\">time_bounds</bounds>\n");
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time>\n");
  fprintf(fpOutList, "    <time_bounds>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start and end time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time_bounds>\n");
  fprintf(fpOutList, "    <latitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">latitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">latitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_north</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-90.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">90.0</valid_max>\n");
  fprintf(fpOutList, "    </latitude>\n");
  fprintf(fpOutList, "    <longitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">longitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">longitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_east</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-180.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">180.0</valid_max>\n");
  fprintf(fpOutList, "    </longitude>\n");
  fprintf(fpOutList, "    <xgrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">X"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_x_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_x_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </xgrid>\n");
  fprintf(fpOutList, "    <ygrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">Y"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_y_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </ygrid>\n");
  fprintf(fpOutList, "    <Polar_Stereographic>\n");
  fprintf(fpOutList, "      <grid_mapping_name>polar_stereographic"
    "</grid_mapping_name>\n");
  fprintf(fpOutList, "      <straight_vertical_longitude_from_pole>%.1f"
    "</straight_vertical_longitude_from_pole>\n", pps.ps.slon);
  fprintf(fpOutList, "      <longitude_of_central_meridian>90.0"
    "</longitude_of_central_meridian>\n");
  fprintf(fpOutList, "      <standard_parallel>%.1f</standard_parallel>\n", 
    pps.ps.slat);
  fprintf(fpOutList, "      <false_easting>%.1f</false_easting>\n", 
    pps.ps.false_easting);
  fprintf(fpOutList, "      <false_northing>%.1f</false_northing>\n",
    pps.ps.false_northing);
  fprintf(fpOutList, "      <projection_x_coordinate>xgrid"
    "</projection_x_coordinate>\n");
  fprintf(fpOutList, "      <projection_y_coordinate>ygrid"
    "</projection_y_coordinate>\n");
  fprintf(fpOutList, "      <units>meters</units>\n");
  fprintf(fpOutList, "    </Polar_Stereographic>\n");
  fprintf(fpOutList, "    <mask>\n");
  fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
    "coordinate reference\">ygrid xgrid</coordinates>\n");
  fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
    "Polar_Stereographic</grid_mapping>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">1</units>\n");
  fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
    "descriptive information about dimensionless quantity\">unitless"
    "</units_description>\n");
  fprintf(fpOutList, "      <FillValue type=\"int\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </mask>\n");
  if (myrFlag) {
    fprintf(fpOutList, "    <multiyear_ice_fraction>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "multiyear ice fraction value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs multiyear ice fraction</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </multiyear_ice_fraction>\n");
  }
  if (divFlag) {
    fprintf(fpOutList, "    <divergence>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "divergence value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs divergence</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </divergence>\n");
  }
  if (vrtFlag) {
    fprintf(fpOutList, "    <vorticity>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "vorticity value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs vorticity</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </vorticity>\n");
  }
  if (shrFlag) {
    fprintf(fpOutList, "    <shear>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "shear value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs shear</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </shear>\n");
  }
  fprintf(fpOutList, "  </metadata>\n");
  fprintf(fpOutList, "  <parameter>\n");
  if (myrFlag)
    fprintf(fpOutList, "    <multiyear_ice_fraction type=\"float\"/>\n");
  if (divFlag)
    fprintf(fpOutList, "    <divergence type=\"float\"/>\n");
  if (vrtFlag)
    fprintf(fpOutList, "    <vorticity type=\"float\"/>\n");
  if (shrFlag)
    fprintf(fpOutList, "    <shear type=\"float\"/>\n");
  fprintf(fpOutList, "  </parameter>\n");
  
  char startStr[15], endStr[15];
  jdStart.year = firstYear;
  jdStart.jd = firstDay;
  jdEnd.year = endYear;
  jdEnd.jd = endDay;
  jd2date(&jdStart, startStr);
  jd2date(&jdEnd, endStr);
  if (firstYear != endYear || firstDay != endDay)
    sprintf(citation, "%s to %s", startStr, endStr);
  else
    sprintf(citation, "%s", startStr);
  fprintf(fpOutList, "  <root>\n");
  fprintf(fpOutList, "    <Conventions>CF-1.6</Conventions>\n");
  fprintf(fpOutList, "    <institution>Alaska Satellite Facility</institution>\n");
  fprintf(fpOutList, "    <title>Kwok, Ron. 2008. MEaSUREs Small-Scale Kinematics"
    " of Arctic Ocean Sea Ice, Version 01, %s. Jet Propulsion Laboratory "
    "Pasadena, CA USA and Alaska Satellite Facility Fairbanks, AK USA. "
    "Digital media.</title>\n", citation);
  fprintf(fpOutList, "    <source>Products derived from RADARSAT-1 SWB imagery at "
    "100 m resolution</source>\n");
  fprintf(fpOutList, "    <comment>Imagery the products are derived from: Copyright "
    "Canadian Space Agency (1996 to 2008)</comment>\n");
  fprintf(fpOutList, "    <reference>Documentation available at: www.asf.alaska.edu"
    "</reference>\n");
  fprintf(fpOutList, "    <history>%s: netCDF file created.</history>\n", isoStr);
  fprintf(fpOutList, "  </root>\n");
  fprintf(fpOutList, "</netcdf>\n");
  FCLOSE(fpOutList);

  // Generate supplemental files: water mask, lat/lon, x/y grids
  asfPrintStatus("Generating supplemental files ...\n");
  float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *maskBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *latBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *lonBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *xBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *yBuf = (float *) MALLOC(sizeof(float)*sample_count);
  meta = meta_read(metaFile);
  
  fpIn = FOPEN(inFile, "r");
  fgets(header, 100, fpIn);
  sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
    &x_map_ur, &y_map_ur);
  fgets(header, 100, fpIn);
  sscanf(header, "%d %d", &sample_count, &line_count);
  
  FILE *fpMask = FOPEN(maskFile, "wb");
  FILE *fpLat = FOPEN(latFile, "wb");
  FILE *fpLon = FOPEN(lonFile, "wb");
  FILE *fpXgrid = FOPEN(xFile, "wb");
  FILE *fpYgrid = FOPEN(yFile, "wb");
  for (ii=0; ii<line_count; ii++) {
    for (kk=0; kk<sample_count; kk++) {
      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
      ieee_big32(floatBuf[kk]);
    }
    for (kk=0; kk<sample_count; kk++) {
      meta_get_latLon(meta, line_count-ii-1, kk, 0.0, &lat, &lon);
      latlon_to_proj(meta->projection, 'R', lat*D2R, lon*D2R, 0.0, &x, &y, &z);
      latBuf[kk] = lat;
      lonBuf[kk] = lon;
      xBuf[kk] = x;
      yBuf[kk] = y;
      if (floatBuf[kk] < 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else if (floatBuf[kk] > 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else {
        maskBuf[kk] = 0.0;
      }
    }
    put_float_line(fpMask, meta, line_count-ii-1, maskBuf);
    put_float_line(fpLat, meta, line_count-ii-1, latBuf);
    put_float_line(fpLon, meta, line_count-ii-1, lonBuf);
    put_float_line(fpXgrid, meta, line_count-ii-1, xBuf);
    put_float_line(fpYgrid, meta, line_count-ii-1, yBuf);
  }
  FCLOSE(fpIn);
  FCLOSE(fpMask);
  FCLOSE(fpLat);
  FCLOSE(fpLon);
  FREE(floatBuf);
  FREE(maskBuf);
  FREE(latBuf);
  FREE(lonBuf);
  FREE(xBuf);
  FREE(yBuf);
  meta_write(meta, latFile);
  meta_write(meta, lonFile);
  meta_write(meta, xFile);
  meta_write(meta, yFile);

  // Write ISO meatadata for netCDF
  asfPrintStatus("Generating metadata for netCDF file ...\n");

  char *ncXmlBase = get_basename(outFile);
  char *ncXmlFile = appendExt(outFile, ".xml");
  fpXml = FOPEN(ncXmlFile, "w");
  fprintf(fpXml, "<rgps>\n");
  fprintf(fpXml, "  <granule>%s</granule>\n", ncXmlBase);
  fprintf(fpXml, "  <metadata_creation>%s</metadata_creation>\n", isoStr);
  fprintf(fpXml, "  <metadata>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"name of product "
    "file\">%s.nc</file>\n", ncXmlBase);
  if (divFlag && vrtFlag && shrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "divergence, vorticity, shear</type>\n");
  else if (myrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "multiyear ice fraction</type>\n");
  fprintf(fpXml, "      <format type=\"string\" definition=\"name of the data "
    "format\">netCDF</format>\n");

  fpInList = FOPEN(listInFile, "r");
  while (fgets(inFile, 512, fpInList)) {
    chomp(inFile);
    split_dir_and_file(inFile, dirName, baseName);
    fprintf(fpXml, "      <source type=\"string\" definition=\"name of the data"
    " source\">%s</source>\n", baseName);
  }
  FCLOSE(fpInList);

  fprintf(fpXml, "      <cell_size_x type=\"double\" definition=\"cell size "
    "in x direction\" units=\"m\">%.2f</cell_size_x>\n", x_pix*1000.0);
  fprintf(fpXml, "      <cell_size_y type=\"double\" definition=\"cell size "
    "in y direction\" units=\"m\">%.2f</cell_size_y>\n", y_pix*1000.0);
  fprintf(fpXml, "      <map_x_lower_left type=\"double\" definition=\"x "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_x_lower_left>\n",
    x_map_ll*1000.0);
  fprintf(fpXml, "      <map_y_lower_left type=\"double\" definition=\"y "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_y_lower_left>\n",
    y_map_ll*1000.0);
  fprintf(fpXml, "      <map_x_upper_right type=\"double\" definition=\"x "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_x_upper_right>"
    "\n", x_map_ur*1000.0);
  fprintf(fpXml, "      <map_y_upper_right type=\"double\" definition=\"y "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_y_upper_right>"
    "\n", y_map_ur*1000.0);
  fprintf(fpXml, "      <cell_dimension_x type=\"int\" definition=\"cell "
    "dimension in x direction\">%d</cell_dimension_x>\n", 
    sample_count);
  fprintf(fpXml, "      <cell_dimension_y type=\"int\" definition=\"cell "
    "dimension in y direction\">%d</cell_dimension_y>\n",
      line_count);
  fprintf(fpXml, "      <projection_string type=\"string\" definition=\"map "
    "projection information as well known text\">%s</projection_string>\n", 
  meta2esri_proj(meta, NULL));
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </metadata>\n");
  fprintf(fpXml, "  <extent>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <westBoundLongitude>%.5f</westBoundLongitude>\n",
    minLon);
  fprintf(fpXml, "      <eastBoundLongitude>%.5f</eastBoundLongitude>\n",
    maxLon);
  fprintf(fpXml, "      <northBoundLatitude>%.5f</northBoundLatitude>\n",
    maxLat);
  fprintf(fpXml, "      <southBoundLatitude>%.5f</southBoundLatitude>\n",
    minLat);
  fprintf(fpXml, "      <start_datetime>%s</start_datetime>\n", first);
  fprintf(fpXml, "      <end_datetime>%s</end_datetime>\n", end);
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </extent>\n");
  fprintf(fpXml, "</rgps>\n");
  FCLOSE(fpXml);
  FREE(ncXmlBase);
  FREE(ncXmlFile);
  meta_free(meta);

  // Export to netCDF
  asfPrintStatus("Exporting to netCDF file ...\n");
  export_netcdf_xml(listOutFile, outFile);

  // Clean up
  remove_dir(tmpDir);
  FREE(tmpDir);
  FREE(outFile);
  FREE(listInFile);
  FREE(isoStr);

  return 0;
}
Ejemplo n.º 20
0
void asf_airsar_import(char *inFile, char *outFile, int insar, int polar)
{
  airsar_header *header = NULL;
  meta_parameters *metaIn = NULL, *metaOut = NULL;
  FILE *fpIn, *fpOut;
  float *floatBuf;
  char dataName[1024], *airsar_basename=NULL;
  int ii, kk, create=TRUE, line_count;
  int dem=FALSE, amp=FALSE, coh=FALSE;
  long line_offset;

  // First check for the existence of the input file. In this case we ingest
  // a single AirSAR file and ignore any other option that is passed in.
  if (fileExists(inFile) && strstr(inFile, "_meta.airsar") == NULL) {

    // Check what kind of data it is
    if (strstr(inFile, ".demi2"))
      dem = TRUE;
    else if (strstr(inFile, ".vvi2"))
      amp = TRUE;
    else if (strstr(inFile, ".corgr"))
      coh = TRUE;
    // FIX ME: Does not deal with polarimetric data yet

    header = read_airsar_header(inFile);
    metaIn = import_airsar_meta(inFile, airsar_basename, TRUE);
    line_offset = header->first_data_offset/metaIn->general->sample_count/2;
    metaIn->general->line_count += line_offset;
    metaOut = import_airsar_meta(inFile, airsar_basename, TRUE);

    // Assign appropriate data type
    if (dem || amp)
      metaIn->general->data_type = INTEGER16;
    else 
      metaIn->general->data_type = ASF_BYTE;

    metaOut->general->data_type = REAL32;
    floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count);
    fpIn = FOPEN(inFile, "rb");
    append_ext_if_needed(outFile, ".img", NULL);
    fpOut = FOPEN(outFile, "wb");
    for (ii=0; ii<metaOut->general->line_count; ii++) {

      // Interferometric data can be read using get_float_line
      if (dem || amp || coh)
	get_float_line(fpIn, metaIn, ii+line_offset, floatBuf);

      // DEM needs some additional treatment      
      if (dem) {
	for (kk=0; kk<metaIn->general->sample_count; kk++)
	  floatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment +
	    metaIn->airsar->elevation_offset;
      }

      // Writing away should work the same way
      put_float_line(fpOut, metaOut, ii, floatBuf);
      asfLineMeter(ii, metaOut->general->line_count);
    }
    FCLOSE(fpIn);
    FCLOSE(fpOut);
    if (dem) {
      metaOut->general->image_data_type = DEM;
      strcpy(metaOut->general->bands, "DEM");
    }
    else if (amp) {
      metaOut->general->image_data_type = AMPLITUDE_IMAGE;
      strcpy(metaOut->general->bands, "AMPLITUDE");
    }
    else if (coh) {
      metaOut->general->image_data_type = COHERENCE_IMAGE;
      strcpy(metaOut->general->bands, "COHERENCE");
    }
    meta_write(metaOut, outFile);
  }
  // Take care of interferometric layer stack
  else if (insar) {

    // Check for DEM
    sprintf(dataName, "%s.demi2", inFile);
    if (!fileExists(dataName))
      asfPrintError("Could not find DEM (%s)\nDEM is required for reliable"
		    "geometry and geolocation\n", dataName);
    else {
      printf("Ingesting DEM (%s) ...\n", dataName);
      metaIn = import_airsar_meta(dataName, inFile, TRUE);
      line_count = metaIn->general->line_count;
      ingest_insar_data(dataName, inFile, "DEM", sizeof(short), line_count,
			outFile, create);
      create = FALSE;
    }

    // Check for amplitude image
    sprintf(dataName, "%s.vvi2", inFile);
    if (!fileExists(dataName))
      asfPrintWarning("Could not find amplitude image (%s)\n", dataName);
    else {
      printf("Ingesting amplitude image (%s) ...\n", dataName);
      ingest_insar_data(dataName, inFile, "AMPLITUDE", sizeof(short), 
			line_count, outFile, create);
      create = FALSE;
    }

    // Check for coherence image
    sprintf(dataName, "%s.corgr", inFile);
    if (!fileExists(dataName))
      asfPrintWarning("Could not find coherence image (%s)\n", dataName);
    else {
      printf("Ingesting coherence image (%s) ...\n", dataName);
      ingest_insar_data(dataName, inFile, "COHERENCE", sizeof(char), 
			line_count, outFile, create);
      create = FALSE;
    }    
  }
  // Take care of polarimetric layer stack
  // We will just put all available power images into a multiband image
  else if (polar) {

    // Check for C-band data
    sprintf(dataName, "%s_c.datgr", inFile);
    if (!fileExists(dataName))
      sprintf(dataName, "%s_c.dat", inFile);
    if (!fileExists(dataName))
      asfPrintWarning("Could not find polarimetric data set (%s)\n",
		      dataName);
    else {
      printf("Ingesting C band data (%s) ...\n", dataName);
      ingest_polarimetry_data(dataName, inFile, outFile, 'C', create);
      create = FALSE;
    }

    // Check for L-band data
    sprintf(dataName, "%s_l.datgr", inFile);
    if (!fileExists(dataName))
      sprintf(dataName, "%s_l.dat", inFile);
    if (!fileExists(dataName))
      asfPrintWarning("Could not find polarimetric data set (%s)\n",
		      dataName);
    else {
      printf("Ingesting L band data (%s) ...\n", dataName);
      ingest_polarimetry_data(dataName, inFile, outFile, 'L', create);
      create = FALSE;
    }

    // Check for P-band data
    sprintf(dataName, "%s_p.datgr", inFile);
    if (!fileExists(dataName))
      sprintf(dataName, "%s_p.dat", inFile);
    if (!fileExists(dataName))
      asfPrintWarning("Could not find polarimetric data set (%s)\n",
		      dataName);
    else {
      printf("Ingesting P band data (%s) ...\n", dataName);
      ingest_polarimetry_data(dataName, inFile, outFile, 'P', create);
      create = FALSE;
    }    
  }
  // Regular ingest
  else 
    import_airsar(inFile, r_AMP, outFile);

  // Clean up time
  if (metaIn)
    meta_free(metaIn);
  if (metaOut)
    meta_free(metaOut);
}
Ejemplo n.º 21
0
int fftMatch(char *inFile1, char *inFile2, char *corrFile,
          float *bestLocX, float *bestLocY, float *certainty)
{
  int nl,ns;
  int mX,mY;               /*Invariant: 2^mX=ns; 2^mY=nl.*/
  int chipX, chipY;        /*Chip location (top left corner) in second image*/
  int chipDX,chipDY;       /*Chip size in second image.*/
  int searchX,searchY;     /*Maximum distance to search for peak*/

  int x,y;
  float doubt;
  float *corrImage=NULL;
  FILE *corrF=NULL,*in1F,*in2F;
  meta_parameters *metaMaster, *metaSlave, *metaOut;

  in1F = fopenImage(inFile1,"rb");
  in2F = fopenImage(inFile2,"rb");
  metaMaster = meta_read(inFile1);
  metaSlave = meta_read(inFile2);

  /*Round to find nearest power of 2 for FFT size.*/
  mX = (int)(log((float)(metaMaster->general->sample_count))/log(2.0)+0.5);
  mY = (int)(log((float)(metaMaster->general->line_count))/log(2.0)+0.5);

  /* Keep size of fft's reasonable */
  if (mX > 13) mX = 13;
  if (mY > 15) mY = 15;
  ns = 1<<mX;
  nl = 1<<mY;

  /* Test chip size to see if we have enough memory for it */
  /* Reduce it if necessary, but not below 1024x1024 (which needs 4 Mb of memory) */
  float *test_mem = (float *)malloc(sizeof(float)*ns*nl*2);
  if (!test_mem && !quietflag) asfPrintStatus("\n");
  while (!test_mem) {
      mX--;
      mY--;
      ns = 1<<mX;
      nl = 1<<mY;
      if (ns < 1024 || nl < 1024) {
          asfPrintError("FFT Size too small (%dx%d)...\n", ns, nl);
      }
      if (!quietflag) asfPrintStatus("   Not enough memory... reducing FFT Size to %dx%d\n", ns, nl);
      test_mem = (float *)malloc(sizeof(float)*ns*nl*2);
  }
  FREE(test_mem);
  if (!quietflag) asfPrintStatus("\n");

  /*Set up search chip size.*/
  chipDX=MINI(metaSlave->general->sample_count,ns)*3/4;
  chipDY=MINI(metaSlave->general->line_count,nl)*3/4;
  chipX=MINI(metaSlave->general->sample_count,ns)/8;
  chipY=MINI(metaSlave->general->line_count,nl)/8;
  searchX=MINI(metaSlave->general->sample_count,ns)*3/8;
  searchY=MINI(metaSlave->general->line_count,nl)*3/8;

  fft2dInit(mY, mX);

  if (!quietflag && ns*nl*2*sizeof(float)>20*1024*1024) {
    asfPrintStatus(
            "   These images will take %d megabytes of memory to match.\n\n",
            ns*nl*2*sizeof(float)/(1024*1024));
  }

  /*Optionally open the correlation image file.*/
  if (corrFile) {
    metaOut = meta_read(inFile1);
    metaOut->general->data_type= REAL32;
    metaOut->general->line_count = 2*searchY;
    metaOut->general->sample_count = 2*searchX;
    corrF=fopenImage(corrFile,"w");
  }

  /*Perform the correlation.*/
  fftProd(in1F,metaMaster,in2F,metaSlave,&corrImage,ns,nl,mX,mY,
          chipX,chipY,chipDX,chipDY,searchX,searchY);

  /*Optionally write out correlation image.*/
  if (corrFile) {
    int outY=0;
    float *outBuf=(float*)MALLOC(sizeof(float)*metaOut->general->sample_count);
    for (y=chipY-searchY;y<chipY+searchY;y++) {
      int index=ns*modY(y,nl);
      int outX=0;
      for (x=chipX-searchX;x<chipX+searchX;x++) {
        outBuf[outX++]=corrImage[index+modX(x,ns)];
      }
      put_float_line(corrF,metaOut,outY++,outBuf);
    }
    meta_write(metaOut, corrFile);
    meta_free(metaOut);
    FREE(outBuf);
    FCLOSE(corrF);
  }

  /*Search correlation image for a peak.*/
  findPeak(corrImage,bestLocX,bestLocY,&doubt,nl,ns,
           chipX,chipY,searchX,searchY);
           *certainty = 1-doubt;

  FREE(corrImage);
  if (!quietflag) {
    asfPrintStatus("   Offset slave image: dx = %f, dy = %f\n"
                   "   Certainty: %f%%\n",*bestLocX,*bestLocY,100*(1-doubt));
  }

  meta_free(metaSlave);
  meta_free(metaMaster);
  FCLOSE(in1F);
  FCLOSE(in2F);

  return (0);
}
Ejemplo n.º 22
0
static int
proj_to_sr(const char *infile, const char *outfile, double pixel_size)
{
    int ii, jj, kk;
    const float_image_sample_method_t sampling_method =
        FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR;

    // overall algorithm:
    // 1. find extents in time/slant space
    // 2. for each pixel in output, resample in input space

    meta_parameters *inMeta = meta_read(infile);
    int nl = inMeta->general->line_count;
    int ns = inMeta->general->sample_count;

    if (!inMeta->projection && !inMeta->transform)
        asfPrintError("Expected a projection/transform block!\n");
    if (!inMeta->state_vectors)
        asfPrintError("Input data does not have state vectors!\n");

    //asfPrintStatus("Converting %s to slant range...\n", infile);

    // first, find extents in time/slant space
    // do this by projecting image corners to time/slant
    int tl_x=0,    tl_y=0;
    int tr_x=ns-1, tr_y=0;
    int bl_x=0,    bl_y=nl-1;
    int br_x=ns-1, br_y=nl-1;

    // we have to find the "real" corners of the image
    // do this using the first band of the input image as a reference
    if (inMeta->general->band_count == 1)
        asfPrintStatus("Tiling the input image...\n");
    else
        asfPrintStatus("Tiling the reference band of the input image...\n");

    FloatImage *in = float_image_new_from_metadata(inMeta, infile);

    // find top left pixel -- TOP-most non-no-data pixel in the image
    for (ii=0; ii<nl; ++ii)
        for (jj=0; jj<ns; ++jj) {
            double val = float_image_get_pixel(in, jj, ii);
            if (val != inMeta->general->no_data && val != 0.0) {
                tl_x = jj; tl_y = ii;
                goto found_tl;
            }
        }

    asfPrintError("Couldn't find top-left pixel! Entire image no data?\n");

  found_tl:

    // find top right pixel -- RIGHT-most non-no-data pixel in the image
    for (jj=ns-1; jj>=0; --jj)
        for (ii=0; ii<nl; ++ii) {
            double val = float_image_get_pixel(in, jj, ii);
            if (val != inMeta->general->no_data && val != 0.0) {
                tr_x = jj; tr_y = ii;
                goto found_tr;
            }
        }

    asfPrintError("Couldn't find top-right pixel! Entire image no data?\n");

  found_tr:

    // find bottom left pixel -- LEFT-most non-no-data pixel in the image
    for (jj=0; jj<ns; ++jj)
        for (ii=nl-1; ii>=0; --ii) {
            double val = float_image_get_pixel(in, jj, ii);
            if (val != inMeta->general->no_data && val != 0.0) {
                bl_x = jj; bl_y = ii;
                goto found_bl;
            }
        }

    asfPrintError("Couldn't find bottom-left pixel! Entire image no data?\n");

  found_bl:

    // find bottom right pixel -- BOTTOM-most non-no-data pixel in the image
    for (ii=nl-1; ii>=0; --ii)
        for (jj=ns-1; jj>=0; --jj) {
            double val = float_image_get_pixel(in, jj, ii);
            if (val != inMeta->general->no_data && val != 0.0) {
                br_x = jj; br_y = ii;
                goto found_br;
            }
        }

    asfPrintError("Couldn't find bottom-right pixel! Entire image no data?\n");

  found_br:

    asfPrintStatus("Determining image extents in time/slant coordinates.\n");
    //asfPrintStatus("Corners are at: TL (%d,%d)\n", tl_y, tl_x);
    //asfPrintStatus(" (line,sample)  TR (%d,%d)\n", tr_y, tr_x);
    //asfPrintStatus("                BL (%d,%d)\n", bl_y, bl_x);
    //asfPrintStatus("                BR (%d,%d)\n", br_y, br_x);

    double tl_time, tl_slant;
    double tr_time, tr_slant;
    double bl_time, bl_slant;
    double br_time, br_slant;

    meta_get_timeSlantDop(inMeta, tl_y, tl_x, &tl_time, &tl_slant, NULL);
    meta_get_timeSlantDop(inMeta, tr_y, tr_x, &tr_time, &tr_slant, NULL);
    meta_get_timeSlantDop(inMeta, bl_y, bl_x, &bl_time, &bl_slant, NULL);
    meta_get_timeSlantDop(inMeta, br_y, br_x, &br_time, &br_slant, NULL);

    //asfPrintStatus("Corners are at: TL (%f,%f)\n", tl_time, tl_slant);
    //asfPrintStatus(" (time,slant)   TR (%f,%f)\n", tr_time, tr_slant);
    //asfPrintStatus("                BL (%f,%f)\n", bl_time, bl_slant);
    //asfPrintStatus("                BR (%f,%f)\n", br_time, br_slant);

    double slant_start = min4(tl_slant, tr_slant, bl_slant, br_slant);
    double slant_end = max4(tl_slant, tr_slant, bl_slant, br_slant);

    double time_min = min4(tl_time, tr_time, bl_time, br_time);
    double time_max = max4(tl_time, tr_time, bl_time, br_time);

    double slant_incr;
    double time_start, time_end, time_incr;
    int onl, ons;

    if (pixel_size > 0) {
        slant_incr = pixel_size;
        ons = (slant_end - slant_start) / slant_incr;

        if (inMeta->sar) {
            // in this case, the original data has a SAR block, we will use the
            // same azimuth time per pixel.
            time_incr = inMeta->sar->azimuth_time_per_pixel;

            // we always want to be DECREASING in time
            // latest time is on top (line 1), earliest on bottom (line ONL)
            if (time_incr > 0) {
                time_incr = -time_incr;
                inMeta->sar->azimuth_time_per_pixel =
                    -inMeta->sar->azimuth_time_per_pixel;
            }

            time_start = time_max;
            time_end = time_min;

            onl = (time_end - time_start) / time_incr;
        }
        else {
            // here, no sar block in the original data, just make a square
            // image with decreasing time
            onl = ons;
            time_incr = (time_min - time_max) / (double)onl;
            time_start = time_max;
            time_end = time_min;
        }
    }
    else {
        // not provided a slant range pixel size, we'll figure something out

        if (inMeta->sar) {
            // use the same azimuth time per pixel.
            time_incr = inMeta->sar->azimuth_time_per_pixel;

            // we always want to be DECREASING in time
            // latest time is on top (line 1), earliest on bottom (line ONL)
            if (time_incr > 0) {
                time_incr = -time_incr;
                inMeta->sar->azimuth_time_per_pixel =
                    -inMeta->sar->azimuth_time_per_pixel;
            }

            time_start = time_max;
            time_end = time_min;

            onl = (time_end - time_start) / time_incr;
        }
        else {
            // no info... determine azimuth time per pixel by keeping
            // the height the same as in the original image
            onl = nl;
            time_incr = (time_min - time_max) / (double)onl;
            time_start = time_max;
            time_end = time_min;
        }

        // make it square, to get the slant range pixel size
        ons = onl;
        pixel_size = slant_incr = (slant_end - slant_start) / (double)ons;
    }

    asfRequire(onl > 0, "Internal Error: Invalid output line count: %d\n", onl);
    asfRequire(ons > 0, "Internal Error: Invalid output sample count: %d\n", ons);

    asfPrintStatus("  Slant range values: %f -> %f\n", slant_start, slant_end);
    asfPrintStatus("  Slant range pixel size: %f\n", pixel_size);
    asfPrintStatus("  Time values: %f -> %f\n", time_start, time_end);
    asfPrintStatus("  Output Image will be %5d x %5d LxS\n", onl, ons);
    asfPrintStatus("      (Input Image was %5d x %5d LxS)\n", nl, ns);

    // generate a grid over the image, to generate our splines
    // this grid size seems to work pretty well...
    int n = 120;

    asfPrintStatus("Creating %dx%d mapping grid...\n", n, n);
 
    // changed how these are calculated, so that the spline will cover
    // the entire value range
    double time_grid_incr = fabs(time_end - time_start) / (double)(n-1);
    if (time_incr < 0) time_grid_incr = -time_grid_incr;
    double slant_grid_incr = fabs(slant_end - slant_start) / (double)(n-1);
    if (slant_incr < 0) slant_grid_incr = -slant_grid_incr;    

    // allocating memory for the splines, and the arrays to generate them
    gsl_interp_accel **samp_accels = MALLOC(sizeof(gsl_interp_accel *) * n);
    gsl_spline **samp_splines = MALLOC(sizeof(gsl_spline *) * n);

    gsl_interp_accel **line_accels = MALLOC(sizeof(gsl_interp_accel *) * n);
    gsl_spline **line_splines = MALLOC(sizeof(gsl_spline *) * n);

    double *slant_in = MALLOC(sizeof(double)*n);
    double *line_out = MALLOC(sizeof(double)*n);
    double *samp_out = MALLOC(sizeof(double)*n);

    // an alias -- use the same array (to save memory -- these are not used
    // at the same time), but create an alias for it, so it is not so confusing
    double *time_in = slant_in;
    //double max_err = 0;

    // set up the vertical splines
    for (jj=0; jj<n; ++jj) {
        double slant = slant_start + jj*slant_grid_incr;

        for (ii=0; ii<n; ++ii) {
            // splines need strictly increasing range variables
            if (time_grid_incr > 0)
                time_in[ii] = time_start + ii*time_grid_incr;
            else
                time_in[ii] = time_end - ii*time_grid_incr;

            ts2ls(inMeta, time_in[ii], slant, &line_out[ii], &samp_out[ii]);
            //printf("time: %f, slant: %f ==> line: %f, samp %f\n",
            //       time_in[ii], slant, line_out[ii], samp_out[ii]);
        }

        samp_accels[jj] = gsl_interp_accel_alloc();
        samp_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n);
        gsl_spline_init(samp_splines[jj], time_in, samp_out, n);

        line_accels[jj] = gsl_interp_accel_alloc();
        line_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n);
        gsl_spline_init(line_splines[jj], time_in, line_out, n);
    }

    // now, we're on to the resampling stage.. loop through output pixels
    asfPrintStatus("Generating slant range image...\n");

    double no_data_value = meta_is_valid_double(inMeta->general->no_data) ?
        inMeta->general->no_data : 0;

    // keep track of error sizes
    double max_error = 0;
    double avg_error = 0;
    int count = 0;

    // these stride values allow us to track when we're in between grid points
    int ii_n = onl/n;
    int jj_n = ons/n;
    int ii_n2 = ii_n/2;
    int jj_n2 = jj_n/2;

    // set up output metadata
    meta_parameters *outMeta = meta_read(infile);

    if (outMeta->transform) {
        FREE(outMeta->transform);
        outMeta->transform = NULL;
    }

    if (outMeta->projection) {
        FREE(outMeta->projection);
        outMeta->projection = NULL;
    }

    outMeta->general->line_count = onl;
    outMeta->general->sample_count = ons;

    if (!outMeta->sar)
        outMeta->sar = meta_sar_init();

    outMeta->sar->image_type = 'S';

    outMeta->sar->azimuth_time_per_pixel = time_incr;
    assert(outMeta->sar->azimuth_time_per_pixel < 0);

    outMeta->sar->time_shift = time_start;

    outMeta->general->y_pixel_size = inMeta->sar->azimuth_time_per_pixel / 
                                     time_incr * inMeta->general->y_pixel_size;
    assert(outMeta->general->y_pixel_size > 0);

    outMeta->sar->slant_range_first_pixel = slant_start;
    outMeta->general->x_pixel_size = slant_incr;

    outMeta->sar->line_increment = outMeta->sar->sample_increment = 1;
    outMeta->general->start_sample = outMeta->general->start_line = 0;

    outMeta->general->no_data = no_data_value;

    char **band_name = extract_band_names(inMeta->general->bands,
                                          inMeta->general->band_count);

    // now generate output image
    char *img_file = appendExt(outfile, ".img");
    float *out = MALLOC(sizeof(float) * ons);

    for (kk=0; kk<inMeta->general->band_count; ++kk) {
        if (inMeta->general->band_count != 1)
            asfPrintStatus("Working on band: %s\n", band_name[kk]);

        // for the 2nd and higher bands, free the band from the previous iteration,
        // and read in the next band from the input image
        if (kk>0) {
            float_image_free(in);
            asfPrintStatus("Loading input...\n");
            in = float_image_band_new_from_metadata(inMeta, kk, infile);
        }

        FILE *ofp = FOPEN(img_file, kk==0 ? "wb" : "ab");
        asfPrintStatus("Generating output...\n");
        for (ii=0; ii<onl; ++ii) {
            asfLineMeter(ii,onl);
            double time = time_start + ii * time_incr;

            // set up horizontal splines for this row
            gsl_interp_accel *samp_accel = gsl_interp_accel_alloc();
            gsl_spline *samp_spline = gsl_spline_alloc(gsl_interp_cspline, n);

            gsl_interp_accel *line_accel = gsl_interp_accel_alloc();
            gsl_spline *line_spline = gsl_spline_alloc(gsl_interp_cspline, n);

            //printf("time: %f slant: %f\n", time, slant_start);
            for (jj=0; jj<n; ++jj) {
                slant_in[jj] = slant_start + jj * slant_grid_incr;
                //printf("time: %f slant: %f\n", time, slant_in[jj]);
                samp_out[jj] = gsl_spline_eval_check(samp_splines[jj], time,
                                               samp_accels[jj]);
                line_out[jj] = gsl_spline_eval_check(line_splines[jj], time,
                                               line_accels[jj]);
                //printf("samp_out: %f line_out: %f\n", samp_out[jj], line_out[jj]);
            }

            gsl_spline_init(samp_spline, slant_in, samp_out, n);
            gsl_spline_init(line_spline, slant_in, line_out, n);

            // use the splines to produce output pixels
            for (jj=0; jj<ons; ++jj) {
                double slant = slant_start + jj * slant_incr;
                double samp = gsl_spline_eval_check(samp_spline, slant, samp_accel);
                double line = gsl_spline_eval_check(line_spline, slant, line_accel);

                // check the spline every so often (halfway between grid points)
                // only do this on band #1 (the reference band)
                if (kk==0 && ii%ii_n2==0 && 
                    ii%ii_n!=0 && jj%jj_n2==0 && jj%jj_n!=0)
                {
                    double samp_real, line_real;
                    ts2ls(inMeta, time, slant, &line_real, &samp_real);

                    double err = (line-line_real)*(line-line_real) +
                                 (samp-samp_real)*(samp-samp_real);

                    //printf("(%d,%d) -- Actual: (%f,%f) Splined: (%f,%f)\n",
                    //       ii, jj, line_real, samp_real, line, samp);

                    if (err > max_error) max_error = err;
                    avg_error += err;
                    ++count;
                }

                // now interpolate within the original image
                // if we are outside, use "no_data" from metadata
                double val = no_data_value;
                if (line > 0 && line < nl-1 && samp > 0 && samp < ns-1)
                    val = float_image_sample(in, samp, line, sampling_method);

                out[jj] = (float)val;
            }

            gsl_interp_accel_free(samp_accel);
            gsl_spline_free(samp_spline);

            gsl_interp_accel_free(line_accel);
            gsl_spline_free(line_spline);

            put_float_line(ofp, outMeta, ii, out);
        }

        fclose(ofp);
    }

    // free the last band of the input
    float_image_free(in);

    FREE(slant_in);
    FREE(line_out);
    FREE(samp_out);

    for (ii=0; ii<n; ++ii) {
        gsl_interp_accel_free(samp_accels[ii]);
        gsl_spline_free(samp_splines[ii]);
        gsl_interp_accel_free(line_accels[ii]);
        gsl_spline_free(line_splines[ii]);
    }

    FREE(samp_accels);
    FREE(samp_splines);
    FREE(line_accels);
    FREE(line_splines);

    FREE(out);

    for (kk=0; kk<inMeta->general->band_count; ++kk)
        FREE(band_name[kk]);
    FREE(band_name);

    // see how bad our errors were
    avg_error /= (double)count;
    asfPrintStatus("Model max error: %f, avg: %f\n",
                   max_error, avg_error);

    double thresh = 0.1;
    if (max_error > 100*thresh)
        asfPrintError("Maximum error exceeded threshold: %f > %f\n",
                      max_error, 100*thresh);
    else if (avg_error > 10*thresh)
        asfPrintError("Average error exceeded threshold: %f > %f\n",
                      avg_error, 10*thresh);
    if (max_error > 10*thresh)
        asfPrintWarning("Maximum error exceeds threshold: %f > %f\n",
                        max_error, 10*thresh);
    if (avg_error > thresh)
        asfPrintWarning("Average error exceeds threshold: %f > %f\n",
                        avg_error, thresh);

    char *meta_file = appendExt(outfile, ".meta");
    asfPrintStatus("Writing %s\n", meta_file);
    meta_write(outMeta, meta_file);
    free(meta_file);
    free(img_file);

    meta_free(outMeta);
    meta_free(inMeta);

    return 0; //success
}
Ejemplo n.º 23
0
int asf_windspeed(platform_type_t platform_type, char *band_id,
                  double wind_dir, int cmod4,
                  double landmaskHeight, char *landmaskFile, char *demFile,
                  char *inBaseName, char *colormapName, char *outBaseName)
{
  char *inDataName, outDataName[1024], outMetaName[1024];
  FILE *in = NULL, *out = NULL;

  asfPrintStatus("\n   Determining windspeeds in: %s\n", inBaseName);

  strcpy(outDataName, outBaseName);
  strcpy(outMetaName, outBaseName);
  inDataName = (char *)MALLOC(sizeof(char) * (strlen(inBaseName) + 10));
  strcpy(inDataName, inBaseName);
  append_ext_if_needed(inDataName, ".img", NULL);
  append_ext_if_needed(outDataName, ".img", NULL);
  append_ext_if_needed(outMetaName, ".meta", NULL);

  // New images for processing in to out
  meta_parameters *imd = meta_read(inBaseName);
  meta_general *img = imd->general; // convenience ptr
  meta_parameters *omd = meta_read(inBaseName);
  meta_general *omg = omd->general; // convenience ptr
  meta_sar *oms = omd->sar; // convenience ptr
  omg->band_count = 0;
  strcpy(omg->bands, "");
  strcpy(oms->polarization, "");
  if (strstr(img->bands, "VV") == NULL && strstr(img->bands, "HH") == NULL) {
    asfPrintError("Cannot find any VV or HH polarized bands in this data.  Available\n"
        "bands are %s).  Wind speeds can only be determined on Sigma0-\n"
        "calibrated SAR data in HH or VV polarizations.\n", img->bands);
  }
  in = (FILE *)FOPEN(inDataName, "rb");
  out = (FILE *)FOPEN(outDataName, "wb");
  FREE(inDataName);

  // For each band
  double alpha = 1.0; // Default for VV polarization;
  int band_num;
  float *data = (float *)MALLOC(sizeof(float) * img->sample_count);
  for (band_num = 0; band_num < img->band_count; band_num++) {
    // Get band name, check for proper polarization, and create new output bandname, set alpha
    char *band_name = get_band_name(img->bands, img->band_count, band_num);
    long offset = img->line_count * band_num;
    char polarization[2]="";
    if (strncmp_case(band_name, "SIGMA-VV", 8) == 0 ||
        strncmp_case(band_name, "SIGMA-HH", 8) == 0)
    {
      asfPrintStatus("\nProcessing wind speed calculations on band %s...\n\n", band_name);

      (omg->band_count)++;
      strcpy(polarization, (strstr(band_name, "VV") != NULL) ? "VV" : "HH");
      strcpy(oms->polarization, polarization);
      sprintf(&omg->bands[strlen(omg->bands)], "%s%s%s", WINDSPEED_BAND_BASENAME, polarization,
              (band_num < img->band_count - 1 && img->band_count > 0) ? ", " : "");
      alpha = (strcmp(polarization, "VV") == 0) ? 1.0 : DEFAULT_HH_POL_ALPHA; // For CMODx
    }
    else {
      asfPrintStatus("\nFound band: %s (Cannot calculate wind speed on this type of band)\n\n",
                     band_name);
      continue; // Skip this band
    }

    // Calculate average r_look for entire image (r_look is the angle between the NADIR line
    // and a line point directly north, the 'look angle' of the platform.)
    double r_look = asf_r_look(imd);
    double phi_diff = wind_dir - r_look;

    // Pre-populate incidence angles (as a function of sample) and get min/max incidence angle
    // as well
    int line, sample;
    double *incids = (double *)MALLOC(img->sample_count * sizeof(double));
    double min_incid = DBL_MAX;
    double max_incid = DBL_MIN;
    for (sample = 0; sample < img->sample_count; sample++) {
      incids[sample] = R2D * meta_incid(imd, img->line_count / 2, sample);
      min_incid = (incids[sample] < min_incid) ? incids[sample] : min_incid;
      max_incid = (incids[sample] > max_incid) ? incids[sample] : max_incid;
    }

    // Get min/max radar cross-sections
    asfPrintStatus("\nFinding min/max radar cross-sections...\n\n");
    double rcs_min = DBL_MAX;
    double rcs_max = DBL_MIN;
    for (line = 0; line < img->line_count; line++) {
      // Get a line
      get_float_line(in, imd, line+offset, data);
      for (sample = 0; sample < img->sample_count; sample++) {
        if (meta_is_valid_double(data[sample]) && data[sample] >= 0.0) {
          rcs_min = (data[sample] < rcs_min) ? data[sample] : rcs_min;
          rcs_max = (data[sample] > rcs_max) ? data[sample] : rcs_max;
        }
      }
      asfLineMeter(line, img->line_count);
    }

    // FIXME: Generate 2D array of windspeeds here.  One dimension is incidence angle and
    // the other is radar cross-section.  The values in the table are wind speed as a function
    // of incidence angle and radar cross-section (given the provided wind direction.)  The idea
    // is to more-quickly populate a grid of results and then to interpolate results for each
    // pixel of the image rather then perform the full calculation (very sloooow)

    double windspeed1 = 0.0, windspeed2 = 0.0;
    for (line = 0; line < img->line_count; line++) {
      // Get a line
      get_float_line(in, imd, line+offset, data);
      for (sample = 0; sample < img->sample_count; sample++) {
        // FIXME: Here is where we should apply a land mask ...in this if-statement expression
        if (meta_is_valid_double(data[sample]) && data[sample] >= 0.0) {
          // Calculate windspeed
          // FIXME: This returns the angle, at the target pixel location, between straight up
          // and the line to the satellite.  Make sure Frank's code doesn't assume the angle
          // between the line to the satellite and a horizontal line, i.e. 90 degrees minus
          // this angle.
          double incidence_angle = incids[sample];
          switch (platform_type) {
            case p_RSAT1:
              if (!cmod4) {
                // Use CMOD5 to calculate windspeeds
                double hh = alpha;
                ws_inv_cmod5((double)data[sample], phi_diff, incidence_angle,
                             &windspeed1, &windspeed2,
                             (double)MIN_CMOD5_WINDSPEED, (double)MAX_CMOD5_WINDSPEED, 25,
                             hh);
                data[sample] = windspeed1; // When 2 answers exist, take the lower (per Frank Monaldo)
              }
              else {
                // Use CMOD4 to calculate windspeeds
                asfPrintError("The CMOD4 algorithm is not yet supported.  Avoid the -cmod4\n"
                    "option for now and let %s default to using the CMOD5 algorithm\n"
                    "instead.\n");
              }
              break;
            case p_PALSAR:
            case p_TERRASARX:
            case p_ERS1:
            case p_ERS2:
            default:
              asfPrintError("Found a platform type (%s) that is not yet supported.\n",
                            (platform_type == p_PALSAR)    ? "PALSAR" :
                            (platform_type == p_TERRASARX) ? "TerraSAR-X" :
                            (platform_type == p_ERS1)      ? "ERS-1" :
                            (platform_type == p_ERS2)      ? "ERS-2" : "UNKNOWN PLATFORM");
          }
        }
      }
      put_float_line(out, omd, line+offset, data);
      asfLineMeter(line, img->line_count);
    }
  } // end for (each band)
  FREE(data);

  // Insert colormap into metadata

  meta_write(omd, outMetaName);
  meta_free(imd);
  meta_free(omd);

  asfPrintStatus("Windspeed calculation complete.\n\n");

  return EXIT_SUCCESS;
}
Ejemplo n.º 24
0
void c2p_ext(const char *inDataName, const char *inMetaName,
             const char *outfile, int multilook, int banded)
{
    meta_parameters *in_meta = meta_read(inMetaName);
    int data_type = in_meta->general->data_type;
    // the old code did this, but why??
    in_meta->general->data_type = meta_polar2complex(data_type);

    // some sanity checks
    switch (data_type) {
      case COMPLEX_BYTE:
      case COMPLEX_INTEGER16:
      case COMPLEX_INTEGER32:
      case COMPLEX_REAL32:
      case COMPLEX_REAL64:
          break;
      default:
          asfPrintError("c2p: %s is not a complex image.\n", inDataName);
    }

    if (in_meta->general->band_count != 1)
        asfPrintError("c2p: %s is not a single-band image.\n", inDataName);

    if (!in_meta->sar)
        asfPrintError("c2p: %s is missing a SAR block.\n", inDataName);

    asfPrintStatus("Converting complex image to amplitude/phase...\n");

    int nl = in_meta->general->line_count;
    int ns = in_meta->general->sample_count;
    // process 1 line at a time when not multilooking, otherwise grab nlooks
    int nlooks = multilook ? in_meta->sar->look_count : 1;

    if (nlooks == 1 && multilook) {
        asfPrintStatus("Not multilooking, look_count is 1.\n");
        multilook = FALSE;
    }

    if (multilook)
        asfPrintStatus("Multilooking with %d looks.\n", nlooks);

    meta_parameters *out_meta = meta_read(inMetaName);
    out_meta->general->data_type = meta_complex2polar(data_type);

    // set up input/output files
    FILE *fin = fopenImage(inDataName, "rb");

    // we either have 1 or 2 output files, per the "banded" flag.
    char *outfile_img = appendExt(outfile, ".img");
    char *amp_name=NULL, *phase_name=NULL;
    FILE *fout_banded=NULL, *fout_amp=NULL, *fout_phase=NULL;
    if (banded) {
        asfPrintStatus("Output is 2-band image: %s\n", outfile_img);
        fout_banded = fopenImage(outfile_img, "wb");
    } else {
        amp_name = appendToBasename(outfile_img, "_amp");
        phase_name = appendToBasename(outfile_img, "_phase");
        asfPrintStatus("Output amplitude file: %s\n", amp_name);
        asfPrintStatus("Output phase file: %s\n", phase_name);
        fout_amp = fopenImage(amp_name, "wb");
        fout_phase = fopenImage(phase_name, "wb");
    }
    if (banded)
        assert(fout_banded && !fout_amp && !fout_phase);
    else
        assert(!fout_banded && fout_amp && fout_phase);

    // get the metadata band_count correct, needed in the put_* calls
    if (banded) {
        out_meta->general->band_count = 2;
        strcpy(out_meta->general->bands, "AMP,PHASE");
    }

    // input buffer
    complexFloat *cpx = MALLOC(sizeof(complexFloat)*ns*nlooks);

    // output buffers
    float *amp = MALLOC(sizeof(float)*ns*nlooks);
    float *phase = MALLOC(sizeof(float)*ns*nlooks);

    int line_in;    // line in the input image
    int line_out=0; // line in the output image
    int samp;       // sample #, loop index
    int l;          // line loop index, iterates over the lines in the block

    out_meta->general->line_count = (int)ceil((double)nl/(double)nlooks);

    for (line_in=0; line_in<nl; line_in+=nlooks)
    {
        // lc = "line count" -- how many lines to read. normally we will read
        // nlooks lines, but near eof we might have to read fewer
        int lc = nlooks; 
        if (line_in + lc > nl)
            lc = nl - line_in;

        // read "nlooks" (or possibly fewer, if near eof) lines of data
        int blockSize = get_complexFloat_lines(fin,in_meta,line_in,lc,cpx);
        if (blockSize != lc*ns)
            asfPrintError("bad blockSize: bs=%d nlooks=%d ns=%d\n", 
			  blockSize, nlooks, ns);

        // first, compute the power/phase
        for (l=0; l<lc; ++l) {
            for (samp=0; samp<ns; ++samp) {
                int k = l*ns + samp; // index into the block
                float re = cpx[k].real;
                float im = cpx[k].imag;
                if (re != 0.0 || im != 0.0) {
                    amp[k] = re*re + im*im;
                    phase[k] = atan2(im, re);
                } else {
                    amp[k] = phase[k] = 0.0;
                }
            }
        }

        // now multilook, if requested
        if (multilook) {
            // put the multilooked data in the first "row" of amp,phase
            for (samp=0; samp<ns; ++samp) {
                float value = 0.0;
                for (l=0; l<lc; ++l)
                    value += amp[l*ns + samp];
                amp[samp] = sqrt(value/(float)lc);

                value = 0.0;
                for (l=0; l<lc; ++l)
                    value += phase[l*ns + samp];
                phase[samp] = value/(float)lc;
            }
        }
        else {
            for (samp=0; samp<ns*lc; ++samp)
                amp[samp] = sqrt(amp[samp]);
        }

        // write out a line (multilooked) or a bunch of lines (not multi)
        if (multilook) {
            if (banded) {
                put_band_float_line(fout_banded, out_meta, 0, line_out, amp);
                put_band_float_line(fout_banded, out_meta, 1, line_out, phase);
            } else {
                put_float_line(fout_amp, out_meta, line_out, amp);
                put_float_line(fout_phase, out_meta, line_out, phase);
            }
            ++line_out;
        } else {
            for (l=0; l<lc; ++l) {
                if (banded) {
                    put_band_float_line(fout_banded, out_meta, 0, line_in+l, amp);
                    put_band_float_line(fout_banded, out_meta, 1, line_in+l, phase);
                } else {
                    put_float_line(fout_amp, out_meta, line_in+l, amp);
                    put_float_line(fout_phase, out_meta, line_in+l, phase);
                }
                ++line_out;
            }
        }

        asfPercentMeter((float)line_in/(float)(nl));
    }
    asfPercentMeter(1.0);

    fclose(fin);
    if (fout_banded) fclose(fout_banded);
    if (fout_amp) fclose(fout_amp);
    if (fout_phase) fclose(fout_phase);

    if (multilook) {
        if (out_meta->general->line_count != line_out)
            asfPrintError("Line counts don't match: %d != %d\n",
                out_meta->general->line_count, line_out);
        out_meta->general->y_pixel_size *= nlooks;
        out_meta->sar->azimuth_time_per_pixel *= nlooks;
        out_meta->sar->multilook = TRUE;
    } else
        assert(line_out == nl);

    // write out the metadata, different whether multi-banded or not
    if (banded) {
        assert(!amp_name && !phase_name);
        meta_write(out_meta, outfile);
    } else {
        assert(amp_name && phase_name);
        
        out_meta->general->image_data_type = AMPLITUDE_IMAGE;
        meta_write(out_meta, amp_name);
        
        out_meta->general->image_data_type = PHASE_IMAGE;
        meta_write(out_meta, phase_name);
    }

    if (multilook)
        asfPrintStatus("Original line count: %d, after multilooking: %d "
            "(%d looks)\n", nl, line_out, nlooks);

    meta_free(in_meta);
    meta_free(out_meta);

    FREE(amp);
    FREE(phase);
    FREE(cpx);

    FREE(outfile_img);

    FREE(amp_name);
    FREE(phase_name);
}
Ejemplo n.º 25
0
static void add_to_stack(char *out, int band, char *file,
                         int size_x, int size_y,
                         double start_x, double start_y,
                         double per_x, double per_y, int multiband)
{
    meta_parameters *metaIn = meta_read(file);
    meta_parameters *metaOut = meta_read(out);
    char *base = (char *) MALLOC(sizeof(char)*512);
    int start_line, start_sample;

    // this should work even if per_x / per_y are negative...
    start_sample = (int) ((start_x - metaIn->projection->startX) / per_x + .5);
    start_line = (int) ((start_y - metaIn->projection->startY) / per_y + .5);

    int ns = metaIn->general->sample_count;
    int nl = metaIn->general->line_count;

    asfPrintStatus("  Location in stacked image is S:%d-%d, L:%d-%d\n",
        start_sample, start_sample + size_x,
        start_line, start_line + size_y);

    if (start_sample + size_x > ns || start_line + size_y > nl) {
        asfPrintError("Image extents were not calculated correctly!\n");
    }

    FILE *fpIn = FOPEN(file, "rb");
    FILE *fpOut;
    char *metaFile = appendExt(out, ".meta");
    if (band > 0 || !multiband) {
      fpOut = FOPEN(out, "ab");
      sprintf(base, ",%s", get_basename(file));
      strcat(metaOut->general->bands, base);
    }
    else {
      fpOut = FOPEN(out, "wb");
      sprintf(base, "%s", get_basename(file));
      strcpy(metaOut->general->bands, base);
    }
    if (multiband)
      metaOut->general->band_count = band + 1;
    else
      metaOut->general->band_count = 1;
    meta_write(metaOut, metaFile);
    float *line = MALLOC(sizeof(float)*size_x);

    int y;
    for (y=start_line; y<start_line+size_y; ++y) {
      get_partial_float_line(fpIn, metaIn, y, start_sample, size_x, line);
      if (multiband) 
	put_band_float_line(fpOut, metaOut, band, y-start_line, line); 
      else
	put_float_line(fpOut, metaOut, y-start_line, line); 
      asfLineMeter(y, start_line+size_y);
    }

    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(line);
    FREE(metaFile);
    FREE(base);
    meta_free(metaIn);
    meta_free(metaOut);
}
Ejemplo n.º 26
0
int main(int argc, char *argv[])
{
  char basename[256];
  char *airsarname;
  char *outname;
  char *ext;
  char *off_char;

  int *ibuff;			/* Input and output buffers		*/
  float *obuff;
  unsigned char *obuff_char;

  FILE *fpOut;			
  FILE *fpIn;

  int nl, ns;			/* Number of lines, number of samples	*/
  int y, x;			/* Counters				*/
  int hb, lb;			/* Header Bytes, Line Bytes		*/
  int demi2=0;			/* Is this a DEM?			*/

  float incr=1;
  float offset=0;

  meta_parameters *meta;

  if(argc != 3){
    printf("Usage:	%s inSARfile outLASfile\n",argv[0]);
    printf("\tinput: inSARfile, an AirSAR image\n");
    printf("\toutput: outLASfile, a LAS image (.img and .ddr)\n");

    printf("\nAirsarin reads an AirSAR image, and\n");
    printf("converts it to the format used by our \n");
    printf("other tools.\n");
    printf("This is often the first step in analysing a SAR image.\n");
    printf("\nVersion %.2f, ASF STEP Tools\n",VERSION);
    exit(1);
  }

  airsarname=argv[1];
  outname=argv[2];

/* Strip the extension off for the basename */
  strcpy(basename, airsarname);
  ext = strchr(basename, '.');

  if(!strcmp(".demi2",ext)) demi2=1;
  *ext = '\0';
  if(demi2==1) printf("It's a DEM!\n");
  else printf("Hrmmm....\n");

/* Create the output ddr */
  meta = raw_init();
  airsar2meta(airsarname, meta);
  if (demi2)
    meta->general->image_data_type = DEM;
  else
    meta->general->image_data_type = AMPLITUDE_IMAGE;
  meta_write(meta, outname);
  fpOut = fopenImage(outname, "wb");
  ns = meta->general->sample_count;
  nl = meta->general->line_count;

/* Allocate buffer space */
  ibuff = (int *) malloc(ns * sizeof(int));
  obuff = (float *)malloc(ns * sizeof(float));
  obuff_char =(unsigned char*)malloc(ns * sizeof(unsigned char));

/* Determine the headerBytes and the length of each line */
  hb = atoi(get_airsar(airsarname,"FIRST","BYTE OFFSET OF FIRST DATA RECORD"));
  lb = atoi(get_airsar(airsarname,"FIRST","RECORD LENGTH IN BYTES"));

  if(demi2){
    off_char = (char *)malloc(sizeof(char));
    strcpy(off_char, get_airsar(airsarname,"DEM","ELEVATION OFFSET"));
    offset = atof(off_char); 
    incr = atof( get_airsar(airsarname,"DEM","ELEVATION INCREMENT"));
    printf("offset should be = \t%s\n", off_char);
    printf("offset = \t\t%f\n", offset);
    printf("increment = \t\t%f\n", incr);
  }

  printf("\nBeginning IMG conversion...\n");

  fpIn = FOPEN(airsarname, "r");

/* Read input file, convert, and write to output file */
  for (y = 0; y< nl; y++)
  {
    readAirSARLine(fpIn, ibuff, hb, lb, y, meta);
    
    if( meta->general->data_type == BYTE) {
      for (x = 0; x< ns; x++)
	obuff_char[x]=(unsigned char)ibuff[x];
      FWRITE(obuff_char, ns, 1, fpOut);
    }
    else {
      for (x = 0; x < ns; x++){
	obuff[x]=(float)ibuff[x];
	
	if(obuff[x]!=49152)obuff[x]=obuff[x]*incr+offset;
	else obuff[x]=0;
      }
      put_float_line(fpOut, meta, y, obuff);
    }
    if ((y % 500) == 0)
      printf("Now Processing Line No = %d \n", y);
  }

  FCLOSE(fpOut);
  FCLOSE(fpIn);

  return 0;
}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
	char *baseFile;
	meta_parameters *meta;
	baseline base;
	int   wid, len,		/* Width and Length of input scene    */
		ss, sl;		/* Offsets of input scene in original */
	int x,y;
	double xScale,yScale;
	float percent=5.0;
	
	FILE  *fin, *fout;
	char  szInPhase[255], szInAmp[255], szOutPhase[255], szOutAmp[255];
	float *data;
	double *sflat,*cflat;
	double derampDirection=1.0;/*1.0=forward deramping.  -1.0=backward deramping.*/
	logflag=0;

/* process command line args */
	currArg=1; /* from cla.h in asf.h */
	/* optional args */
	while (currArg < (argc-3)) {
		char *key = argv[currArg++];
		if (strmatch(key,"-log")) {
			CHECK_ARG(1);
			strcpy(logFile,GET_ARG(1));
			fLog = FOPEN(logFile, "a");
			logflag=1;
		}
		else if (strmatch(key,"-backward")) {
			derampDirection = -1.0;
		}
		else {printf("**Invalid option: %s\n",argv[currArg-1]); usage(argv[0]);}
	}
	if ((argc-currArg) < 3) {printf("Insufficient arguments.\n"); usage(argv[0]);}
	/* required args */
	create_name(szInAmp, argv[currArg], "_amp.img");
	create_name(szInPhase, argv[currArg], "_phase.img");
	baseFile = argv[currArg+1];

	asfSplashScreen(argc, argv);
	
	/* Get input scene size and windowing info, check validity */
	meta = meta_read(szInPhase);

	wid = meta->general->sample_count;
	len = meta->general->line_count;
	ss = meta->general->start_sample - 1;
	sl = meta->general->start_line - 1;
	xScale = meta->sar->sample_increment;
	yScale = meta->sar->line_increment;
	
	create_name(szOutAmp,argv[currArg+2],"_amp.img");
	meta_write(meta, szOutAmp);
	create_name(szOutPhase,argv[currArg+2],"_phase.img");
	meta_write(meta, szOutPhase);

	/*Link over ".amp" file, if it exists.*/
	if (fileExists(szInAmp)&&!fileExists(szOutAmp))
	{
		char command[1024];
		sprintf(command,"ln -s %s %s\n", szInAmp, szOutAmp);
		system(command);
	}
	
	/* buffer mallocs, read data file */
	data = (float *)MALLOC(sizeof(float)*wid);
	sflat = (double *)MALLOC(sizeof(double)*wid);
	cflat = (double *)MALLOC(sizeof(double)*wid);
	fin = fopenImage(szInPhase,"rb");
	fout = fopenImage(szOutPhase,"wb");
	
	/* read in CEOS parameters & convert to meters */
	base=read_baseline(baseFile);
	
	/* calculate slant ranges and look angles - Ian's thesis eqn 3.10 */
	for (x = 0; x < wid; x++) {
		double flat=meta_flat(meta,0.0,x*xScale+ss);
		sflat[x]=sin(flat);
		cflat[x]=cos(flat);
	}
	/* Deramp 'data' array */
	
/*	printf("\n  starting in-place deramp of input data \n\n");*/
	for (y = 0; y < len; y++)
	{
		double Bn_y,Bp_y;
		double twok=derampDirection*2.0*meta_get_k(meta);
		meta_interp_baseline(meta,base,y*(int)yScale+sl,&Bn_y,&Bp_y);
		/* read in the next row of data */
		get_float_line(fin, meta, y, data);
		
		/* calculate flat-earth range phase term & remove it */ 
		for (x = 0; x < wid; x++)
		{
			double d=data[x];
			if (d!=0.0) /*Ignore points which didn't phase unwrap.*/
				d -= twok*(Bp_y*cflat[x]-Bn_y*sflat[x]);
			/*Was: d-=ceos_flat_phase(ceos,base,x,y);*/
			data[x]=d;
		}
		
		/* write out this row of data */
		put_float_line(fout, meta, y, data);
		if (y*100/len==percent) {
		  printf("   Completed %3.0f percent\n", percent);
		  percent+=5.0;
		}
	}
/*	printf("\nDone with deramp\n\n");*/
	
	/* save and scram */
	FCLOSE(fin); FCLOSE(fout);
	FREE(data); FREE(sflat);FREE(cflat);

	printf("   Completed 100 percent\n\n");
	if (logflag) {
	  sprintf(logbuf, "   Wrote %lld bytes of data\n\n", (long long)(len*wid*4));
	  printLog(logbuf);
	}

	return 0;
}
Ejemplo n.º 28
0
int asf_elevation(char *unwrapped_phase, char *phase_mask, 
		  char *baseFile, char *seeds, char *slant_elevation,
		  char *slant_elevation_error, char *slant_amplitude, 
		  char *slant_coherence, char *ground_elevation, 
		  char *ground_elevation_error, char *ground_amplitude, 
		  char *ground_coherence)
{

  int x, y, ss, sl, nrows, ncols;
  double xScale, yScale, k, *phase2elevBase, *sinFlat, *cosFlat;
  meta_parameters *meta;
  baseline base;
  FILE *fphase, *felev, *feleverr, *fseed, *fmask, *fcoh;
  float *uwp, *coh, *elev, *eleverr;
  unsigned char *mask;
  double delta_phase, delta_height;
  double seed_phase, seed_height;

  printf("\nGenerating slant range elevation and elevation error ...\n\n");

  /* Get input scene size and windowing info. Get datafile values*/
  meta = meta_read(unwrapped_phase);
  nrows  = meta->general->line_count;
  ncols  = meta->general->sample_count;
  sl     = meta->general->start_line;
  ss     = meta->general->start_sample;
  yScale = meta->sar->look_count;
  xScale = meta->sar->sample_increment;
  
  // Write metadata files for temporary slant range images
  //  meta->general->image_data_type = DEM;
  meta_write(meta, slant_elevation);
  meta_write(meta, slant_elevation_error);
  
  /* Allocate space for vectors and matricies*/
  uwp = (float *) MALLOC(sizeof(float)*ncols);
  coh = (float *) MALLOC(sizeof(float)*ncols);
  elev = (float *) MALLOC(sizeof(float)*ncols);
  eleverr = (float *) MALLOC(sizeof(float)*ncols);
  mask = (unsigned char *) MALLOC(sizeof(unsigned char)*ncols);

  // Wavenumber K
  k = meta_get_k(meta);

  // Read in baseline values
  base = read_baseline(baseFile);
  
  // Open input files
  fphase = fopenImage(unwrapped_phase, "rb");
  fseed = FOPEN(seeds, "r");
  fmask = fopenImage(phase_mask, "rb");
  fcoh = fopenImage(slant_coherence, "rb");
  
  /*Use least-squares fit to determine the optimal seed_phase and seed_height.*/
  {
    double x,xSum=0,xSqrSum=0,hSum=0,hxSum=0,pxSum=0,pxSqrSum=0;
    double a,b,c,d,e,f,det;
    int npts=0;
    float *phase_line;
    
    phase_line = (float *) MALLOC(sizeof(float)*meta->general->sample_count);
    
    while (1)
      {
	float seed_x,seed_y,height,phase;
	int seek_x,seek_y;
	/*Read in each seed point*/
	if (3!=fscanf(fseed,"%f%f%f",&seed_x,&seed_y,&height))
	  break;/*Break out when no more points.*/
	seek_x=(int)((seed_x-ss)/xScale);
	seek_y=(int)((seed_y-sl)/yScale);
	get_float_line(fphase, meta, seek_y, phase_line);
	phase = phase_line[seek_y];
	if (phase==0)
	  continue;/*Escher couldn't unwrap this tie point.*/
	
	// Calculate that seed point's impact on fit.
	x         = meta_phase_rate(meta,base,seed_y,seed_x);
	xSum     += x;
	xSqrSum  += x * x;
	hSum     += height;
	hxSum    += height * x;
	pxSum    += phase * x;
	pxSqrSum += phase * x * x;
	npts++;
      }
    if (!quietflag)
      printf("   Read %d seed points\n",npts);
    /* The least-squares fit above leaves us with a matrix equation
     *	[ a  b ]   [ seed_phase  ]   [ e ]
     *	[      ] * [             ] = [   ]
     *	[ c  d ]   [ seed_height ]   [ f ]
     *
     *	which has the solution
     *
     *	[ d  -b ]   [ e ]    1    [ seed_phase  ]
     *	[       ] * [   ] * --- = [             ]
     *	[ -c  a ]   [ f ]   det   [ seed_height ]
     */
    a = -xSqrSum;
    b = xSum;
    c = -xSum;
    d = npts;
    e = hxSum-pxSqrSum;
    f = hSum-pxSum;
    det = a*d-b*c;
    seed_phase  = (e*d-f*b)/det;
    seed_height = (e*(-c)+f*a)/det;
  }
  
  if (!quietflag) 
    printf("   Seed Phase: %f\n   Elevation: %f\n\n",seed_phase,seed_height);
  
  /* calculate the sine of the incidence angle across cols*/
  sinFlat = (double *)MALLOC(sizeof(double)*ncols);
  cosFlat = (double *)MALLOC(sizeof(double)*ncols);
  phase2elevBase = (double *)MALLOC(sizeof(double)*ncols);
  for (x=0;x<ncols;x++)
    {
      int img_x = x*xScale + ss;
      double incid = meta_incid(meta, 0, img_x);
      double flat = meta_flat(meta, 0, img_x);
      sinFlat[x] = sin(flat);
      cosFlat[x] = cos(flat);
      phase2elevBase[x] = meta_get_slant(meta, 0, img_x)*sin(incid)/(2.0*k);
    }
  
  // Open intermediate output files
  felev = fopenImage(slant_elevation, "wb");
  feleverr = fopenImage(slant_elevation_error, "wb");
  
  /* loop through each row & calculate height*/
  /*Note:
    To make this faster, we don't call 
    delta_height=delta_phase * meta_phase_rate(ceos,base,y*yScale+sl,x*xScale+ss).
    Instead, we use the annoying temporary arrays
    allocated above to calculate the same thing, quicker.
  */
  for (y=0; y<nrows; y++) {
    double Bn_y,Bp_y;

    // Read in data
    FREAD(mask, sizeof(unsigned char), ncols, fmask);
    get_float_line(fphase, meta, y, uwp);
    get_float_line(fcoh, meta, y, coh);
    
    // Calculate baseline for this row
    meta_interp_baseline(meta, base, y*yScale+sl+1, &Bn_y, &Bp_y);
    
    // Step through each pixel in row
    for (x=0; x<ncols; x++) {
      // Calculate elevation
      if (uwp[x] != 0.0) {
	delta_phase = (double) uwp[x] - seed_phase;
	delta_height = delta_phase * phase2elevBase[x]/
	  (-Bp_y*sinFlat[x] - Bn_y*cosFlat[x]);
	elev[x] = delta_height + seed_height;
      }
      else 
	elev[x] = 0.0;
      // Calculate elevation error
      if (mask[x] == 0x10) {
	double coh_factor, base_height, sigma_height;
	coh_factor = (FLOAT_EQUALS_ZERO(coh[x])) ? 0.0 : sqrt((1-coh[x])/coh[x]);
	base_height = phase2elevBase[x]/(-Bp_y*sinFlat[x] - Bn_y*cosFlat[x]);
	sigma_height = base_height * coh_factor;
	eleverr[x] = (float) fabs(base_height*coh_factor);
      }
      else
	eleverr[x] = -1.0;
    }
    
    put_float_line(felev, meta, y, elev);
    put_float_line(feleverr, meta, y, eleverr);

    asfLineMeter(y, nrows);
  }
  
  // Free memory and close files
  FREE(uwp);
  FREE(mask);
  FREE(coh);
  FREE(elev);
  FREE(eleverr);
  FREE(sinFlat);
  FREE(cosFlat);
  FREE(phase2elevBase);
  FCLOSE(felev);
  FCLOSE(feleverr);
  FCLOSE(fphase);
  FCLOSE(fseed);
  FCLOSE(fmask);


  int fill_value=-1;
  // Transform all the slant range products into ground range
  printf("\nGenerating ground range elevation ...\n");
  deskew_dem(slant_elevation, NULL, ground_elevation, NULL, 0, NULL, NULL, TRUE,
             fill_value, 0);
  printf("\nGenerating ground range amplitude image ...\n");
  deskew_dem(slant_elevation, NULL, ground_amplitude, slant_amplitude, 1, NULL, NULL,
             TRUE, fill_value, 0);
  printf("\nGenerating ground range elevation error ...\n");
  deskew_dem(slant_elevation, NULL, ground_elevation_error, slant_elevation_error, 1,
             NULL, NULL, TRUE, fill_value, 0);
  printf("\nGenerating ground range coherence image ...\n\n");
  deskew_dem(slant_elevation, NULL, ground_coherence, slant_coherence, 0, NULL, NULL,
             TRUE, fill_value, 0);

  //meta_free(meta);
  return 0;
}