Exemple #1
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;
}
Exemple #2
0
/*
  DebugWritePatch:
  Outputs the current patch trans array, and
  converts it to amplitude and phase.
*/
void debugWritePatch(const patch *p,char *basename)
{
  FILE *fp;
  char name[1024],outname[1024];
  meta_parameters *meta;
  int i;

  strcpy(outname,g.out);
  strcat(strcat(outname,"_"),basename);
  strcat(strcpy(name,outname),".img");


  meta = meta_read(g.in1);
  meta->general->line_count = p->n_range;
  meta->general->sample_count = p->n_az;
  meta->general->data_type = COMPLEX_REAL32;
  meta->general->image_data_type = COMPLEX_IMAGE;
  meta_write(meta, name);

  fp = fopenImage(name,"wb");

  for (i=0; i<p->n_range; ++i)
    put_complexFloat_line(fp, meta, i, p->trans+i*p->n_az);

  FCLOSE(fp);
  meta_free(meta);

  patchToRGBImage(outname, TRUE);
}
Exemple #3
0
void debugWritePatch_Line(int lineNo, complexFloat *line, char *basename,
                          int n_range, int n_az)
{
  FILE *fp;
  meta_parameters *meta;
  char outname[320],name[320];
  char *mode;

  strcpy(outname,g.out);
  strcat(strcat(outname,"_"),basename);
  strcat(strcpy(name,outname),".img");

  if (lineNo == 0) {
      meta = meta_read(g.in1);
      meta->general->line_count = n_range;
      meta->general->sample_count = n_az;
      meta->general->data_type = COMPLEX_REAL32;
      meta->general->image_data_type = COMPLEX_IMAGE;
      meta_write(meta, name);
  } else {
      meta = meta_read(name);
  }

  mode = lineNo == 0 ? "wb" : "ab";
  fp = fopenImage(name,mode);
  put_complexFloat_line(fp, meta, lineNo, line);
  FCLOSE(fp);

  if (lineNo == meta->general->line_count - 1)
    patchToRGBImage(outname, TRUE);

  meta_free(meta);
}
Exemple #4
0
static void add_pixels(FloatImage *out, char *file,
                       double start_x, double start_y,
                       double per_x, double per_y)
{
    meta_parameters *meta = meta_read(file);

    if (!meta) {
        asfPrintError("Couldn't read metadata for: %s!\n", file);
    }

    // figure out where in the giant image these pixels will go
    int start_line, start_sample;

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

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

    asfPrintStatus("  Location in combined is S:%d-%d, L:%d-%d\n",
        start_sample, start_sample + ns,
        start_line, start_line + nl);

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

    FILE *img = fopenImage(file, "rb");
    if (!img) {
        asfPrintError("Couldn't open image file: %s!\n", file);
    }

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

    int y;
    for (y=0; y<nl; ++y) {
        get_float_line(img, meta, y, line);

        int x;
        for (x=0; x<ns; ++x) {
            float v = line[x];

            // don't write out "no data" values
            if (v != meta->general->no_data)
                float_image_set_pixel(out, x + start_sample, y + start_line, v);
        }

        asfLineMeter(y, nl);
    }

    fclose(img);
    free(line);
    meta_free(meta);
}
Exemple #5
0
// if png_flag is true, outputs a PNG.  if false, outputs a jpeg
static void patchToRGBImage(char *outname, int png_flag)
{
  update_status("Generating %s", outname);
  if (!quietflag)
    printf("   Outputting Debugging image '%s'...\n",outname);

  // input name is just the output name with ".img"
  char *polar_name = MALLOC((strlen(outname)+20)*sizeof(char));
  sprintf(polar_name, "%s_polar.img", outname);

  // will multilook, as well as conver to polar, generates a 2-band
  // file (amplitude is band 1, phase is band 2)
  c2p(outname,polar_name,FALSE,TRUE);

  // prepare for RGB conversion
  int i,j;
  meta_parameters *meta = meta_read(polar_name);
  int nl = meta->general->line_count;
  int ns = meta->general->sample_count;
  float *amp = MALLOC(sizeof(float)*ns);
  float *phase = MALLOC(sizeof(float)*ns);
  unsigned char *red = MALLOC(sizeof(unsigned char)*ns);
  unsigned char *grn = MALLOC(sizeof(unsigned char)*ns);
  unsigned char *blu = MALLOC(sizeof(unsigned char)*ns);
  FILE *fp = fopenImage(polar_name, "rb");
  const double TWOPI=2.*PI;
  const double PIOVER3=PI/3.;
  int n=0;

  // first/second passes are stats gathering
  asfPrintStatus("Gathering stats...\n");
  double avg=0, stddev=0;
  for (i=0; i<nl; i+=3) {
    get_float_line(fp,meta,i,amp);
    for (j=0; j<ns; j+=3) {
      avg += amp[j];
      ++n;
    }
    asfPercentMeter((float)i/((float)nl*2.));
  }
  avg /= (double)n;
  for (i=0; i<nl; i+=3) {
    get_float_line(fp,meta,i,amp);
    for (j=0; j<ns; j+=3) {
      stddev += (amp[j]-avg)*(amp[j]-avg);
    }
    asfPercentMeter((float)(i+nl)/((float)nl*2.));
  }
  asfPercentMeter(1);
  stddev = sqrt(stddev/(double)n);
  double min = avg - 2*stddev;
  double max = avg + 2*stddev;

  // open up PNG/JPEG output file
  FILE *ofp=NULL;
  struct jpeg_compress_struct cinfo;
  png_structp png_ptr;
  png_infop png_info_ptr;
  char *jpgname = NULL;
  char *pngname = NULL;
  if (png_flag) {
    asfPrintStatus("Generating debug image (PNG)...\n");
    pngname = appendExt(outname, ".png");
    initialize_png_file(pngname,meta,&ofp,&png_ptr,&png_info_ptr,TRUE);
  }
  else {
    asfPrintStatus("Generating debug image (JPEG)...\n");
    jpgname = appendExt(outname, ".jpg");
    initialize_jpeg_file(jpgname,meta,&ofp,&cinfo,TRUE);
  }

  // now read in the polar image, calculate RGB values, write to jpeg/png
  for (i=0; i<nl; ++i) {
    get_band_float_line(fp,meta,0,i,amp);
    get_band_float_line(fp,meta,1,i,phase);

    for (j=0; j<ns; ++j) {
      // scale to 2-sigma, to get brightness of the pixel
      unsigned char intensity;
          //=(unsigned char)(amp[j] * 128./(float)avg * 41./255.);
      if (amp[j]<=min)
        intensity=0;
      else if (amp[j]>=max)
        intensity=255;
      else
        intensity=(unsigned char)((amp[j]-min)/(max-min)*255.);

      // color of the pixel is determined by the phase
      unsigned char r=0,g=0,b=0;
      if (phase[j]<-PI) phase[j]+=TWOPI;     // ensure [-PI, PI)
      if (phase[j]>=PI) phase[j]-=TWOPI;
      int range = (int)((phase[j]+PI)/PIOVER3); // will be 0-6 (and rarely 6)
      switch (range) {
        case 0: r=1;           break;
        case 1: r=1; g=1;      break;
        case 2:      g=1;      break;
        case 3:      g=1; b=1; break;
        case 4:           b=1; break;
        case 5: r=1;      b=1; break;
        case 6:                break; // left black
        default:
          printf("phase: %f, range: %d\n", phase[j], range);
          assert(FALSE); break;
      }

      red[j] = r*intensity;
      grn[j] = g*intensity;
      blu[j] = b*intensity;
    }

    // write the line
    if (png_flag)
      write_rgb_png_byte2byte(ofp,red,grn,blu,png_ptr,png_info_ptr,ns);
    else
      write_rgb_jpeg_byte2byte(ofp,red,grn,blu,&cinfo,ns);

    // keep the user interested!
    asfPercentMeter((float)i/((float)nl));
  }
  asfPercentMeter(1.0);

  // clean up
  FCLOSE(fp);
  FREE(amp);
  FREE(phase);
  FREE(red);
  FREE(grn);
  FREE(blu);
  meta_free(meta);
  if (png_flag)
    finalize_png_file(ofp,png_ptr,png_info_ptr);
  else
    finalize_jpeg_file(ofp,&cinfo);
  FREE(jpgname);
  FREE(pngname);
  clean(polar_name);
  FREE(polar_name);
}
Exemple #6
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);
}
Exemple #7
0
void deskew(const char *infile, const char *outfile)
{
    meta_parameters *meta = meta_read(infile);

    int nl = meta->general->line_count;
    int np = meta->general->sample_count;
    int nb = meta->general->band_count;
    char **band_name = extract_band_names(meta->general->bands, nb);
    int band, line, samp, deskewed = meta->sar->deskewed != 0;

    if (!meta->sar)
        asfPrintError("Cannot deskew data without a sar block!\n");

    char *tmp_outfile;
    int do_rename = FALSE;
    if (strcmp(infile, outfile) == 0 && nb>1) {
        // user wants to deskew in-place
        // we can't actually do that on multi-band data, too much to keep in memory
        // use a temporary file, then clobber input file
        tmp_outfile = appendToBasename(outfile, "_tmp");
        do_rename = TRUE;
    } else {
        // normal case: either
        // 1) single-band in-place deskew
        // 2) not in-place deskew (single or multi)
        tmp_outfile = STRDUP(outfile);
    }

    // calculate the amount of shift necessary
    double fac = calc_shift(meta, 0, 0);
    // Not sure if we need this or not...
    //fac *= meta->general->x_pixel_size / meta->general->y_pixel_size;

    // the "lower" array stores the required shifts, indexed by column
    // (the amount of shift is row-independent)
    int *lower = MALLOC(np * sizeof(int));
    for (samp=0; samp<np; ++samp)
        lower[samp] = (int) floor(fac*(double)samp);

    if (meta->sar->deskewed) {
        asfPrintStatus("Data is already deskewed.\n");
    } else {
        asfPrintStatus("Far-range shift amount: ");
        if (lower[np-1] > 0)
            asfPrintStatus("%d pixels down.\n", lower[np-1]);
        else
            asfPrintStatus("%d pixels up.\n", -lower[np-1]);
    }

    float *ibuf = MALLOC(np * sizeof(float));
    float *obuf = CALLOC(np*nl, sizeof(float));

    FILE *fpi = fopenImage(infile, "rb");

    for (band=0; band<nb; ++band) {
        if (nb>1)
            asfPrintStatus("Deskewing band: %s\n", band_name[band]);

        // apply deskewing to this band
        for (line=0; line<nl; ++line) {
            get_float_line(fpi, meta, line + nl*band, ibuf);

            for (samp=0; samp<np; ++samp) {
                int out_line = deskewed ? line : line + lower[samp];
                if (out_line >= 0 && out_line < nl)
                    obuf[out_line*np+samp] = ibuf[samp];
            }

            asfLineMeter(line,nl);
        }

        // write out this band
        FILE *fpo = fopenImage(tmp_outfile, band>0 ? "ab" : "wb");
        put_float_lines(fpo, meta, band*nl, nl, obuf);
        FCLOSE(fpo);
    }

    FCLOSE(fpi);
    FREE(obuf);
    FREE(ibuf);
    FREE(lower);

    // if we output to a temporary file, clobber the input
    if (do_rename) {
        char *tmp_outfile_img = appendExt(tmp_outfile, ".img");
        char *outfile_img = appendExt(outfile, ".img");
        //printf("Renaming: %s -> %s\n", tmp_outfile_img, outfile_img);
        rename(tmp_outfile_img, outfile_img);
        FREE(tmp_outfile_img);
        FREE(outfile_img);
    }
    FREE(tmp_outfile);

    // only need to update the deskewed flag in the metadata
    meta->sar->deskewed = 1;
    meta_write(meta, outfile);
    meta_free(meta);
}
Exemple #8
0
void prep_specan_file(int nLooks,int quality,double aspect,
    struct ARDOP_PARAMS *g,meta_parameters *meta)
{
    getRec *inFile;
    FILE *outFile;
    int outLines,outSamples/*,x*/;
    /*char command[1024];*/
    int i;

