예제 #1
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);
}
예제 #2
0
END_TEST

/* Test routine which writes new-style meta files.  */
START_TEST(test_meta_read_write_new_format)
{
  /* Get something to write.  */
  char in_file[512];
  meta_parameters *meta;
  meta_parameters *meta_reread;	/* For re-read structure.  */

  sprintf(in_file,"%s/test_file_new_style.meta",_TEST_DATA_DIR);
  meta = meta_read(in_file);
  meta_write(meta, "test_output/test_output_file.meta");
  meta_reread = meta_read("test_output/test_output_file.meta");
  
  /* Test a few random or not-so-random fields for equality.  */
  fail_unless(!strcmp(meta->general->sensor, meta_reread->general->sensor),
	      "sensor elements from original and written-then-reread metadata structures don't match");
  fail_unless(meta->projection->type == meta_reread->projection->type,
	      "projection->type fields from original and written-then-reread metadata structures not equal");
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.atct.rlocal,
				       meta_reread->projection
				                    ->param.atct.rlocal),
	      "projection->param.atct.rlocal fields from original and written-then-reread metadata structures not equal");

  if ( unlink("test_output/test_output_file.meta") == -1 ) {
    perror("failed to delete intra-test temporary file test_output_file.meta");
    fail("");
  }
}
예제 #3
0
int main(int argc, char **argv)
{
	char las_name[256];
	char meta_name[256];
	meta_parameters *meta;
	
/* Parse command line */
	currArg=1;
	if (argc-currArg < 2)
		{printf("Insufficient arguments.\n"); usage(argv[0]);}
	if (argc-currArg > 2)
		{printf("Excessive arguments.\n"); usage(argv[0]);}
	strcpy(las_name, argv[currArg]);
	strcpy(meta_name,argv[currArg+1]);
	
/* Read .ddr & .meta file info & put into meta structures */ 
	meta = meta_read(las_name);
	meta->general->image_data_type = IMAGE;

/* write it out new style */
	meta_write(meta, meta_name);

/* Clean and report */
	meta_free(meta);
	printf("***Wrote %s.meta from %s.ddr and %s.meta.\n",
	       meta_name,las_name,las_name);

	return 0;
}
예제 #4
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);
}
예제 #5
0
END_TEST

START_TEST(test_ps) /* Polar Stereo */
{
  char error_string[256];
  char in_file[512];
  meta_parameters *meta;
  sprintf(in_file,"%s/new_style_ps.meta",_TEST_DATA_DIR);
  meta = meta_read(in_file);
  meta_write(meta,"test_output/out_ps.meta");
/* look at a couple fields real quick */
  sprintf(error_string,"meta->sar->dopRangeQuad is %-16.11g, should be 0.0001246",meta->sar->range_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->range_doppler_coefficients[2],0.0001246),error_string);
  sprintf(error_string,"meta->sar->dopAzQuad is %-16.11g, should be 2e-07",meta->sar->azimuth_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->azimuth_doppler_coefficients[2],2e-07),error_string);

