Example #1
0
void floats_to_bytes_from_file_ext(const char *inFile, const char *outFile,
  char *band, float mask, scale_t scaling, float scale_factor)
{
  FILE *fp;
  meta_parameters *meta;
  float *float_data;
  unsigned char *byte_data;
  int ii, band_number;
  long long pixel_count;
  long offset;

  meta = meta_read(inFile);
  band_number = (!band || strlen(band) == 0 || strcmp(band, "???")==0) ? 0 :
    get_band_number(meta->general->bands, meta->general->band_count, band);
  pixel_count = meta->general->line_count * meta->general->sample_count;
  offset = meta->general->line_count * band_number;
  float_data = (float *) MALLOC(sizeof(float) * pixel_count);
  fp = FOPEN(inFile, "rb");
  get_float_lines(fp, meta, offset, meta->general->line_count, float_data);
  FCLOSE(fp);
  byte_data = floats_to_bytes_ext(float_data, pixel_count, mask, scaling,
    scale_factor);
  for (ii=0; ii<pixel_count; ii++)
    float_data[ii] = (float) byte_data[ii];
  meta->general->data_type = ASF_BYTE;
  meta_write(meta, outFile);
  fp = FOPEN(outFile, "wb");
  put_float_lines(fp, meta, offset, meta->general->line_count, float_data);
  FCLOSE(fp);
  FREE(float_data);
  FREE(byte_data);
  meta_free(meta);
}
Example #2
0
void loadWrappedPhase(char *f)
{
  FILE * fd;
  meta_parameters *meta;

  fd = FOPEN(f, "rb");
  meta = meta_read(f);
  get_float_lines(fd, meta, 0, len, phase);
  FCLOSE(fd);

  return;
}
Example #3
0
void 
loadWrappedPhase(char *f)
{
  FILE * fd;
  meta_parameters *meta;

  printf ("   loading wrapped phase...\n");

  fd = FOPEN(f, "rb");
  meta = meta_read(f);
  get_float_lines(fd, meta, 0, len, phase);
  FCLOSE(fd);

  printf("   wrapped phase data loaded...\n");
  return;
}
Example #4
0
static void get_asf_lines(ReadAsfClientInfo *info, meta_parameters *meta,
                          int row, int n, float *buf)
{
    // wrapper for get_float_line() that multilooks if needed
    if (info->ml) {
        assert(meta->sar);
        int i,j,k;
        int nlooks = meta->sar->azimuth_look_count;
        int ns = meta->general->sample_count;
        row *= nlooks;

        // we fudged the line count in the metadata for the
        // viewer (which is displaying a multilooked image), we must
        // put the correct value back for the reader
        int lc = meta->general->line_count;
        meta->general->line_count = g_saved_line_count;

        float *tmp = MALLOC(sizeof(float)*ns);
        for (i=0; i<n; ++i) {
            float *this_row = buf + i*ns;
            get_float_line(info->fp, meta, row+i*nlooks, this_row);
            int n_read = nlooks;
            for (k=1; k<nlooks; ++k) {
                if (row+n*nlooks+k >= meta->general->line_count) {
                    --n_read;
                } else {
                    get_float_line(info->fp, meta, row+i*nlooks+k, tmp);
                    for (j=0; j<meta->general->sample_count; ++j)
                        this_row[j] += tmp[j];
                }
            }
            for (j=0; j<meta->general->sample_count; ++j)
                this_row[j] /= n_read;
        }
        free(tmp);

        meta->general->line_count = lc;
    }
    else {
        // no multilooking case
        get_float_lines(info->fp, meta, row, n, buf);
    }
}
Example #5
0
/* Function 'readSubset' returning a subset of image. The data type of the
   output image is float, regardless what the input data type is. It errors
   on complex data. The function expects to have the memory for the returning 
   image array already allocated. 
*/
void readSubset(char *fileName, int width, int height, int posX, int posY, 
		float *subset)
{
  FILE *fp;
  char dataFileName[255];
  int ii, kk;
  float *buffer;
  meta_parameters *meta = meta_read(fileName);
  int lines = meta->general->line_count;
  int samples = meta->general->sample_count;

  /* Check whether input parameters are feasible */
  assert (width > 0);
  assert (height > 0);
  assert (width < lines);
  assert (height < samples);
  assert (posX > 0);
  assert (posY > 0);
  assert ((posX+width) < samples);
  assert ((posY+height) < lines);
  if (meta->general->data_type > 5)
    printErr("   ERROR: 'readSubset' does not work on complex data!\n");

  /* Allocate memory for buffers */
  buffer = (float *) MALLOC(height*samples*sizeof(float));

  /* Open image file */
  create_name(dataFileName, fileName, ".img");
  fp = FOPEN(dataFileName, "rb");

  /* Read the appropriate data chunk */
  get_float_lines(fp, meta, posY, height, buffer);

  /* Fill in the subset buffer */
  for (ii=0; ii<height; ii++) 
    for (kk=0; kk<width; kk++) 
      subset[ii*width+kk] = buffer[ii*samples+posX+kk];

  /* Clean up */
  FCLOSE(fp);
  FREE(buffer);
  meta_free(meta);
}
Example #6
0
int main(int argc,char *argv[])
{
  char  infile1[256], infile2[256], infile3[256];  // Input file name                         
  char  outfile[256];         			   // Output file name
  char tmpPath[1024];
  browse_type_t mode = NOTYPE;
  int   i,j;
  int   sample_count;
  double scale;
  extern int currArg;
  strcpy(tmpPath, "");

  // Parse command line
  if ((argc-currArg)<1) {
    printf("Insufficient arguments.\n"); 
    usage("");
  }

  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatches(key, "-sentinel", "--sentinel", NULL)) {
      CHECK_ARG(1);
      scale = atof(GET_ARG(1));
      mode = SENTINEL_DUAL;
    }
    else if (strmatches(key, "-tmpDir", "--tmpDir", NULL)) {
      CHECK_ARG(1);
      strcpy(tmpPath, GET_ARG(1));
    }
    else if (strmatches(key, "-log", "--log", NULL)) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = TRUE;
    }
    else if (strmatches(key, "-quiet", "--quiet", "-q", NULL))
      quietflag = TRUE;
    else {
      --currArg;
      break;
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  if (mode == NOTYPE && argc == 4)
    mode = PALSAR_FBD;
  else if (mode == NOTYPE && argc == 5) 
    mode = PALSAR_PLR;

  if (!quietflag) 
    asfSplashScreen(argc, argv);

  if (mode == PALSAR_FBD) {
  
    asfPrintStatus("Creating colorized browse image from PALSAR FBD data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(outfile,argv[3],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }    
    strcpy(meta1->general->bands,"HH");
    strcpy(meta2->general->bands,"HV");

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *ofp = FOPEN(outfile, "w");
    char ofile1[256];
    char ofile2[256];

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_DB.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_DB.img");
 
    printf("Creating output DB files %s and %s\n",ofile1,ofile2);
    FILE *ofp1 = FOPEN(ofile1, "w");
    FILE *ofp2 = FOPEN(ofile2, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
        }
  	sample_count++;
      }
    }
    put_float_lines(ofp1, meta1, 0,meta1->general->line_count,buf1);
    put_float_lines(ofp2, meta2, 0,meta1->general->line_count,buf2);

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(fp1);
    fclose(fp2);
    fclose(ofp1);
    fclose(ofp2);

    /* Scale the data to a byte range using given min/max values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-30.0,-1.0); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-30.0,-10.0); 
   
    /* 
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1);
    */

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_byte.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_byte.img");
 
    printf("Creating output byte files %s and %s\n",ofile1,ofile2);
    ofp1 = FOPEN(ofile1, "w");
    ofp2 = FOPEN(ofile2, "w");

    meta1->general->data_type=REAL32;
    meta2->general->data_type=REAL32;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
  	  sample_count++;
      }
    }

    put_float_lines(ofp1,meta1,0,meta1->general->line_count,buf1); 
    put_float_lines(ofp2,meta2,0,meta2->general->line_count,buf2); 

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(ofp1);
    fclose(ofp2);

    /* Create the third band for the color image */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
 	 if (buf2[sample_count] != 0) {
           /*
           buf3[sample_count] = (buf1[sample_count] / buf2[sample_count]); 
           */

           buf3[sample_count] = (buf1[sample_count] - buf2[sample_count]);
           if (buf3[sample_count] < 1) buf3[sample_count] = 1;
           else if (buf3[sample_count] > 255) buf3[sample_count] = 255;
         } else buf3[sample_count] = 0;
         sample_count++;
       }
    }

    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA ,-25.0,-10.0); 
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf3[sample_count] = (float) cbuf3[sample_count];
  	  sample_count++;
      }
    }

    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,DIV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);

  } 
  else if (mode == PALSAR_PLR) {
  
    /* Mode 1 - Create Color Browse from 3 bands using 3sigma stretch */
    asfPrintStatus("Creating colorized browse image from PALSAR PLR data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(infile3,argv[3],".img");
    create_name(outfile,argv[4],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);
    meta_parameters *meta3 = meta_read(infile3);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    if (meta3->general->line_count != meta2->general->line_count ||
        meta3->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    float *buf4 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3, *cbuf4;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *fp3 = FOPEN(infile3, "r");
    FILE *ofp = FOPEN(outfile, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);
    get_float_lines(fp3,meta3,0,meta3->general->line_count, buf3);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
          if (buf3[sample_count] != 0)
            buf3[sample_count] = 10.0 * log10f(buf3[sample_count]);
        }
  	sample_count++;
      }
    }
    /* Scale the data to a byte range using 3-sigma stretch values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,SIGMA3,-30.0,-1.0);
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);
    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);

    meta1->general->data_type=REAL32;
    //meta2->general->data_type=ASF_BYTE;
    //meta3->general->data_type=ASF_BYTE;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
          buf3[sample_count] = (float) cbuf3[sample_count];
          sample_count++;
      }
    }
 
    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,VV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);
  }
  else if (mode == SENTINEL_DUAL) {
  
    asfPrintStatus("Creating colorized browse image from Sentinel dual-pol "
      "data\n");
    if (strlen(tmpPath) > 0) {
      create_name(infile1,argv[5],".img");
      create_name(infile2,argv[6],".img");
      create_name(outfile,argv[7],".tif");
    }
    else {
      create_name(infile1,argv[3],".img");
      create_name(infile2,argv[4],".img");
      create_name(outfile,argv[5],".tif");
    }

    // Create temporary directory
    char tmpDir[1024];
    if (strlen(tmpPath) > 0)
      sprintf(tmpDir, "%s%cbrowse-", tmpPath, DIR_SEPARATOR);
    else
      strcpy(tmpDir, "browse-");
    strcat(tmpDir, time_stamp_dir());
    create_clean_dir(tmpDir);
    asfPrintStatus("Temp dir is: %s\n", tmpDir);
  
    // Calculate ratio image
    char tmpRatio[512], tmpRed[512], tmpGreen[512], tmpBlue[512], tmpIn[512];
    char *inFiles[2]; 
    inFiles[0] = (char *) MALLOC(sizeof(char)*255);
    inFiles[1] = (char *) MALLOC(sizeof(char)*255);
    strcpy(inFiles[0], infile1);
    strcpy(inFiles[1], infile2);
    sprintf(tmpRatio, "%s%cdiv.img", tmpDir, DIR_SEPARATOR);
    raster_calc(tmpRatio, "a/b", 2, inFiles);
    
    // Resample all three bands and scale to byte
    meta_parameters *metaIn = meta_read(tmpRatio);
    double scaleFactor = 1.0/(scale/metaIn->general->x_pixel_size);
    meta_free(metaIn);
    sprintf(tmpIn, "%s%cred.img", tmpDir, DIR_SEPARATOR);
    resample(infile1, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpRed, "%s%cred_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpRed, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cgreen.img", tmpDir, DIR_SEPARATOR);
    resample(infile2, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpGreen, "%s%cgreen_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpGreen, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cblue.img", tmpDir, DIR_SEPARATOR);
    resample(tmpRatio, tmpIn, scaleFactor, scaleFactor);    
    sprintf(tmpBlue, "%s%cblue_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpBlue, NULL, -40.0, SIGMA);

    // Layer stack the bands
    char tmpBrowse[512];
    sprintf(tmpBrowse, "%s%cbrowse.img", tmpDir, DIR_SEPARATOR);
    FILE *fpOut = FOPEN(tmpBrowse, "w");    
    meta_parameters *metaOut = meta_read(tmpRed);
    metaOut->general->band_count = 3;
    metaIn = meta_read(tmpRed);
    int line_count = metaIn->general->line_count;
    int sample_count = metaIn->general->sample_count;
    
    float *buf = (float *) MALLOC(sizeof(float)*line_count*sample_count);
    FILE *fpIn = FOPEN(tmpBlue, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 0, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpGreen, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 1, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpRed, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 2, 0, line_count, buf);
    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(buf);

    strcpy(metaOut->general->bands, "red,green,blue");
    meta_write(metaOut, tmpBrowse);
    
    // Export to GeoTIFF
    char *band_names[3] = { "blue", "green", "red" };
    asf_export_bands(GEOTIFF, NONE, TRUE, FALSE, FALSE, FALSE, FALSE, 
      tmpBrowse, outfile, band_names, NULL, NULL);

    // Clean up
    asfPrintStatus("Removing temporary directory: %s\n", tmpDir);
    remove_dir(tmpDir);
    meta_free(metaIn);
    meta_free(metaOut);
  }
  else
    asfPrintError("Mode is not defined!\n");

  asfPrintStatus("Done.\n");
  exit(EXIT_SUCCESS);
}
Example #7
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);
  
}
Example #8
0
static void get_uavsar_lines(ReadUavsarClientInfo *info, meta_parameters *meta,
                             int row, int n, float *buf)
{
    // wrapper for get_float_line() that multilooks if needed
    int j,ns=meta->general->sample_count;
    if (info->ml) {
        assert(meta->sar);
        int i,k;
        int nlooks = meta->sar->azimuth_look_count;
        row *= nlooks;

        // we fudged the line count in the metadata for the
        // viewer (which is displaying a multilooked image), we must
        // put the correct value back for the reader
        int lc = meta->general->line_count;
        meta->general->line_count = g_saved_line_count;

        float *tmp = MALLOC(sizeof(float)*ns);
        for (i=0; i<n; ++i) {
            float *this_row = buf + i*ns;
            get_float_line(info->fp, meta, row+i*nlooks, this_row);
            for (j=0; j<ns; ++j)
                ieee_big32(this_row[j]);
            int n_read = nlooks;
            for (k=1; k<nlooks; ++k) {
                if (row+n*nlooks+k >= meta->general->line_count) {
                    --n_read;
                } else {
                    get_float_line(info->fp, meta, row+i*nlooks+k, tmp);
                    for (j=0; j<ns; ++j)
                        ieee_big32(tmp[j]);
                    for (j=0; j<ns; ++j)
                        this_row[j] += tmp[j];
                }
            }
            for (j=0; j<meta->general->sample_count; ++j)
                this_row[j] /= n_read;
        }
        free(tmp);

        // restore the fudged value
        meta->general->line_count = lc;
    }
    else {
        // no multilooking case
        if (info->is_complex) {
            complexFloat *cf_buf = MALLOC(sizeof(complexFloat)*ns*n);
            get_complexFloat_lines(info->fp, meta, row, n, cf_buf);
            for (j=0; j<n*ns; ++j) {
                ieee_big32(cf_buf[j].real);
                ieee_big32(cf_buf[j].imag);
                buf[j] = hypot(cf_buf[j].real, cf_buf[j].imag);
                //buf[j] = atan2_check(cf_buf[j].imag, cf_buf[j].real);
            }
            FREE(cf_buf);
        }
        else {
            get_float_lines(info->fp, meta, row, n, buf);
            for (j=0; j<n*ns; ++j)
                ieee_big32(buf[j]);
        }
    }
}
Example #9
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;
}
Example #10
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;
}
Example #11
0
int geoid_adjust(const char *input_filename, const char *output_filename)
{
  char *input_img = appendExt(input_filename, ".img");
  char *input_meta = appendExt(input_filename, ".meta");

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

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

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

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

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

  double avg = 0.0;
  int num=0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  FCLOSE(fpIn);
  FCLOSE(fpOut);

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

  // success
  return 0;
}
Example #12
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;
}