    specan_struct rng={1.0/RFS,
        RSLOPE,
        RCEN,
        RBW,
        RLEN_INIT};

    specan_struct az={1.0/AFS,
        ASLOPE,
        ACEN,
        ABW,
        ALEN_INIT};

/*Set quality: longer FFT's -> bigger
image, better quality.*/
    for (i=0;i<quality;i++)
    {
        rng.fftLen*=2;
        az.fftLen*=2;
    }
    rng.fftLen=(int)(rng.fftLen*aspect);

/*Open files.*/
    if (!quietflag) printf("Opening input files...\n");
    inFile=fillOutGetRec(g->in1);
    outFile=fopenImage(g->out,"wb");

/*Init. Range Variables*/
    if (!quietflag) printf("Init SPECAN\n");
    rng.iSamp=1.0/g->fs;/*Sample size, range (s)= 1.0/sample freqency (Hz)*/
    rng.chirpSlope=g->slope;/*Range chirp slope (Hz/Sec)*/
    specan_init(&rng);

/*Init. Azimuth Variables*/
    if (!quietflag) printf("Estimate Doppler\n");
    az.iSamp=1.0/g->prf;/*Sample size, azimuth (s)=1.0/sample freqency (Hz)*/

    if (meta->stVec==NULL) {
        fprintf(stderr, "Can only quicklook scenes with state vectors!\n");
        exit(1);}
    else {  /*Find doppler rate (Hz/sec) <=> azimuth chirp slope*/
        double dopRate,yaw=0.0;
        GEOLOCATE_REC *g=init_geolocate_meta(&meta->stVec->vecs[0].vec,meta);
        double look;
                int ret;
                ret=getLook(g,meta->geo->slantFirst,yaw,&look);
                assert(ret==0);
        getDoppler(g,look,yaw,NULL,&dopRate,NULL,NULL);
        az.chirpSlope=dopRate;
        free_geolocate(g);
    }