/* look at the good stuff */
  sprintf(error_string,"meta->projection->param.ps.slat is %-16.11g, should be 72.374152778",meta->projection->param.ps.slat);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.ps.slat,72.374152778),error_string);
  sprintf(error_string,"meta->geo->proj->param.ps.slat is %-16.11g, should be 72.374152778",meta->geo->proj->param.ps.slat);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.ps.slat,72.374152778),error_string);

  sprintf(error_string,"meta->projection->param.ps.slon is %-16.11g, should be -158.3591",meta->projection->param.ps.slon);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.ps.slon,-158.3591),error_string);
  sprintf(error_string,"meta->geo->proj->param.ps.slon is %-16.11g, should be -158.3591",meta->geo->proj->param.ps.slon);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.ps.slon,-158.3591),error_string);
  meta_free(meta);
}
예제 #6
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);
}
예제 #7
0
int main(int argc, char **argv)
{
  char meta_name[255];
  char envi_name[255];
  meta_parameters *meta=NULL;
  envi_header *envi=NULL;
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;

  if (argc > 1) {
      check_for_help(argc, argv);
      handle_license_and_version_args(argc, argv, TOOL_NAME);
  }
  if (argc < 3) {
      asfPrintStatus("\nNot enough arguments.\n");
      usage();
      return 1;
  }

  /* Parse command line args */
  while (currArg < (argc-2))
    {
      char *key=argv[currArg++];
      if (strmatch(key,"-log")) {
        sprintf(logFile, "%s", argv[currArg]);
        logflag = 1;
      }
      else {
        printf("\n   ***Invalid option:  %s\n\n",
               argv[currArg-1]);
        usage(argv[0]);
      }
    }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }

  create_name(envi_name, argv[currArg], ".hdr");
  create_name(meta_name, argv[currArg+1], ".meta");

  asfSplashScreen(argc, argv);

  // Read ENVI header
  envi = read_envi(envi_name);

  // Fill metadata structure with valid data
  meta = envi2meta(envi);

  // Write metadata file
  meta_write(meta, meta_name);

  // Clean and report
  meta_free(meta);
  asfPrintStatus("   Converted ENVI header (%s) to metadata file (%s)\n\n",
         envi_name, meta_name);

  return 0;
}
예제 #8
0
int main(int argc, char *argv[])
{
  // Allocate some memory
  char *inFile = (char *) MALLOC(sizeof(char)*512);
  char *outFile = (char *) MALLOC(sizeof(char)*512);

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

  asfSplashScreen (argc, argv);

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

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

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

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

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

  power = (float *) MALLOC(sizeof(float)*meta->general->sample_count);
  byteBuf = (char *) MALLOC(sizeof(char)*10);
  airsar_header *header = read_airsar_header(inFile);
  long offset = header->first_data_offset;
  FSEEK(fpIn, offset, SEEK_SET);
  for (ii=0; ii<meta->general->line_count; ii++) {
    for (kk=0; kk<meta->general->sample_count; kk++) {
      FREAD(byteBuf, sizeof(char), 10, fpIn);
      power[kk] = sqrt(((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]));
    }
    put_float_line(fpOut, meta, ii, power);
    asfLineMeter(ii, meta->general->line_count);
  }
  FCLOSE(fpIn);
  FCLOSE(fpOut);
  meta_write(meta, outFile);
  if (power)
    FREE(power);
  if (byteBuf)
    FREE(byteBuf);
  if (meta)
    meta_free(meta);
}
예제 #10
0
int main (int argc, char *argv[]) {

	const char		*const_str = "ThisStringIsUsedToTestWriteOfMetadata";
	char			*str;
	uint8_t			size, type;
	struct  bitio	*bd;

	bd = bopen("metadata_test.dat", 'w');
	if (bd == NULL)
		goto error;

	meta_write(bd, 1, (void*)const_str, strlen(const_str) + 1);
	meta_write(bd, 2, (void*)const_str, 2);
	meta_finalize(bd);

	bclose(bd);

	bd = bopen("metadata_test.dat", 'r');
	if (bd == NULL)
		goto error;

	str = meta_read(bd, &type, &size);
	if (strcmp(str, const_str) != 0 || type != 1 || size != strlen(str) + 1)
		goto error;

	str = meta_read(bd, &type, &size);
	if (str[0] != const_str[0] || str[1] != const_str[1] || type != 2 || size != 2)
		goto error;

	bclose(bd);
	unlink("metadata_test.dat");
	exit(EXIT_SUCCESS);
error:
	bclose(bd);
	unlink("metadata_test.dat");
	exit(EXIT_FAILURE);
}
예제 #11
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;
}
예제 #12
0
int combine(char **infiles, int n_inputs, char *outfile)
{
  int ret, ii, size_x, size_y;
  double start_x, start_y;
  double per_x, per_y;

  // Determine image parameters
  determine_extents(infiles, n_inputs, &size_x, &size_y, &start_x, &start_y,
		    &per_x, &per_y);
  
  asfPrintStatus("\nCombined image size: %dx%d LxS\n", size_y, size_x);
  asfPrintStatus("  Start X,Y: %f,%f\n", start_x, start_y);
  asfPrintStatus("    Per X,Y: %lg,%lg\n", per_x, per_y);
  
  // float_image will handle cacheing of the large output image
  FloatImage *out = float_image_new(size_x, size_y);
  
  // loop over the input images, last to first, so that the files listed
  // first have their pixels overwrite files listed later on the command line
  for (ii=n_inputs-1; ii>=0; ii--) {
    asfPrintStatus("\nProcessing %s... \n", infiles[ii]);
      
    // Add this image's pixels
    add_pixels(out, infiles[ii], start_x, start_y, per_x, per_y);
  }
  
  asfPrintStatus("Writing metadata.\n");
  
  meta_parameters *meta_out = meta_read(infiles[0]);
  
  meta_out->projection->startX = start_x;
  meta_out->projection->startY = start_y;
  meta_out->general->line_count = size_y;
  meta_out->general->sample_count = size_x;
  
  meta_write(meta_out, outfile);
  meta_free(meta_out);

  char *outfile_full = appendExt(outfile, ".img");
  asfPrintStatus("Saving image (%s).\n", outfile_full);
  ret = float_image_store(out, outfile_full, fibo_be);
  if (ret!=0) 
    asfPrintError("Error storing output image!\n");
  float_image_free(out);
  free(outfile_full);
  
  return ret;
}
예제 #13
0
void import_gridfloat(char *inBaseName, char *outBaseName)
{
    int i, j;
    int column_count, row_count;
    char *flt_file = appendExt(inBaseName, ".flt");

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

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

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

    meta_write(meta, meta_filename);

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

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

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

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

    fclose(fp);
    fclose(out);

    free(data_filename);
    free(floats);

    free(flt_file);
}
예제 #14
0
int main (int argc, char **argv)
{
	char ceosName[256];
	char metaName[256];
	meta_parameters *meta;
	
	/* Parse command line */
	if (argc-currArg < 2)
		{printf("Insufficient arguments.\n"); usage(argv[0]);}
	if (argc-currArg > 2)
		{printf("Excessive arguments.\n"); usage(argv[0]);}
	strcpy(ceosName,argv[currArg]);
	strcpy(metaName,argv[currArg+1]);
	
	meta = meta_create(ceosName);
	meta_write(meta,metaName);
	meta_free(meta);
	
	exit(EXIT_SUCCESS);
}
예제 #15
0
END_TEST

/********************************************************
 * Test all possible projections                       */
START_TEST(test_atct) /* along track cross track */
{
  char error_string[256];
  char in_file[512];
  meta_parameters *meta;
  sprintf(in_file,"%s/new_style_atct.meta",_TEST_DATA_DIR);
  meta = meta_read(in_file);
  meta_write(meta,"test_output/out_atct.meta");
/* look at a couple fields real quick */
  sprintf(error_string,"meta->sar->dopRangeQuad is %-16.11g, should be 0.0001246",meta->sar->range_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->range_doppler_coefficients[2],0.0001246),error_string);
  sprintf(error_string,"meta->sar->dopAzQuad is %-16.11g, should be 2e-07",meta->sar->azimuth_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->azimuth_doppler_coefficients[2],2e-07),error_string);

/* look at the good stuff */
  sprintf(error_string,"meta->projection->param.atct.rlocal is %-16.11g, should be 6000000.0",meta->projection->param.atct.rlocal);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.atct.rlocal,6000000.0),error_string);
  sprintf(error_string,"meta->geo->proj->param.atct.rlocal is %-16.11g, should be 6000000.0",meta->geo->proj->param.atct.rlocal);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.atct.rlocal,6000000.0),error_string);

  sprintf(error_string,"meta->projection->param.atct.alpha1 is %-16.11g, should be 0.6",meta->projection->param.atct.alpha1);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.atct.alpha1,0.6),error_string);
  sprintf(error_string,"meta->geo->proj->param.atct.alpha1 is %-16.11g, should be 0.6",meta->geo->proj->param.atct.alpha1);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.atct.alpha1,0.6),error_string);

  sprintf(error_string,"meta->projection->param.atct.alpha2 is %-16.11g, should be -0.44",meta->projection->param.atct.alpha2);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.atct.alpha2,-0.44),error_string);
  sprintf(error_string,"meta->geo->proj->param.atct.alpha2 is %-16.11g, should be -0.44",meta->geo->proj->param.atct.alpha2);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.atct.alpha2,-0.44),error_string);

  sprintf(error_string,"meta->projection->param.atct.alpha3 is %-16.11g, should be 0.6",meta->projection->param.atct.alpha3);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.atct.alpha3,0.6),error_string);
  sprintf(error_string,"meta->geo->proj->param.atct.alpha3 is %-16.11g, should be 0.6",meta->geo->proj->param.atct.alpha3);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.atct.alpha3,0.6),error_string);

  meta_free(meta);
}
예제 #16
0
END_TEST

START_TEST(test_utm) /* universal transverse mercator */
{
  char error_string[256];
  char in_file[512];
  meta_parameters *meta;
  sprintf(in_file,"%s/new_style_utm.meta",_TEST_DATA_DIR);
  meta = meta_read(in_file);
  meta_write(meta,"test_output/out_utm.meta");
/* look at a couple fields real quick */
  sprintf(error_string,"meta->sar->dopRangeQuad is %-16.11g, should be 0.0001246",meta->sar->range_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->range_doppler_coefficients[2],0.0001246),error_string);
  sprintf(error_string,"meta->sar->dopAzQuad is %-16.11g, should be 2e-07",meta->sar->azimuth_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->azimuth_doppler_coefficients[2],2e-07),error_string);
/* look at the good stuff */
  sprintf(error_string,"meta->projection->param.utm.zone is %d, should be 6",meta->projection->param.utm.zone);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.utm.zone,6),error_string);
  sprintf(error_string,"meta->geo->proj->param.utm.zone is %d, should be 6",meta->geo->proj->param.utm.zone);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.utm.zone,6),error_string);
  meta_free(meta);
}
예제 #17
0
END_TEST

START_TEST(test_lamcc) /* Lambert conformal conic */
{
  char error_string[256];
  char in_file[512];
  meta_parameters *meta;
  sprintf(in_file,"%s/new_style_lamcc.meta",_TEST_DATA_DIR);
  meta = meta_read(in_file);
  meta_write(meta,"test_output/out_lamcc.meta");
/* look at a couple fields real quick */
  sprintf(error_string,"meta->sar->dopRangeQuad is %-16.11g, should be 0.0001246",meta->sar->range_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->range_doppler_coefficients[2],0.0001246),error_string);
  sprintf(error_string,"meta->sar->dopAzQuad is %-16.11g, should be 2e-07",meta->sar->azimuth_doppler_coefficients[2]);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->sar->azimuth_doppler_coefficients[2],0.0000002),error_string);