    az.chirpCenter=g->fd*(1.0/az.iSamp);/*Convert doppler central freqency to Hz*/
    /*For de-scalloping, compute the most powerful doppler freqency.*/
    az.powerCenter=(1.0/az.iSamp)*
        fftEstDop(inFile,inFile->nLines/2,1,az.fftLen);

    if (!quietflag) printf("Doppler centroid at %.0f Hz, %.0f Hz/sec\n",az.chirpCenter,az.chirpSlope);
    specan_init(&az);

    if (!quietflag) printf("Efficiency: Range(%d): %.0f%%   Azimuth(%d): %.0f%%\n",
                           rng.fftLen,100.0*rng.oNum/rng.fftLen,
                           az.fftLen,100.0*az.oNum/az.fftLen);

/*Process image.*/
    specan_file(inFile,nLooks,outFile,&rng,&az,&outLines,&outSamples);
    FCLOSE(outFile);
    freeGetRec(inFile);

/*Create DDR for output file.*/
    {
        struct DDR ddr;/*Output DDR*/
        c_intddr(&ddr);
        ddr.dtype=DTYPE_FLOAT;
        ddr.nbands=1;
        ddr.nl=outLines;
        ddr.ns=outSamples;
        ddr.sample_inc=rng.oSamp/rng.iSamp;
        ddr.line_inc=az.oSamp/az.iSamp;
        c_putddr(g->out,&ddr);
    }
/*Copy over metadata*/
    if (meta->info)
        sprintf(meta->info->processor,"ASF/QUICKLOOK/%.2f",VERSION);
    meta_write(meta,g->out);
}
Exemple #9
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;
}
Exemple #10
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);
}
Exemple #11
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;
}
Exemple #12
0
int main (int argc, char *argv[])
{
  char cpxName[BUF],ampName[BUF],phsName[BUF]; /* File Names                  */
  FILE *fdCpx, *fdAmp, *pdPhs;            /* File Pointers                    */
  int line, sample;                       /* Line & sample indices for looping*/
  int percentComplete;                    /* Percent of data processed        */
  int ampBlockSize, phsBlockSize;         /* Number of samples gotten         */
  float *ampBuf, *aP, *phsBuf, *pP;       /* Output data buffers              */
  complexFloat *cpxBuf, *cP;              /* Input data buffers               */
  meta_parameters *inMeta, *outMeta;      /* In/Out meta structs              */
  int i, phaseImage=FALSE;

/* Make sure there are the correct number of args in the command line */
  if (argc < 3) { usage(argv[0]); }

/* Make sure input and output names are different */
  if (strcmp(argv[1],argv[2])==0) {
    printf("p2c: Input and output names cannot be the same. Exiting.\n");
    exit(EXIT_FAILURE);
  }
  
/* Get commandline args */
  create_name (ampName,argv[1],".amp"); 
  create_name (phsName,argv[1],".phase"); 
  create_name (cpxName,argv[2],".cpx");
  
  // Check whether phase image actually exists. If it does not exist, we will 
  // generate a phase image with a constant value on the fly.
  if (fileExists(phsName))
    phaseImage = TRUE;
  else
    printf("\nCould not find phase image! Generating constant phase image on "
	   "the fly ...\n");

/* Read the meta data. Write output meta with COMPLEX_* data type. */
  inMeta = meta_read(argv[1]);
  outMeta = meta_read(argv[1]);
  outMeta->general->data_type = meta_polar2complex(inMeta->general->data_type);
  meta_write(outMeta,argv[2]);

/* malloc buffers, check and open files */
  cpxBuf = (complexFloat *)MALLOC(sizeof(complexFloat)
                         * outMeta->general->sample_count * CHUNK_OF_LINES);
  ampBuf = (float *)MALLOC(sizeof(float)
                         * inMeta->general->sample_count * CHUNK_OF_LINES);
  phsBuf = (float *)MALLOC(sizeof(float)
                         * inMeta->general->sample_count * CHUNK_OF_LINES);
  fdCpx = fopenImage(cpxName, "wb");
  fdAmp = fopenImage(ampName, "rb");  
  pdPhs = fopenImage(phsName, "rb");  

/* Run thru the complex file, writing real data to amp and imag data to phase */
  printf("\n");
  percentComplete = 0;
  for (line=0; line<inMeta->general->line_count; line+=CHUNK_OF_LINES)
  {
    if ((line*100/inMeta->general->line_count == percentComplete)) {
      printf("\rConverting amp and phase to complex: %3d%% complete.",
             percentComplete++);
      fflush(NULL);
    }
    ampBlockSize = get_float_lines(fdAmp,inMeta,line,CHUNK_OF_LINES,ampBuf);
    if (phaseImage) {
      phsBlockSize = get_float_lines(pdPhs,inMeta,line,CHUNK_OF_LINES,phsBuf);
      if (ampBlockSize != phsBlockSize) {
	printf("\n");
	printf("p2c: Failed to get the same number of samples from amplitude and phase files.\n");
	printf("p2c: Exiting...\n\n");
	exit(EXIT_FAILURE);
      }
    }
    else {
      for (i=0; i<inMeta->general->sample_count*CHUNK_OF_LINES; i++)
	phsBlockSize = 0.0;
    }
    cP = cpxBuf;
    aP = ampBuf;
    pP = phsBuf;
    for (sample=0; sample<ampBlockSize; sample++) {
      cP->real = *aP * cos(*pP);
      cP->imag = *aP * sin(*pP);
      cP++;
      aP++;
      pP++;
    }
    put_complexFloat_lines(fdCpx,outMeta,line,CHUNK_OF_LINES,cpxBuf);
  }
  printf("\rConverted amp and phase to complex:  100%% complete.\n\n");

  /* close, free, halt */
  FCLOSE(fdCpx);
  FCLOSE(fdAmp);
  FCLOSE(pdPhs);
  FREE(cpxBuf);
  FREE(ampBuf);
  FREE(phsBuf);
  meta_free(inMeta);
  meta_free(outMeta);
  
  return 0;
}
Exemple #13
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;
}
Exemple #14
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);
}
Exemple #15
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);
}
Exemple #16
0
void calculate_plot(char *axis, char *gridFile, char *dataFile, char *maskFile, 
		    char *outFile, meta_parameters *meta, float xConstant)
{
  FILE *fpIn=NULL, *fpImg=NULL, *fpOut=NULL, *fpMask=NULL;
  quadratic_2d q;
  plot_t *plot;
  int maskFlag=FALSE, ii, kk, ll, size=BUFSIZE, points=0, x, y, index;
  char inLine[255], *mask=NULL; 
  float *bufImage=NULL;
  double xValue, slope, offset, *l, *s, *value;
  
  /* Prepare mask image for reading */
  if (maskFile != NULL) maskFlag = TRUE;
  if (maskFlag) {
    fpMask = fopenImage(maskFile, "rb");
    mask = (unsigned char *) MALLOC(lines * samples * sizeof(char));
    FREAD(mask, sizeof(char), lines*samples, fpMask);
    FCLOSE(fpMask);
  }
  
  if (gridFile) {
    /* Set things up for least square calculation */
    value=(double *)MALLOC(sizeof(double)*MAX_PTS);
    l=(double *)MALLOC(sizeof(double)*MAX_PTS);
    s=(double *)MALLOC(sizeof(double)*MAX_PTS);
    
    /* Read xValue grid points and estimate parameter for xValue calculation 
       using least squares approach */
    points = 0;
    fpIn = FOPEN(gridFile, "r");
    while (NULL!=(fgets(inLine, 255, fpIn))) {
      sscanf(inLine,"%lf%lf%lf", &value[points], &l[points], &s[points]); 
      points++;
    }
    FCLOSE(fpIn);
    
    q = find_quadratic(value, l, s, points);
    q.A = xConstant; 
  }  
  
  /* Determine minimum and maximum xValue for binning */
  min = 100000000;
  max = -100000000;
  for (ii=0; ii<lines; ii++) {
    for (kk=0; kk<samples; kk++) {
      x = ii;
      y = kk;
      if (gridFile) {
	xValue = q.A + q.B*x + q.C*y + q.D*x*x + q.E*x*y+ q.F*y*y;
	xValue += q.G*x*x*y + q.H*x*y*y + q.I*x*x*y*y;
	xValue += q.J*x*x*x + q.K*y*y*y;
      }
      else if (strcmp(axis, "Sample") == 0)
	xValue = y;
      else if (strcmp(axis, "Line") == 0)
	xValue = x;
      if (maskFlag) {
	if ((xValue > max) && mask[ii*samples+kk]) max = xValue;
	if ((xValue < min) && mask[ii*samples+kk]) min = xValue;
      }
      else {
	if (xValue > max) max = xValue;
	if (xValue < min) min = xValue;
      }
    }
  }

  /* Determine parameters for binning */
  if (interval > 0.0) 
    bins = ((max-min) / interval) + 0.5; /* interval supersedes number of bins */
  if (bins < 2 || bins > 1024) bins = 256;
  slope = (bins-1) / (max-min);
  offset = -slope * min;
  interval = (max-min) / bins;
  
  /* Initialize plot */
  plot = (plot_t *) MALLOC(bins * sizeof(plot_t));
  for (ii=0; ii<bins; ii++) {
    plot[ii].count = 0;
    plot[ii].min = 100000000;
    plot[ii].max = -100000000;
    plot[ii].mean = 0.0;
    plot[ii].stdDev = 0.0;
  }
  
  /* Prepare input image for reading */
  fpImg = fopenImage(dataFile, "rb");
  bufImage = (float *) MALLOC(samples * sizeof(float) * BUFSIZE);
  
  /* First data sweep: Calculate mean values and get the counts */
  printf("   First data sweep: Calculate mean values and get the counts ...\n");
  for (ii=0; ii<lines; ii+=size) {
    if ((lines-ii)<BUFSIZE) size = lines-ii;
    get_float_lines(fpImg, meta, ii, size, bufImage);
    for (ll=0; ll<size; ll++) 
      for (kk=0; kk<samples; kk++) {
	x = ii + ll;
	y = kk;
	if (gridFile) {
	  xValue = q.A + q.B*x + q.C*y + q.D*x*x + q.E*x*y+ q.F*y*y;
	  xValue += q.G*x*x*y + q.H*x*y*y + q.I*x*x*y*y;
	  xValue += q.J*x*x*x + q.K*y*y*y;
	}
	else if (strcmp(axis, "Sample") == 0)
	  xValue = y;
	else if (strcmp(axis, "Line") == 0)
	  xValue = x;
	index = (int) (slope*xValue + offset);

	if (maskFlag) {
	  if (mask[x*samples+y]) {
	    if (bufImage[ll*samples+kk] < plot[index].min)
	      plot[index].min = bufImage[ll*samples+kk];
	    if (bufImage[ll*samples+kk] > plot[index].max)
	      plot[index].max = bufImage[ll*samples+kk];
	    plot[index].mean += bufImage[ll*samples+kk];
	    plot[index].count++;
	  }
	}
	else {
	  if (bufImage[ll*samples+kk] < plot[index].min)
	    plot[index].min = bufImage[ll*samples+kk];
	  if (bufImage[ll*samples+kk] > plot[index].max)
	    plot[index].max = bufImage[ll*samples+kk];
	  plot[index].mean += bufImage[ll*samples+kk];
	  plot[index].count++;
	}
      }
  }
  for (ii=0; ii<bins; ii++)
    plot[ii].mean /= plot[ii].count;
  
  FCLOSE(fpImg);
  
  /* Second data sweep: Calculate standard deviations */
  printf("   Second data sweep: Calculating standard deviations ...\n\n");
  fpImg = fopenImage(dataFile, "rb");
  for (ii=0; ii<lines; ii+=size) {
    if ((lines-ii)<BUFSIZE) size = lines-ii;
    get_float_lines(fpImg, meta, ii, size, bufImage);
    for (ll=0; ll<size; ll++) 
      for (kk=0; kk<samples; kk++) {
	x = ii + ll;
	y = kk;
	if (gridFile) {
	  xValue = q.A + q.B*x + q.C*y + q.D*x*x + q.E*x*y+ q.F*y*y;
	  xValue += q.G*x*x*y + q.H*x*y*y + q.I*x*x*y*y;
	  xValue += q.J*x*x*x + q.K*y*y*y;
	}
	else if (strcmp(axis, "Sample") == 0)
	  xValue = y;
	else if (strcmp(axis, "Line") == 0)
	  xValue = x;
	index = (int) (slope*xValue + offset);

	if (maskFlag) {
	  if (mask[x*samples+y]) 
	    plot[index].stdDev +=
	      SQR(plot[index].mean - bufImage[ll*samples+kk]);
	}
	else {
	  plot[index].stdDev +=
	    SQR(plot[index].mean - bufImage[ll*samples+kk]);
	}
      }
  }
  for (ii=0; ii<bins; ii++) 
    plot[ii].stdDev = sqrt(plot[ii].stdDev / (plot[ii].count-1));
  
  FCLOSE(fpImg);
  
  /* Prepare output file for writing */
  fpOut = FOPEN(outFile, "w");
  fprintf(fpOut, "%s", axis);

  if (meta->general->radiometry == r_SIGMA ||
      meta->general->radiometry == r_GAMMA ||
      meta->general->radiometry == r_BETA) {
    fprintf(fpOut, "\tMin value\tMax value\tMean value\tdB value\tCount"
	    "\tStandard deviation\n");
    for (ii=0; ii<bins; ii++)
      fprintf(fpOut, "%10.4lf\t%.8lf\t%10.4lf\t%10.4lf\t%10.4lf\t%10li\t%10.4lf\n", 
	      (min+ii*interval), plot[ii].min, plot[ii].max, plot[ii].mean, 
	      10*log10(plot[ii].mean), plot[ii].count, plot[ii].stdDev);
  }
  else {
    fprintf(fpOut, "\tMin value\tMax value\tMean value\tCount\tStandard deviation\n");
    for (ii=0; ii<bins; ii++)
      fprintf(fpOut, "%10.4lf\t%.8lf\t%10.4lf\t%10.4lf\t%10li\t%10.4lf\n", 
	      (min+ii*interval), plot[ii].min, plot[ii].max,
	      plot[ii].mean, plot[ii].count, plot[ii].stdDev);
  }

  FCLOSE(fpOut);
  
}
Exemple #17
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;
}
Exemple #18
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);
}
Exemple #19
0
/* Main program */
int main(int argc, char *argv[])
{
  FILE *fpLook=NULL, *fpIncid=NULL, *fpRange=NULL, *fpIn=NULL, *fpMask=NULL;
  meta_parameters *meta;
  stateVector stVec;
  int ii, kk, ll;
  char inFile[255], metaFile[255], dataFile[255], outLook[255], outIncid[255];
  char outRange[255], outBase[255], outFile[255], *maskFile=NULL; 
  char cmd[255], *bufMask=NULL;
  float *bufImage=NULL, *bufLook=NULL, *bufIncid=NULL, *bufRange=NULL;
  double latitude, longitude, time, doppler, earth_radius=0, satellite_height, range;
  double look_angle, incidence_angle, height;
  double line, sample, re=6378144.0, rp=6356754.9, px, py;
  double firstLook=0.0, firstIncid=0.0, firstRange=0.0;
  flag_indices_t flags[NUM_FLAGS];

  /* Set all flags to 'not set' */
  for (ii=0; ii<NUM_FLAGS; ii++) {
    flags[ii] = FLAG_NOT_SET;
  }
  
/**********************BEGIN COMMAND LINE PARSING STUFF**********************/
  /* Check to see if any options were provided */
  if (checkForOption("-help", argc, argv) != -1) /* Most important */
    help_page();
  flags[f_LOOK] = checkForOption("-look", argc, argv);
  flags[f_INCIDENCE] = checkForOption("-incidence", argc, argv);
  flags[f_RANGE] = checkForOption("-range", argc, argv);
  flags[f_LINE] = checkForOption("-line", argc, argv);
  flags[f_SAMPLE] = checkForOption("-sample", argc, argv);
  flags[f_MIN] = checkForOption("-min", argc, argv);
  flags[f_MAX] = checkForOption("-max", argc, argv);
  flags[f_BINS] = checkForOption("-bins", argc, argv);
  flags[f_INTERVAL] = checkForOption("-interval", argc, argv);

  /* Make sure to set log & quiet flags (for use in our libraries) */
  logflag = (flags[f_LOG]!=FLAG_NOT_SET) ? TRUE : FALSE;
  quietflag = (flags[f_QUIET]!=FLAG_NOT_SET) ? TRUE : FALSE;

  { /* We need to make sure the user specified the proper number of arguments */
    int needed_args = 4;/*command & in_base & out_base */
    if (flags[f_MIN] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_MAX] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_BINS] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_INTERVAL] != FLAG_NOT_SET) needed_args += 2; /* option & value */

    /*Make sure we have enough arguments*/
    if (argc != needed_args)
      usage();/*This exits with a failure*/
  }

  /* We must be close to good enough at this point...start filling in fields 
     as needed */
  if (flags[f_MIN] != FLAG_NOT_SET)
    min = atof(argv[flags[f_MIN] + 1]);
  if (flags[f_MAX] != FLAG_NOT_SET)
    max = atof(argv[flags[f_MAX] + 1]);
  if (flags[f_BINS] != FLAG_NOT_SET)
    bins = atoi(argv[flags[f_BINS] + 1]);
  if (flags[f_INTERVAL] != FLAG_NOT_SET)
    interval = atof(argv[flags[f_INTERVAL] + 1]);

  if (flags[f_QUIET] == FLAG_NOT_SET)
    /* display splash screen if not quiet */
    print_splash_screen(argc, argv);
  if (flags[f_LOG] != FLAG_NOT_SET)
    strcpy(logFile, argv[flags[f_LOG] + 1]);
  else
    /* default behavior: log to tmp<pid>.log */
    sprintf(logFile, "tmp%i.log", (int)getpid());
  fLog = FOPEN(logFile, "a");

  /* Fetch required arguments */
  strcpy(inFile,argv[argc - 2]);
  strcpy(outBase,argv[argc - 1]);