/* look at the good stuff */
  sprintf(error_string,"meta->projection->param.lamcc.plat1 is %-16.11g, should be 73.123",meta->projection->param.lamcc.plat1);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.lamcc.plat1,73.123),error_string);
  sprintf(error_string,"meta->geo->proj->param.lamcc.plat1 is %-16.11g, should be 73.123",meta->geo->proj->param.lamcc.plat1);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.lamcc.plat1,73.123),error_string);

  sprintf(error_string,"meta->projection->param.lamcc.plat2 is %-16.11g, should be 71.123",meta->projection->param.lamcc.plat2);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.lamcc.plat2,71.123),error_string);
  sprintf(error_string,"meta->geo->proj->param.lamcc.plat2 is %-16.11g, should be 71.123",meta->geo->proj->param.lamcc.plat2);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.lamcc.plat2,71.123),error_string);

  sprintf(error_string,"meta->projection->param.lamcc.lat0 is %-16.11g, should be 72.123",meta->projection->param.lamcc.lat0);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.lamcc.lat0,72.123),error_string);
  sprintf(error_string,"meta->geo->proj->param.lamcc.lat0 is %-16.11g, should be 72.123",meta->geo->proj->param.lamcc.lat0);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.lamcc.lat0,72.123),error_string);
  
  sprintf(error_string,"meta->projection->param.lamcc.lon0 is %f; should be -158.123",meta->projection->param.lamcc.lon0);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->projection->param.lamcc.lon0,-158.123),error_string);
  sprintf(error_string,"meta->geo->proj->param.lamcc.lon0 is %f; should be -158.123",meta->geo->proj->param.lamcc.lon0);
  fail_unless(UNIT_TESTS_FLOAT_COMPARE(meta->geo->proj->param.lamcc.lon0,-158.123),error_string);
  meta_free(meta);
}
예제 #18
0
int asf_logscale(const char *inFile, const char *outFile)
{
  int ii, jj, kk;
  meta_parameters *meta = meta_read(inFile);
  int band_count = meta->general->band_count;
  int sample_count = meta->general->sample_count;
  int line_count = meta->general->line_count;
  float *bufIn = (float *) MALLOC(sizeof(float)*sample_count);
  float *bufOut = (float *) MALLOC(sizeof(float)*sample_count);
  
  char *input = appendExt(inFile, ".img");
  char *output = appendExt(outFile, ".img");
  FILE *fpIn = FOPEN(input, "rb");
  FILE *fpOut = FOPEN(output, "wb");
  for (kk=0; kk<band_count; kk++) {
    for (ii=0; ii<line_count; ii++) {
      get_band_float_line(fpIn, meta, kk, ii, bufIn);
      for (jj=0; jj<sample_count; jj++) {
	if (FLOAT_EQUIVALENT(bufIn[jj], 0.0))
	  bufOut[jj] = 0.0;
	else
	  bufOut[jj] = 10.0 * log10(bufIn[jj]);
      }
      put_band_float_line(fpOut, meta, kk, ii, bufOut);
      asfLineMeter(ii, line_count);
    }
  }
  meta_write(meta, outFile);
  meta_free(meta);
  FCLOSE(fpIn);
  FCLOSE(fpOut);
  FREE(bufIn);
  FREE(bufOut);
  FREE(input);
  FREE(output);

  return FALSE;
}
예제 #19
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;
}
예제 #20
0
static int save_as_asf(ImageInfo *ii,
                       const char *out_file, int what_to_save,
                       int strict_boundary, int load)
{
    // See if we can open the output file up front
    FILE *outFp = fopen(out_file, "wb");
    if (!outFp) {
        // failed to open the output file!
        char errbuf[1024];
        snprintf(errbuf, 1024, "Failed to open %s: %s", out_file,
            strerror(errno));
        message_box(errbuf);
        strcat(errbuf, "\n");
        printf("%s", errbuf);
        return FALSE; // failure
    }

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

    meta_parameters *meta = ii->meta;

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

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

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

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

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

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

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

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

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

    meta_write(out_meta, out_metaname);

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

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

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

    return TRUE;
}
예제 #21
0
int main(int argc, char *argv[])
{
  int extentFlag = FALSE, multiband = FALSE;
  char *extent = (char *) MALLOC(sizeof(char)*1024);
  char *outfile = (char *) MALLOC(sizeof(char)*1024);
  
    handle_common_asf_args(&argc, &argv, ASF_NAME_STRING);
    if (argc>1 && (strcmp(argv[1], "-help")==0 || strcmp(argv[1],"--help")==0))
        help();
    if (argc<3) usage();

    double background_val=0;
    extract_double_options(&argc, &argv, &background_val, "-background",
                           "--background", "-b", NULL);
    if (extract_string_options(&argc, &argv, extent, "-extent", "--extent", 
			       NULL))
      extentFlag = TRUE;
    if (extract_string_options(&argc, &argv, outfile, "-output", "--output",
			       NULL))
      multiband = TRUE;
    
    char *infile = argv[1];

    int i, size_x, size_y, n_inputs=0, start=0, n_bands;
    double start_x, start_y;
    double per_x, per_y;

    asfSplashScreen(argc, argv);
    char *line = (char *) MALLOC(sizeof(char)*512);
    FILE *fpList = FOPEN(infile, "r");
    while (fgets(line, 512, fpList))
      if (strlen(line) > 0)
        n_inputs++;
    FCLOSE(fpList);
    if (extentFlag) {
      n_inputs++;
      start = 1;
    }
    char **infiles = (char **) MALLOC(sizeof(char *)*n_inputs);
    if (extentFlag) {
      infiles[0] = (char *) MALLOC(sizeof(char)*512);
      strcpy(infiles[0], extent);
    }
    fpList = FOPEN(infile, "r");
    for (i=start; i<n_inputs; i++) {
      fgets(line, 512, fpList);
      chomp(line);
      infiles[i] = (char *) MALLOC(sizeof(char)*512);
      strcpy(infiles[i], line);
    }
    FCLOSE(fpList);
    FREE(line);

    if (multiband)
      asfPrintStatus("Stacking %d files to produce: %s\n", n_inputs, outfile);
    else
      asfPrintStatus("Putting %d files in image stack\n", n_inputs);

    asfPrintStatus("Input files:\n");
    for (i=start; i<n_inputs; ++i)
      asfPrintStatus("   %d: %s%s\n", i+1, infiles[i], i==0 ? " (reference)" : "");

    determine_extents(infiles, n_inputs, &size_x, &size_y, &n_bands,
		      &start_x, &start_y, &per_x, &per_y, extentFlag);

    asfPrintStatus("\nStacked image size: %dx%d LxS\n", size_y, size_x);
    asfPrintStatus("  Start X,Y: %f,%f\n", start_x, start_y);
    asfPrintStatus("    Per X,Y: %.2f,%.2f\n", per_x, per_y);

    meta_parameters *meta_out = meta_read(infiles[0]);
    if (multiband)
      meta_out->general->image_data_type = IMAGE_LAYER_STACK;
    meta_out->projection->startX = start_x;
    meta_out->projection->startY = start_y;
    meta_out->general->line_count = size_y;
    meta_out->general->sample_count = size_x;
    meta_out->general->no_data = background_val;
    update_location_block(meta_out);

    //char *outfile_full = appendExt(outfile, ".img");
    char *outfile_full = (char *) MALLOC(sizeof(char)*1024);

    if (multiband) {
      sprintf(outfile_full, "%s.img", stripExt(outfile));
      meta_write(meta_out, outfile_full);
    }
    for (i=start; i<n_inputs; i++) {
      asfPrintStatus("\nProcessing band %d (%s) ... \n", i, infiles[i]);
      if (!multiband) {
	sprintf(outfile_full, "%s_stack.img", stripExt(infiles[i]));
	meta_write(meta_out, outfile_full);
      }
      add_to_stack(outfile_full, i, infiles[i], size_x, size_y, 
                   start_x, start_y, per_x, per_y, multiband);
    }
    meta_free(meta_out);

    FREE(outfile_full);
    for (i=0; i<n_inputs; i++)
      FREE(infiles[i]);
    FREE(infiles);
    FREE(extent);
    FREE(outfile);

    asfPrintStatus("Done.\n");
    return 0;
}
예제 #22
0
static void add_to_stack(char *out, int band, char *file,
                         int size_x, int size_y,
                         double start_x, double start_y,
                         double per_x, double per_y, int multiband)
{
    meta_parameters *metaIn = meta_read(file);
    meta_parameters *metaOut = meta_read(out);
    char *base = (char *) MALLOC(sizeof(char)*512);
    int start_line, start_sample;

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

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

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

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

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

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

    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(line);
    FREE(metaFile);
    FREE(base);
    meta_free(metaIn);
    meta_free(metaOut);
}
예제 #23
0
int update_state_vectors(char *outBaseName, char *file)
{
    int ret = FALSE;
    char *odrFile = NULL;
    meta_parameters *meta = meta_read(outBaseName);

    const char *sensor = meta->general->sensor;
    if (strcmp_case(sensor, "E1") == 0 ||
            strcmp_case(sensor, "ERS1") == 0)
    {
        sensor = "ERS-1";
    }
    if (strcmp_case(sensor, "E2") == 0 ||
            strcmp_case(sensor, "ERS2") == 0)
    {
        sensor = "ERS-2";
    }

    if (strcmp_case(sensor, "ERS-1") != 0 &&
            strcmp_case(sensor, "ERS-2") != 0)
    {
        // not ERS data
        meta_free(meta);
        return ret;
    }

    asfPrintStatus("\nChecking for %s precision state vectors...\n",
                   sensor);

    if (!file || strlen(file) == 0) {
        file = get_arclist_from_settings(sensor);
    }
    if (!file || strlen(file) == 0) {
        return ret;
    }

    if (is_dir(file)) {
        char *arclist = MALLOC(sizeof(char)*(strlen(file) + 128));
        if (file[strlen(file)-1] == DIR_SEPARATOR)
            sprintf(arclist, "%sarclist", file);
        else
            sprintf(arclist, "%s%carclist", file, DIR_SEPARATOR);
        if (isArcList(sensor, arclist))
            odrFile = findInArcList(meta->general->acquisition_date, arclist);
        else
            asfPrintError("No arclist file found in %s\n", file);
        FREE(arclist);
    }
    else if (isArcList(sensor, file))
        odrFile = findInArcList(meta->general->acquisition_date, file);
    else if (!fileExists(file))
        asfPrintError("Not found: %s\n", file);
    else
        // assume file is just a regular ODR file
        odrFile = STRDUP(file);

    if (!odrFile || !fileExists(odrFile))
        asfPrintError("Precision state vector file (%s) does not exist!\n",
                      odrFile ? odrFile : "null");

    asfPrintStatus("Refining %s orbits using ODR file: %s\n",
                   sensor, odrFile);

    FILE *fpIn = FOPEN(odrFile, "rb");

    // Check for new version of ODR file: xODR
    char spec[5];
    FREAD(&spec, 1, 4, fpIn);
    spec[4] = '\0';
    if (strcmp_case(spec, "xODR") != 0)
        asfPrintError("Unsupported precision state vector file (%s) type\n",
                      odrFile);

    // Determine image center time for reference
    julian_date jd;
    jd.year = meta->state_vectors->year;
    jd.jd = meta->state_vectors->julDay;
    double ref_secs = meta->state_vectors->second;
    double ref_time = date2seconds(&jd, ref_secs);
    int stVec_count = meta->state_vectors->vector_count;
    ref_time += meta->state_vectors->vecs[stVec_count/2].time;

    // Initialize structure for updated state vector structure
    meta_state_vectors *prcVec = meta_state_vectors_init(9);
    int year = meta->state_vectors->year;
    prcVec->year = year;
    int julDay = meta->state_vectors->julDay;
    prcVec->julDay = julDay;
    double second = meta->state_vectors->second;
    prcVec->second = second;
    prcVec->vector_count = 9;

    // Read header information
    char satellite[9];
    int begin, repeat_cycle, arc, nRecords, version;
    FREAD(&satellite, 1, 8, fpIn);
    satellite[8] = '\0';
    FREAD(&begin, 1, 4, fpIn);
    ieee_big32(begin);
    FREAD(&repeat_cycle, 1, 4, fpIn);
    ieee_big32(repeat_cycle);
    FREAD(&arc, 1, 4, fpIn);
    ieee_big32(arc);
    FREAD(&nRecords, 1, 4, fpIn);
    ieee_big32(nRecords);
    FREAD(&version, 1, 4, fpIn);
    ieee_big32(version);

    // Read state vectors
    doris_prc_polar *stVec =
        (doris_prc_polar *) MALLOC(sizeof(doris_prc_polar)*nRecords);
    int ii, kk, closest = 0, time, nLat, nLon, nHeight;
    double diff = DAY2SEC*100;
    for (ii=0; ii<nRecords; ii++) {
        FREAD(&time, 1, 4, fpIn);
        ieee_big32(time);
        FREAD(&nLat, 1, 4, fpIn);
        ieee_big32(nLat);
        FREAD(&nLon, 1, 4, fpIn);
        ieee_big32(nLon);
        FREAD(&nHeight, 1, 4, fpIn);
        ieee_big32(nHeight);
        stVec[ii].time = time;
        stVec[ii].lat = (double)nLat/10000000.0;
        stVec[ii].lon = (double)nLon/10000000.0;
        stVec[ii].height = (double)nHeight/1000.0;
        if (fabs((double)time - ref_time) < diff) {
            closest = ii;
            diff = fabs(time - ref_time);
        }
    }
    FCLOSE(fpIn);
    if (closest > 0) {
        asfPrintStatus("Updating orbit information with precision state vectors.\n\n");
        ret = TRUE;

        // Generating state vectors in earth-fixed coordinates
        doris_prc_polar polarVec;
        doris_prc_cartesian cartVec, velOne, velTwo;
        ref_time = date2seconds(&jd, ref_secs);
        for (ii=closest-4; ii<=closest+4; ii++) {
            geocentric_latlon(stVec[ii], &polarVec);
            polar2cartesian(polarVec, &cartVec);

            // Approximate state vector velocity according to getorb FAQs
            // (http://www.deos.tudelft.nl/ers/precorbs/faq.shtml#004001):
            // XYZvel(t) = XYZpos(t + 0.5sec) - XYZpos(t - 0.5sec)
            // Approximating velocities is fine since we will use an interpolation
            // scheme later that does not require these.
            interpolate_prc_vectors(stVec, cartVec.time-0.5, closest-4, closest+4,
                                    &velOne);
            interpolate_prc_vectors(stVec, cartVec.time+0.5, closest-4, closest+4,
                                    &velTwo);

            // Fill in the orbit information into metadata state vector structure
            kk = ii - closest + 4;
            prcVec->vecs[kk].time = cartVec.time - ref_time;
            prcVec->vecs[kk].vec.pos.x = cartVec.x;
            prcVec->vecs[kk].vec.pos.y = cartVec.y;
            prcVec->vecs[kk].vec.pos.z = cartVec.z;
            prcVec->vecs[kk].vec.vel.x = velTwo.x - velOne.x;
            prcVec->vecs[kk].vec.vel.y = velTwo.y - velOne.y;
            prcVec->vecs[kk].vec.vel.z = velTwo.z - velOne.z;
        }
        FREE(meta->state_vectors);
        meta->state_vectors = prcVec;
        meta_write(meta, outBaseName);
        meta_free(meta);
        FREE(stVec);
    }
    else
        asfPrintStatus("\nCould not update orbit information with precision state"
                       " vectors\nOrbit information not available in orbit file "
                       "(%s).\n\n", odrFile);

    return ret;
}
예제 #24
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);
}
예제 #25
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);
}
예제 #26
0
int main(int argc,char **argv)
{
  int lines,samps;                   /* Number of image lines and samples     */
  int fftLen,start_line;             /* FFT length, & line to start processing at*/
  int x,y,i,k;                       /* Counters                              */
  int f_lo1,f_lo2,f_hi1,f_hi2;       /* Filter frequency indicies             */
  int chunk_size,chunk_int;          /* Size of current datablock, & temp value*/
  int last_chunk;                    /* Size of the last chunk                */
  int compensate_for_last_chunk=1;   /* If last chunk = 0 dont loop for last chunk*/
  char *inName, *parmName, *outName; /* Input filename                        */
  float filtStart[2], filtEnd[2];    /* Filter start and stop variables       */
  float df, stop;                    /* Delta and counter variables           */
  complexFloat *inBuf,*outBuf;       /* Input/Output Image Buffers            */
  complexFloat *fftBuf;              /* FFT Buffer for the image              */
  float *ampBuf,*phsBuf;             /* Amplitude and Phase Buffers           */
  float *time_vector,A,B,shift;      /* Time vector, & freq modulation shift vars*/
  float chunk_float;                 /* Temporary value                       */
  FILE *inF, *freqF, *outF1;         /* Input and Output file pointers        */
  float cur_time, f_s;               /* Current time to increment the time vector by */
  meta_parameters *inMeta, *outMeta; /* Meta info about the images            */

/* Usage is shown if the user doesn't give 3 arguements */
  if(argc!=4) { usage(argv[0]); }

  StartWatch();
  printf("Program cpx_filter\n");

/* Get the filename and filter start and end frequencies from the command line*/ 
  inName=argv[1];
  if(findExt(inName)==NULL)
          inName = appendExt(argv[1],".cpx");
  outName=argv[2];
  parmName=argv[3];

/* Get input metadata. Make sure data_type is complex */
  inMeta = meta_read(inName);
  if (inMeta->general->data_type < COMPLEX_BYTE) {
   switch (inMeta->general->data_type) {
     case ASF_BYTE:      inMeta->general->data_type=COMPLEX_BYTE;      break;
     case INTEGER16: inMeta->general->data_type=COMPLEX_INTEGER16; break;
     case INTEGER32: inMeta->general->data_type=COMPLEX_INTEGER32; break;
     case REAL32:    inMeta->general->data_type=COMPLEX_REAL32;    break;
     case REAL64:    inMeta->general->data_type=COMPLEX_REAL64;    break;
    }
    meta_write (inMeta, inName);
  }

/* Open the frequency parameter file and read the parameters */
  if((freqF=FOPEN(parmName,"r"))==NULL) {
    printf("Frequency Parameter File %s could not be Opened!\n",parmName);
    exit(EXIT_FAILURE);
  }
  fscanf(freqF,"%f\n",&f_s);
  fscanf(freqF,"%f\n",&shift);
  fscanf(freqF,"%f %f\n", &filtStart[0], &filtEnd[0]);
  fscanf(freqF,"%f %f\n", &filtStart[1], &filtEnd[1]);

  printf("\n");
  printf("Input file is %s\n",inName);
  printf("Output file is %s.cpx\n",outName);
  printf("Parameter file is %s\n",parmName);
  printf("Filtering from frequencies %.2f to %.2f Hz and %.2f to %.2f in Azimuth\n",filtStart[0],filtEnd[0],filtStart[1],filtEnd[1]);
  printf("The sampling frequency is %f Hz\n",f_s);
  printf("Shifting the spectrum by %.2f Hz\n",shift);

/* Get the number of lines and samples from the input meta file */
  lines = inMeta->general->line_count;
  samps = inMeta->general->sample_count;

  chunk_size  = BLOCK_SIZE;
  chunk_float = (float)lines/chunk_size;
  chunk_int   = lines/chunk_size;
  last_chunk  = (int)((chunk_float-(float)chunk_int) * (float)BLOCK_SIZE + 0.5);
  if( (2*TOSS_SIZE) > last_chunk)
    compensate_for_last_chunk=0;
  printf("Chunk Size is set to %d, the last chunk is %d lines\n",
         chunk_size, last_chunk);

/* Compute the FFT length based on the number of lines. Must be a power of 2 */
  i      = (log10(chunk_size)/log10(2)) + 1;
  fftLen = pow(2,i);
  printf("FFT Length is %d\n",fftLen);
  cfft1d(fftLen,NULL,0);

  printf("The Input Image has %d lines and %d samples\n",lines,samps);

/* Allocate the memory for all the buffers */
  inBuf  = (complexFloat *)MALLOC(sizeof(complexFloat)*samps*fftLen);
  outBuf = (complexFloat *)MALLOC(sizeof(complexFloat)*samps*fftLen);
  fftBuf = (complexFloat *)MALLOC(sizeof(complexFloat)*fftLen);
  ampBuf = (float *)MALLOC(sizeof(float)*fftLen);
  phsBuf = (float *)MALLOC(sizeof(float)*fftLen);
  time_vector = (float *)MALLOC(sizeof(float)*lines);

/* Open the Complex Image File */
  if((inF=FOPEN(inName,"rb"))==NULL) {        
    printf("Complex Image file %s could not be opened\n",inName);
    exit(EXIT_FAILURE);
  }

  strcat(outName,".cpx"); 
  if((outF1=FOPEN(outName,"wb"))==NULL) {
    printf("Unable to write output %s\n",outName);
    exit(EXIT_FAILURE);
  }

  outMeta = meta_copy(inMeta);
  outMeta->general->line_count = 
          chunk_int*(BLOCK_SIZE-2*TOSS_SIZE)+(last_chunk-2*TOSS_SIZE);
  outMeta->general->sample_count = samps; 
  meta_write(outMeta, outName);


/* Find the filter frequency index values */
  df   = f_s/fftLen;
  stop = 0;
  i    = 0;
  while(stop<filtStart[0]) {
    f_lo1 = i;
    stop  = df*i;
    i++;
  }

  stop = 0;
  i    = 0;
  while(stop<filtStart[1]) {
    f_lo2=i;
    stop=df*i;
    i++;
  }

  i    = fftLen;
  stop = df*i;  
  while(stop>filtEnd[0]) {
    f_hi1 = i;
    stop  = df*i;   
    i--;
  }

  i    = fftLen;
  stop = df*i;
  while(stop>filtEnd[1]) {
    f_hi2 = i;
    stop  = df*i;
    i--;
  }

/* Zero out all the arrays and begin processing data */
  cur_time = 0;
  for(i=0; i<fftLen; i++)
  {
    ampBuf[i] = 0;
    phsBuf[i] = 0;
  }

  for(k=0; k<chunk_int+compensate_for_last_chunk; k++)
  {
    printf("\nProcessing Chunk %d of %d\n",k,lines/chunk_size);

    start_line = (k==0) ? 0 : (k*chunk_size)-(2*TOSS_SIZE);

    if (k==chunk_int)
      chunk_size=last_chunk;

    cur_time=start_line*(1/f_s);

  /* Read in the data chunk & put in proper endian order */
    printf("Reading %d Lines Starting at Line %d\n",chunk_size,start_line);
    get_complexFloat_lines(inF, inMeta, start_line, chunk_size, inBuf);

  /* Process the each column */
    printf("Performing the FFT and Filtering Operations\n");
    for(x=0; x<samps; x++)
    {
      if(x%1000 == 0)  printf("Processing Column %d\n",x);

      for(y=0;y<fftLen;y++)
      {
        fftBuf[y].real = 0;
        fftBuf[y].imag = 0;
      }

      for(y=0;y<chunk_size;y++)
      {
        fftBuf[y].real = inBuf[y*samps+x].real;
        fftBuf[y].imag = inBuf[y*samps+x].imag;
      }

      cfft1d(fftLen,fftBuf,-1);

      for (i=0; i<fftLen; i++) 
      {
        ampBuf[i] = sqrt(fftBuf[i].real*fftBuf[i].real
                    + fftBuf[i].imag*fftBuf[i].imag);        

        if(fftBuf[i].imag!=0.0 || fftBuf[i].real!=0.0)
          phsBuf[i] = atan2(fftBuf[i].imag,fftBuf[i].real);
        else
          phsBuf[i] = 0;

        if(((i>f_lo1)&&(i<f_hi1)) || ((i>f_lo2) && (i<f_hi2)))
        {
          ampBuf[i] = 0;
          phsBuf[i] = 0;
        }

        fftBuf[i].real = ampBuf[i]*cos(phsBuf[i]);
        fftBuf[i].imag = ampBuf[i]*sin(phsBuf[i]);        
      }

      cfft1d(fftLen,fftBuf,1);

      for(i=0;i<chunk_size;i++)
      {        
        outBuf[i*samps+x].real = fftBuf[i].real;
        outBuf[i*samps+x].imag = fftBuf[i].imag;
      }        
    }
    printf("Finished the FFT and Filtering Operations\n");

  /* Perform the time-domain frequency shift */ 
    if(shift != 0.0)
    {
      for(i=0; i<chunk_size; i++)
        time_vector[i] = cur_time+(1/f_s)*i;

      printf("\nPerforming time-domain frequency shift of %.2f Hz\n",shift);
      for(y=0; y<chunk_size; y++)
      {
        for(x=0; x<samps; x++)
        {
          A = outBuf[y*samps+x].real;
          B = outBuf[y*samps+x].imag;
          outBuf[y*samps+x].real = A*cos(2*pi*shift*time_vector[y])
                                   - B*sin(2*pi*shift*time_vector[y]);
          outBuf[y*samps+x].imag = B*cos(2*pi*shift*time_vector[y])
                                   + A*sin(2*pi*shift*time_vector[y]);
        }
      }
    }

  /* Write out the data file in big endian format */
    printf("Writing the output lines %d to %d in file %s\n",
      start_line, start_line+chunk_size-TOSS_SIZE, outName);
    put_complexFloat_lines(outF1, outMeta, start_line,
      samps*(chunk_size-TOSS_SIZE), outBuf+(samps*TOSS_SIZE));
  }

  printf("\n");

  FCLOSE(outF1);
  StopWatch();
  return 0;
}
예제 #27
0
int asf_windspeed(platform_type_t platform_type, char *band_id,
                  double wind_dir, int cmod4,
                  double landmaskHeight, char *landmaskFile, char *demFile,
                  char *inBaseName, char *colormapName, char *outBaseName)
{
  char *inDataName, outDataName[1024], outMetaName[1024];
  FILE *in = NULL, *out = NULL;

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

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

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

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

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

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

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

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

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

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

  // Insert colormap into metadata

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

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

  return EXIT_SUCCESS;
}
예제 #28
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);
}
예제 #29
0
파일: md_chown.c 프로젝트: mnv104/capfs
int md_chown(mreq_p request, char *fname)
{
	fmeta meta1;
	int fd,length,i, setgid = -1, force_group_change = 0;
	char temp[MAXPATHLEN];
	dmeta dir;
	struct passwd *pw;
	struct group *grp;


	if ((fd = meta_open(fname, O_RDWR)) < 0) {
		if (errno != EISDIR) {
			PERROR(SUBSYS_META,"md_chown: meta_open");
			return (-1);
		}
	}

   /* check execute permissions on directory */
   strncpy(temp, fname, MAXPATHLEN);
	length = get_parent(temp);
	/* length < 0 means CWD */
   if (length >= 0) {
		dmeta pdir;
		if (meta_access(0, temp, request->uid, request->gid, X_OK) < 0) {
			PERROR(SUBSYS_META,"md_chown: meta_access");
			return(-1);
		}
		get_dmeta(temp, &pdir);
		if(S_ISGID & pdir.dr_mode) {
			setgid = pdir.dr_gid;
		}
	}
	
	/* Read metadata file */	
	if (fd >= 0) {
		if (meta_read(fd, &meta1) < 0) {
			PERROR(SUBSYS_META,"md_chown: meta_read");
			meta_close(fd);
			return (-1);
		}
		lseek(fd, 0, SEEK_SET);
	}
	else { /* directory */
		get_dmeta(fname, &dir);
		meta1.u_stat.st_uid = dir.dr_uid;
		meta1.u_stat.st_gid = dir.dr_gid;
	}

	/* Change owner if necessary */
	if (request->req.chown.owner >= 0) {
		/* root can change this or if uid = file owner uid,
		 * let group chown be performed */
		if (((request->uid != 0) && (request->uid != request->req.chown.owner))
			 || ((request->uid != 0) && (request->uid != meta1.u_stat.st_uid))) 
      {
			errno = EPERM;
			PERROR(SUBSYS_META,"md_chown: permission denied");
			if (fd >= 0)
				meta_close(fd);
			return(-1);
		}
		meta1.u_stat.st_uid = request->req.chown.owner;
	}
	
	/* Change group if necessary */
	if (request->req.chown.group >= 0) {
		if (request->uid) /* not root, check perms */ {
			/* from chown(2), only root or owner can change group
				permissions, so check for owner of file */
			if(request->uid != meta1.u_stat.st_uid){
				LOG(stderr, WARNING_MSG, SUBSYS_META, "md_chown: change group permission denied (1)");
				if (fd >= 0) meta_close(fd);
				errno = EPERM;
				return(-1);
			}

			/* grab group info from /etc/group or wherever */
			if (!(grp = getgrgid(request->req.chown.group))) {
				PERROR(SUBSYS_META,"md_chown: getgrgid");
				if (fd >= 0) meta_close(fd);
				errno = EINVAL;
				return(-1);
			}
			/* see if user is a member of target group in /etc/group or
				/etc/passwd */
			if (!(pw = getpwuid(request->uid))) {
				PERROR(SUBSYS_META,"md_chown: getpwuid");
				if (fd >= 0) meta_close(fd);
				errno = EINVAL;
				return(-1);
			}
			for(i=0;grp->gr_mem[i] && strcmp(pw->pw_name, grp->gr_mem[i]); i++);
			if(!grp->gr_mem[i] && pw->pw_gid != request->req.chown.group) {
				LOG(stderr, WARNING_MSG, SUBSYS_META, "md_chown: change group permission denied (2)");
				if (fd >= 0) meta_close(fd);
				errno = EPERM;
				return(-1);
			}
		}
		if (setgid == -1) {
			meta1.u_stat.st_gid = request->req.chown.group;
		}
		else {
			force_group_change = request->req.chown.force_group_change;
			if(force_group_change == 1) {
				meta1.u_stat.st_gid = request->req.chown.group;
			}
			else {
				meta1.u_stat.st_gid = setgid;
			}
		}
	}	

	/* Write metadata back */
	if (fd >= 0) {
		if (meta_write(fd, &meta1) < 0) {
			PERROR(SUBSYS_META,"md_chown: meta_write");
			meta_close(fd);
			return(-1);
		}
	}
	else { /* directory */
		dir.dr_uid = meta1.u_stat.st_uid;
		dir.dr_gid = meta1.u_stat.st_gid;
		put_dmeta(fname, &dir);
	}

	/* Close metadata file */
	if (fd >= 0 && (meta_close(fd)) < 0) {
		PERROR(SUBSYS_META,"md_chown: meta_close");
		return(-1);
	}	

	/* Do acknowledge and return */
	return (0);
}
예제 #30
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;
}