/***********************END COMMAND LINE PARSING STUFF***********************/

  create_name(metaFile, inFile, ".meta");
  create_name(dataFile, inFile, ".img");
  
  /* Read metadata */
  meta = meta_read(inFile);
  lines = meta->general->line_count;
  samples = meta->general->sample_count;

  /* Set some values */
  doppler = 0.0;

  /* Determine what kind of image it is */
  if (meta->sar->image_type=='P') {
    if (meta->projection->type==SCANSAR_PROJECTION)
      printf("   Detected ScanSAR ");
  }
  else if (meta->sar->image_type=='S')
    printf("   Detected slant range ");
  else if (meta->sar->image_type=='G')
    printf("   Detected ground range ");
/*
  switch (meta->general->image_data_type) 
    {
    case AMPLITUDE_IMAGE: 
      printf("amplitude image ...\n");
      break;
    case SIGMA_IMAGE:
      printf("sigma image ...\n");
      break;
    case GAMMA_IMAGE:
      printf("gamma image ...\n");
      break;
    case BETA_IMAGE:
      printf("beta image ...\n");
      break;
    case RAW_IMAGE:
    case COMPLEX_IMAGE:
    case PHASE_IMAGE:
    case POWER_IMAGE:
    case COHERENCE_IMAGE:
    case GEOREFERENCED_IMAGE:
    case GEOCODED_IMAGE:
    case POLARIMETRIC_IMAGE:
    case LUT_IMAGE:
    case ELEVATION:
    case DEM:
    case IMAGE:
    case MASK:
      break;
    }
*/
  /* Create a mask file for background fill - required only for ScanSAR */
  if (meta->sar->image_type=='P') {
    if (meta->projection->type==SCANSAR_PROJECTION) {
      fpIn = fopenImage(inFile, "rb");
      bufImage = (float *) MALLOC(samples * sizeof(float));
      printf("   Generating mask file ...\n");
      maskFile = (char *) MALLOC(255*sizeof(char));
      sprintf(maskFile, "tmp%i.mask", (int)getpid());
      fpMask = fopenImage(maskFile, "wb");
      bufMask = (unsigned char *) MALLOC(samples * sizeof(char));
      for (ii=0; ii<lines; ii++) {
	get_float_line(fpIn, meta, ii, bufImage);
	for (kk=0; kk<samples; kk++) {
	  if (bufImage[kk]>0.0)
	    bufMask[kk] = 1;
	  else
	    bufMask[kk] = 0;
	}      
	ASF_FWRITE(bufMask, sizeof(char), samples, fpMask);
      }
      FCLOSE(fpMask);
      FREE(bufMask);
      FCLOSE(fpIn);
      FREE(bufImage);
    }
  }

  /* Create grid for least square approach */
  printf("   Initialization ...\n");
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    sprintf(outLook, "tmp%i.look", (int)getpid());
    fpLook = FOPEN(outLook, "w");
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    sprintf(outIncid, "tmp%i.incid", (int)getpid());
    fpIncid = FOPEN(outIncid, "w");
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    sprintf(outRange, "tmp%i.range", (int)getpid());
    fpRange = FOPEN(outRange, "w");
  }

  if (flags[f_LOOK] != FLAG_NOT_SET || flags[f_INCIDENCE] != FLAG_NOT_SET ||
      flags[f_RANGE] != FLAG_NOT_SET) {
    for (ll=0; ll<=RES_X; ll++)
      for (kk=0; kk<=RES_Y; kk++) {
	line = ll * lines / RES_Y;
	sample = kk * samples / RES_X;
	
	if (meta->sar->image_type=='P') {
	  px = meta->projection->startX + meta->projection->perX * sample;
	  py = meta->projection->startY + meta->projection->perY * line;
	  proj_to_latlon(meta->projection, px, py, 0.0,
		     &latitude, &longitude, &height);
	  latLon2timeSlant(meta, latitude, longitude, &time, &range, &doppler);
	}
	else
	  time = meta_get_time(meta, line, sample);
	
	stVec = meta_get_stVec(meta, time);
	if (meta->sar->image_type=='P') {
	  if (meta->projection->type==SCANSAR_PROJECTION) 
	    earth_radius = meta->projection->param.atct.rlocal;
	  else
	    asfPrintError("Unable to determine earth radius.\n");
	}
	else
	  earth_radius = my_get_earth_radius(time, stVec, re, rp);
	satellite_height = my_get_satellite_height(time, stVec);
	range = my_get_slant_range(meta, earth_radius, satellite_height, line, sample);
	look_angle = my_get_look_angle(earth_radius, satellite_height, range);
	incidence_angle = my_get_incidence_angle(earth_radius, satellite_height, range);
	
	if (ll==0 && kk==0) {
	  firstLook = look_angle * R2D;
	  firstIncid = incidence_angle * R2D;
	  firstRange = range;
	}
	
	if (flags[f_LOOK] != FLAG_NOT_SET)
	  fprintf(fpLook, "%.18f %.12f %.12f\n", (float)look_angle*R2D, 
		  line, sample);
	if (flags[f_INCIDENCE] != FLAG_NOT_SET)
	  fprintf(fpIncid, "%.18f %.12f %.12f\n", (float)incidence_angle*R2D, 
		  line, sample);
	if (flags[f_RANGE] != FLAG_NOT_SET) 
	  fprintf(fpRange, "%.18f %.12f %.12f\n", (float)range, line, sample);
      }
  }
  
  /* Close files for now */
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    FCLOSE(fpLook);
    FREE(bufLook);
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    FCLOSE(fpIncid);
    FREE(bufIncid);
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    FCLOSE(fpRange);
    FREE(bufRange);
  }
  
  /* Calculate plots */
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_look.plot");
    calculate_plot("Look angle", outLook, dataFile, maskFile, outFile, 
		   meta, firstLook);
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_incid.plot");
    calculate_plot("Incidence angle", outIncid, dataFile, maskFile, outFile, 
		   meta, firstIncid);
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_range.plot");
    calculate_plot("Range", outRange, dataFile, maskFile, outFile, 
		   meta, firstRange);
  }
  if (flags[f_LINE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_line.plot");
    calculate_plot("Line", NULL, dataFile, maskFile, outFile, 
		   meta, 0.0);
  }
  if (flags[f_SAMPLE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_sample.plot");
    calculate_plot("Sample", NULL, dataFile, maskFile, outFile, 
		   meta, 0.0);
  }
  
  /* Clean up */
  sprintf(cmd, "rm -rf tmp*");
  system(cmd);
  
  exit(0);
}
Exemple #20
0
int sr2gr_pixsiz(const char *infile, const char *outfile, float grPixSize)
{
	int    in_np,  in_nl;               /* input number of pixels,lines  */
	int    out_np, out_nl;              /* output number of pixels,lines */
	int    ii,line,band;
	float  oldX,oldY;
	float  sr2gr[MAX_IMG_SIZE];
	float  ml2gr[MAX_IMG_SIZE];
	int    a_lower[MAX_IMG_SIZE];
	int    lower[MAX_IMG_SIZE], upper[MAX_IMG_SIZE];
	float  a_ufrac[MAX_IMG_SIZE], a_lfrac[MAX_IMG_SIZE];
	float  ufrac[MAX_IMG_SIZE], lfrac[MAX_IMG_SIZE];
	float *ibuf1,*ibuf2,*obuf;
	char   infile_name[512],inmeta_name[512];
	char   outfile_name[512],outmeta_name[512];
	FILE  *fpi, *fpo;
	meta_parameters *in_meta;
	meta_parameters *out_meta;

        create_name (infile_name, infile, ".img");
        create_name (outfile_name, outfile, ".img");

        create_name (inmeta_name, infile, ".meta");
        create_name (outmeta_name, outfile, ".meta");

	in_meta  = meta_read(inmeta_name);
	out_meta = meta_copy(in_meta);
	in_nl = in_meta->general->line_count;
	in_np = in_meta->general->sample_count;
	
	if (in_meta->sar->image_type != 'S')
	{
            asfPrintError("sr2gr only works with slant range images!\n");
	}

      	oldX = in_meta->general->x_pixel_size * in_meta->sar->sample_increment;
	oldY = in_meta->general->y_pixel_size * in_meta->sar->line_increment;

        /* If user didn't specify a pixel size, make the pixels square & leave
           the y pixel size unchanged */
        if (grPixSize < 0)
            grPixSize = oldY;

	/*Update metadata for new pixel size*/
	out_meta->sar->time_shift  += ((in_meta->general->start_line)
				* in_meta->sar->azimuth_time_per_pixel);
	out_meta->sar->slant_shift -= ((in_meta->general->start_sample)
				* in_meta->general->x_pixel_size);
	out_meta->general->start_line   = 0.0;
	out_meta->general->start_sample = 0.0;
	out_meta->sar->azimuth_time_per_pixel *= grPixSize
					/ in_meta->general->y_pixel_size;
	out_meta->sar->line_increment   = 1.0;
        out_meta->sar->sample_increment = 1.0;
        if (out_meta->transform)
          out_meta->transform->target_pixel_size = grPixSize;	
	/*Create ground/slant and azimuth conversion vectors*/
	out_meta->sar->image_type       = 'G'; 
	out_meta->general->x_pixel_size = grPixSize;
	out_meta->general->y_pixel_size = grPixSize;
	sr2gr_vec(out_meta,oldX,grPixSize,sr2gr);
	ml_vec(oldY,grPixSize,ml2gr);

	out_np = MAX_IMG_SIZE;
	out_nl = MAX_IMG_SIZE;
	for (ii=MAX_IMG_SIZE-1; ii>0; ii--)
		if ((int)sr2gr[ii] > in_np)
			out_np = ii;
	for (ii=MAX_IMG_SIZE-1; ii>0; ii--)
		if ((int)ml2gr[ii] > in_nl)
			out_nl = ii;
	
	out_meta->general->line_count   = out_nl;
        out_meta->general->line_scaling *= (double)in_nl/(double)out_nl;
        out_meta->general->sample_scaling = 1;
	out_meta->general->sample_count = out_np;
	if (out_meta->projection) {
		out_meta->projection->perX = grPixSize;
		out_meta->projection->perY = grPixSize;
	}

	meta_write(out_meta,outmeta_name);
	
	fpi = fopenImage(infile_name,"rb");
	fpo = fopenImage(outfile_name,"wb");
	
	for (ii=0; ii<MAX_IMG_SIZE; ii++)
	{
		lower[ii] = (int) sr2gr[ii];
		upper[ii] = lower[ii] + 1;
		ufrac[ii] = sr2gr[ii] - (float) lower[ii];
		lfrac[ii] = 1.0 - ufrac[ii]; 
		
		a_lower[ii] = (int) ml2gr[ii];
		a_ufrac[ii] = ml2gr[ii] - (float) a_lower[ii];
		a_lfrac[ii] = 1.0 - a_ufrac[ii]; 
	}

	ibuf1 = (float *) MALLOC ((in_np+FUDGE_FACTOR)*sizeof(float));
	ibuf2 = (float *) MALLOC ((in_np+FUDGE_FACTOR)*sizeof(float));
	obuf = (float *) MALLOC (out_np*sizeof(float));

	/* Initialize input arrays to 0 */
	for (ii=0;ii<in_np+FUDGE_FACTOR;ii++) {
		ibuf1[ii]=ibuf2[ii]=0.0;
	}

        /* Get the band info */
        int bc = in_meta->general->band_count;
        char **band_name = extract_band_names(in_meta->general->bands, bc);

	/* Work dat magic! */
        for (band=0; band<bc; ++band) {
          asfPrintStatus("Working on band: %s\n", band_name[band]);
          for (line=0; line<out_nl; line++)
          {
            if (a_lower[line]+1 < in_nl)
            {
              get_band_float_line(fpi,in_meta,band,a_lower[line],  ibuf1);
              get_band_float_line(fpi,in_meta,band,a_lower[line]+1,ibuf2);
            }
            
            for (ii=0; ii<out_np; ii++)
            {
              int val00,val01,val10,val11,tmp1,tmp2;
              val00 = ibuf1[lower[ii]];
              val01 = ibuf1[upper[ii]];
              val10 = ibuf2[lower[ii]];
              val11 = ibuf2[upper[ii]];
              
              tmp1 = val00*lfrac[ii] + val01*ufrac[ii];
              tmp2 = val10*lfrac[ii] + val11*ufrac[ii];
              
              obuf[ii] = tmp1*a_lfrac[line] + tmp2*a_ufrac[line];
            }
            put_band_float_line(fpo,out_meta,band,line,obuf);
            asfLineMeter(line, out_nl);
          }
        }
        for (band=0; band<bc; ++band)
          FREE(band_name[band]);
        FREE(band_name);
        meta_free(in_meta);
        meta_free(out_meta);
	FCLOSE(fpi);
	FCLOSE(fpo);
	
        return TRUE;
}
Exemple #21
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);
}
Exemple #22
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;
}
Exemple #23
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;
}