int main(int argc, char **argv) { dbf_header_t *header; extern int currArg; // Pre-initialized to 1 int n=0; char motion[512], deformation[512], connectivity[512], definition[512]; char cell[512], shape_type[25], line[1024], **col; // Parse command line if ((argc-currArg)<1) { printf("Insufficient arguments.\n"); usage(); } strcpy(motion, argv[currArg]); strcpy(deformation, argv[currArg+1]); strcpy(connectivity, argv[currArg+2]); strcpy(definition, argv[currArg+3]); strcpy(cell, argv[currArg+4]); asfSplashScreen(argc, argv); // Reading cell connectivity file asfPrintStatus("Reading cell connectivity file ...\n"); FILE *fp = FOPEN(connectivity, "r"); int ii, kk, nCells = 0; fgets(line, 1024, fp); while (fgets(line, 1024, fp)) nCells++; FCLOSE(fp); rgps_cell_t *cells = (rgps_cell_t *) MALLOC(sizeof(rgps_cell_t)*nCells); fp = FOPEN(connectivity, "r"); fgets(line, 1024, fp); for (ii=0; ii<nCells; ii++) { fgets(line, 1024, fp); chomp(line); split_into_array(line, ',', &n, &col); cells[ii].cell_id = atoi(col[0]); cells[ii].grid_id = atoi(col[1]); cells[ii].order = atoi(col[2]); free_char_array(&col, n); } FCLOSE(fp); // Reading cell definition file asfPrintStatus("Reading cell definition file ...\n"); fp = FOPEN(definition, "r"); fgets(line, 1024, fp); while (fgets(line, 1024, fp)) { chomp(line); split_into_array(line, ',', &n, &col); for (ii=0; ii<nCells; ii++) if (cells[ii].cell_id == atoi(col[0])) { cells[ii].birth_year = atoi(col[3]); cells[ii].birth_time = atof(col[4]); cells[ii].death_year = atoi(col[5]); cells[ii].death_time = atof(col[6]); } free_char_array(&col, n); } FCLOSE(fp); // Reading ice motion file asfPrintStatus("Reading ice motion file ...\n"); read_header_config("RGPS_LP_GRID", &header, &n, shape_type); fp = FOPEN(motion, "r"); int nGrids = 0; fgets(line, 1024, fp); chomp(line); while (fgets(line, 1024, fp)) nGrids++; FCLOSE(fp); rgps_grid_t *grid = (rgps_grid_t *) MALLOC(sizeof(rgps_grid_t)*nGrids); fp = FOPEN(motion, "r"); fgets(line, 1024, fp); for (ii=0; ii<nGrids; ii++) { fgets(line, 1024, fp); chomp(line); split_into_array(line, ',', &n, &col); for (kk=0; kk<n; kk++) { if (strcmp_case(header[kk].shape, "IMAGE_ID") == 0) strcpy(grid[ii].image_id, col[kk]); else if (strcmp_case(header[kk].shape, "GPID") == 0) grid[ii].gpid = atoi(col[kk]); else if (strcmp_case(header[kk].shape, "OBS_YEAR") == 0) grid[ii].obs_year = atoi(col[kk]); else if (strcmp_case(header[kk].shape, "OBS_TIME") == 0) grid[ii].obs_time = atof(col[kk]); else if (strcmp_case(header[kk].shape, "BIRTH_YEAR") == 0) grid[ii].birth_year = atoi(col[kk]); else if (strcmp_case(header[kk].shape, "BIRTH_TIME") == 0) grid[ii].birth_time = atof(col[kk]); else if (strcmp_case(header[kk].shape, "DEATH_YEAR") == 0) grid[ii].death_year = atoi(col[kk]); else if (strcmp_case(header[kk].shape, "DEATH_TIME") == 0) grid[ii].death_time = atof(col[kk]); else if (strcmp_case(header[kk].shape, "X_MAP") == 0) grid[ii].x = atof(col[kk]); else if (strcmp_case(header[kk].shape, "Y_MAP") == 0) grid[ii].y = atof(col[kk]); } free_char_array(&col, n); } FCLOSE(fp); // Reading ice deformation file asfPrintStatus("Converting ice deformation file ...\n"); read_header_config("RGPS_DP_GRID", &header, &n, shape_type); fp = FOPEN(deformation, "r"); FILE *fpOut = FOPEN(cell, "w"); fprintf(fpOut, "CELL_TIME,CELL_ID,STREAM,BIRTH_YEAR,BIRTH_TIME,DEATH_YEAR," "DEATH_TIME,N_OBS,OBS_YEAR,OBS_TIME,X_MAP,Y_MAP,LAT,LON,X_DISP,Y_DISP," "C_AREA,D_AREA,DTP,DUDX,DUDY,DVDX,DVDY,IMAGE_ID,DISP_MAG\n"); fgets(line, 1024, fp); // header line while (fgets(line, 1024, fp)) { chomp(line); rgps_grid2cell(line, grid, nGrids, cells, nCells, header, fpOut); } FCLOSE(fp); FCLOSE(fpOut); FREE(grid); FREE(cells); return(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; /*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->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; }
void calc_stats_from_file_with_formula(const char *inFile, char *bands, calc_stats_formula_t formula_callback, double mask, double *min, double *max, double *mean, double *stdDev, gsl_histogram **histogram) { int ii,jj,kk; const int N=MAX_BANDS; *min = 999999; *max = -999999; *mean = 0.0; meta_parameters *meta = meta_read(inFile); int band_numbers[N]; for (ii=0; ii<N; ++ii) band_numbers[ii] = -1; int band_count = 0; if (bands) { char *s = STRDUP(bands); // a copy we can fiddle with char *q, *p = s; do { q = strchr(p, ','); if (q) *q = '\0'; if (strlen(p) > 0 && strcmp(p, "???") != 0) { band_numbers[band_count] = get_band_number(meta->general->bands, meta->general->band_count, p); //printf("%s -> %d\n", p, band_numbers[band_count]); ++band_count; } if (q) p = q+1; } while (q); FREE(s); } long band_offsets[N]; float *band_data[N]; for (ii=0; ii<N; ++ii) { if (band_numbers[ii] >= 0) { band_offsets[ii] = meta->general->line_count * band_numbers[ii]; band_data[ii] = MALLOC(sizeof(float)*meta->general->sample_count); } else { band_offsets[ii] = -1; band_data[ii] = NULL; } } // pass 1 -- calculate mean, min & max FILE *fp = FOPEN(inFile, "rb"); long long pixel_count=0; asfPrintStatus("\nCalculating min, max, and mean...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter((double)ii/(double)meta->general->line_count); for (kk=0; kk<N; ++kk) { if (band_data[kk]) { assert(band_offsets[kk] >= 0); get_float_line(fp, meta, ii + band_offsets[kk], band_data[kk]); } } for (jj=0; jj<meta->general->sample_count; ++jj) { int is_masked = FALSE; if (ISNAN(mask)) { for (kk=0; kk<N; ++kk) if (band_data[kk] && FLOAT_EQUIVALENT(band_data[kk][jj], mask)) is_masked = TRUE; } if (!is_masked) { double data_arr[N]; int ll; for (ll=0, kk=0; kk<N; ++kk) if (band_data[kk]) data_arr[ll++] = band_data[kk][jj]; assert(ll==band_count); double val = formula_callback(data_arr, mask); if (val < *min) *min = val; if (val > *max) *max = val; *mean += val; ++pixel_count; } } } asfPercentMeter(1.0); FCLOSE(fp); *mean /= pixel_count; // Guard against weird data if(!(*min<*max)) *max = *min + 1; // Initialize the histogram. const int num_bins = 256; gsl_histogram *hist = gsl_histogram_alloc (num_bins); gsl_histogram_set_ranges_uniform (hist, *min, *max); *stdDev = 0.0; // pass 2 -- update histogram, calculate standard deviation fp = FOPEN(inFile, "rb"); asfPrintStatus("\nCalculating standard deviation and histogram...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter((double)ii/(double)meta->general->line_count); for (kk=0; kk<N; ++kk) { if (band_data[kk]) { assert(band_offsets[kk] >= 0); get_float_line(fp, meta, ii + band_offsets[kk], band_data[kk]); } } for (jj=0; jj<meta->general->sample_count; ++jj) { int is_masked = FALSE; if (ISNAN(mask)) { for (kk=0; kk<N; ++kk) if (band_data[kk] && FLOAT_EQUIVALENT(band_data[kk][jj], mask)) is_masked = TRUE; } if (!is_masked) { double data_arr[N]; int ll; for (ll=0, kk=0; kk<N; ++kk) if (band_data[kk]) data_arr[ll++] = band_data[kk][jj]; assert(ll==band_count); double val = formula_callback(data_arr, mask); *stdDev += (val - *mean) * (val - *mean); gsl_histogram_increment (hist, val); } } } asfPercentMeter(1.0); FCLOSE(fp); *stdDev = sqrt(*stdDev/(pixel_count - 1)); for (ii=0; ii<N; ++ii) if (band_data[ii]) FREE(band_data[ii]); *histogram = hist; }
// Main program body. int main (int argc, char *argv[]) { char *inFile, *outFile; int currArg = 1; int kernel_size = -1; int NUM_ARGS = 2; handle_license_and_version_args(argc, argv, ASF_NAME_STRING); asfSplashScreen(argc, argv); if (argc<=1) usage(ASF_NAME_STRING); else if (strmatches(argv[1],"-help","--help",NULL)) print_help(); while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key,"-help","--help",NULL)) { print_help(); // doesn't return } else if (strmatches(key,"-log","--log",NULL)) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag = TRUE; } else if (strmatches(key,"-quiet","--quiet","-q",NULL)) { quietflag = TRUE; } else if (strmatches(key,"-kernel-size","--kernel-size","-ks","-k",NULL)) { CHECK_ARG(1); kernel_size = atoi(GET_ARG(1)); } else { --currArg; break; } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments.\n"); usage(argv[0]); } else if ((argc-currArg) > NUM_ARGS) { printf("Unknown argument: %s\n", argv[currArg]); usage(argv[0]); } inFile = argv[currArg]; outFile = argv[currArg+1]; if (kernel_size < 0) asfPrintError("No kernel size specified!\n" "Use the option '-kernel-size'.\n"); char *in_base = get_basename(inFile); char *out_base = get_basename(outFile); asfPrintStatus("Smoothing image: %s -> %s\n", in_base, out_base); smooth(inFile, outFile, kernel_size, EDGE_TRUNCATE); asfPrintStatus("Done.\n"); free(in_base); free(out_base); return EXIT_SUCCESS; }
// Main program body. int main (int argc, char *argv[]) { char *leader_file_list, *output_file, file[255]; struct dataset_sum_rec *dssr; struct att_data_rec *atdr; struct VFDRECV *facdr; int currArg = 1; int NUM_ARGS = 2; // process log/quiet/license/etc options handle_common_asf_args(&argc, &argv, ASF_NAME_STRING); asfSplashScreen(argc, argv); if (argc<=1) usage(ASF_NAME_STRING); else if (strmatches(argv[1],"-help","--help",NULL)) print_help(); else if (argc<=2) usage(ASF_NAME_STRING); while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key,"-help","--help",NULL)) { print_help(); // doesn't return } else { --currArg; break; } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments.\n"); usage(argv[0]); } else if ((argc-currArg) > NUM_ARGS) { printf("Unknown argument: %s\n", argv[currArg]); usage(argv[0]); } leader_file_list = argv[currArg]; output_file = argv[currArg+1]; // Read granule information FILE *fpIn = FOPEN(leader_file_list, "r"); FILE *fpOut = FOPEN(output_file, "w"); fprintf(fpOut, "Leader_file, Yaw, Doppler_range, Doppler_azimuth\n"); dssr = (struct dataset_sum_rec *) MALLOC(sizeof(struct dataset_sum_rec)); atdr = (struct att_data_rec *) MALLOC(sizeof(struct att_data_rec)); facdr = (struct VFDRECV *) MALLOC(sizeof(struct VFDRECV)); double yaw; while (fgets(file, 1024, fpIn)) { file[strlen(file)-1] = '\0'; if (get_dssr(file, dssr) < 0) { asfPrintWarning("Leader file (%s) does not contain data set summary" " record\n", file); continue; } if (get_atdr(file, atdr) < 0) { asfPrintWarning("Leader file (%s) does not contain attitude data record", "\n", file); continue; } if (get_asf_facdr(file, facdr) < 0) { asfPrintWarning("Leader file (%s) does not contain facility related data" " record\n", file); continue; } yaw = facdr->scyaw; if (FLOAT_EQUIVALENT(yaw, 0.0)) yaw = atdr->data->yaw; fprintf(fpOut, "%s, %.4lf, %.3lf, %.3lf\n", file, yaw, dssr->crt_dopcen[0], dssr->alt_dopcen[0]); } FCLOSE(fpIn); FCLOSE(fpOut); FREE(dssr); FREE(atdr); FREE(facdr); asfPrintStatus("Done.\n"); return EXIT_SUCCESS; }
int asf_calibrate(const char *inFile, const char *outFile, radiometry_t outRadiometry, int wh_scaleFlag) { meta_parameters *metaIn = meta_read(inFile); meta_parameters *metaOut = meta_read(inFile); if (!metaIn->calibration) { asfPrintError("This data cannot be calibrated, missing calibration block.\n"); } // Check for valid output radiometry if (outRadiometry == r_AMP || outRadiometry == r_POWER) asfPrintError("Invalid radiometry (%s) passed into calibration function!\n", radiometry2str(outRadiometry)); // Check whether output radiometry fits with Woods Hole scaling flag if (wh_scaleFlag && outRadiometry >= r_SIGMA && outRadiometry <= r_GAMMA) outRadiometry += 3; // This can only work if the image is in some SAR geometry if (metaIn->projection && metaIn->projection->type != SCANSAR_PROJECTION) asfPrintError("Can't apply calibration factors to map projected images\n" "(Amplitude or Power only)\n"); radiometry_t inRadiometry = metaIn->general->radiometry; asfPrintStatus("Calibrating %s image to %s image\n\n", radiometry2str(inRadiometry), radiometry2str(outRadiometry)); // FIXME: This function should be able to remap between different // radiometry projections. if (metaIn->general->radiometry != r_AMP) asfPrintError("Currently only AMPLITUDE as radiometry is supported!\n"); metaOut->general->radiometry = outRadiometry; int dbFlag = FALSE; if (outRadiometry >= r_SIGMA && outRadiometry <= r_GAMMA) metaOut->general->no_data = 0.0001; if (outRadiometry >= r_SIGMA_DB && outRadiometry <= r_GAMMA_DB) { metaOut->general->no_data = -40.0; dbFlag = TRUE; } if (metaIn->general->image_data_type != POLARIMETRIC_IMAGE) { if (outRadiometry == r_SIGMA || outRadiometry == r_SIGMA_DB) metaOut->general->image_data_type = SIGMA_IMAGE; else if (outRadiometry == r_BETA || outRadiometry == r_BETA_DB) metaOut->general->image_data_type = BETA_IMAGE; else if (outRadiometry == r_GAMMA || outRadiometry == r_GAMMA_DB) metaOut->general->image_data_type = GAMMA_IMAGE; } if (wh_scaleFlag) metaOut->general->data_type = ASF_BYTE; char *input = appendExt(inFile, ".img"); char *output = appendExt(outFile, ".img"); FILE *fpIn = FOPEN(input, "rb"); FILE *fpOut = FOPEN(output, "wb"); int dualpol = strncmp_case(metaIn->general->mode, "FBD", 3) == 0 ? 1 : 0; int band_count = metaIn->general->band_count; int sample_count = metaIn->general->sample_count; int line_count = metaIn->general->line_count; char **bands = extract_band_names(metaIn->general->bands, band_count); float *bufIn = (float *) MALLOC(sizeof(float)*sample_count); float *bufOut = (float *) MALLOC(sizeof(float)*sample_count); float *bufIn2 = NULL, *bufOut2 = NULL, *bufOut3 = NULL; if (dualpol && wh_scaleFlag) { bufIn2 = (float *) MALLOC(sizeof(float)*sample_count); bufOut2 = (float *) MALLOC(sizeof(float)*sample_count); bufOut3 = (float *) MALLOC(sizeof(float)*sample_count); metaOut->general->band_count = 3; sprintf(metaOut->general->bands, "%s,%s,%s-%s", bands[0], bands[1], bands[0], bands[1]); } int ii, jj, kk; float cal_dn, cal_dn2; double incid; if (dualpol && wh_scaleFlag) { metaOut->general->image_data_type = RGB_STACK; for (ii=0; ii<line_count; ii++) { get_band_float_line(fpIn, metaIn, 0, ii, bufIn); get_band_float_line(fpIn, metaIn, 1, ii, bufIn2); for (jj=0; jj<sample_count; jj++) { // Taking the remapping of other radiometries out for the moment //if (inRadiometry >= r_SIGMA && inRadiometry <= r_BETA_DB) //bufIn[jj] = cal2amp(metaIn, incid, jj, bands[kk], bufIn[jj]); incid = meta_incid(metaIn, ii, jj); cal_dn = get_cal_dn(metaOut, incid, jj, bufIn[jj], bands[0], dbFlag); cal_dn2 = get_cal_dn(metaOut, incid, jj, bufIn2[jj], bands[1], dbFlag); if (FLOAT_EQUIVALENT(cal_dn, metaIn->general->no_data) || cal_dn == cal_dn2) { bufOut[jj] = 0; bufOut2[jj] = 0; bufOut3[jj] = 0; } else { bufOut[jj] = (cal_dn + 31) / 0.15 + 1.5; bufOut2[jj] = (cal_dn2 + 31) / 0.15 + 1.5; bufOut3[jj] = bufOut[jj] - bufOut2[jj]; } } put_band_float_line(fpOut, metaOut, 0, ii, bufOut); put_band_float_line(fpOut, metaOut, 1, ii, bufOut2); put_band_float_line(fpOut, metaOut, 2, ii, bufOut3); asfLineMeter(ii, line_count); } } else { for (kk=0; kk<band_count; kk++) { for (ii=0; ii<line_count; ii++) { get_band_float_line(fpIn, metaIn, kk, ii, bufIn); for (jj=0; jj<sample_count; jj++) { // Taking the remapping of other radiometries out for the moment //if (inRadiometry >= r_SIGMA && inRadiometry <= r_BETA_DB) //bufIn[jj] = cal2amp(metaIn, incid, jj, bands[kk], bufIn[jj]); if (strstr(bands[kk], "PHASE") == NULL) { incid = meta_incid(metaIn, ii, jj); cal_dn = get_cal_dn(metaOut, incid, jj, bufIn[jj], bands[kk], dbFlag); if (wh_scaleFlag) { if (FLOAT_EQUIVALENT(cal_dn, metaIn->general->no_data)) bufOut[jj] = 0; else bufOut[jj] = (cal_dn + 31) / 0.15 + 1.5; } else bufOut[jj] = cal_dn; } else // PHASE band, do nothing bufOut[jj] = bufIn[jj]; } put_band_float_line(fpOut, metaOut, kk, ii, bufOut); asfLineMeter(ii, line_count); } if (kk==0) sprintf(metaOut->general->bands, "%s-%s", radiometry2str(outRadiometry), bands[kk]); else { char tmp[255]; sprintf(tmp, ",%s-%s", radiometry2str(outRadiometry), bands[kk]); strcat(metaOut->general->bands, tmp); } } } meta_write(metaOut, outFile); meta_free(metaIn); meta_free(metaOut); FREE(bufIn); FREE(bufOut); if (dualpol) { FREE(bufIn2); FREE(bufOut2); FREE(bufOut3); } for (kk=0; kk<band_count; ++kk) FREE(bands[kk]); FREE(bands); FCLOSE(fpIn); FCLOSE(fpOut); FREE(input); FREE(output); return FALSE; }
static int proj_to_sr(const char *infile, const char *outfile, double pixel_size) { int ii, jj, kk; const float_image_sample_method_t sampling_method = FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR; // overall algorithm: // 1. find extents in time/slant space // 2. for each pixel in output, resample in input space meta_parameters *inMeta = meta_read(infile); int nl = inMeta->general->line_count; int ns = inMeta->general->sample_count; if (!inMeta->projection && !inMeta->transform) asfPrintError("Expected a projection/transform block!\n"); if (!inMeta->state_vectors) asfPrintError("Input data does not have state vectors!\n"); //asfPrintStatus("Converting %s to slant range...\n", infile); // first, find extents in time/slant space // do this by projecting image corners to time/slant int tl_x=0, tl_y=0; int tr_x=ns-1, tr_y=0; int bl_x=0, bl_y=nl-1; int br_x=ns-1, br_y=nl-1; // we have to find the "real" corners of the image // do this using the first band of the input image as a reference if (inMeta->general->band_count == 1) asfPrintStatus("Tiling the input image...\n"); else asfPrintStatus("Tiling the reference band of the input image...\n"); FloatImage *in = float_image_new_from_metadata(inMeta, infile); // find top left pixel -- TOP-most non-no-data pixel in the image for (ii=0; ii<nl; ++ii) for (jj=0; jj<ns; ++jj) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { tl_x = jj; tl_y = ii; goto found_tl; } } asfPrintError("Couldn't find top-left pixel! Entire image no data?\n"); found_tl: // find top right pixel -- RIGHT-most non-no-data pixel in the image for (jj=ns-1; jj>=0; --jj) for (ii=0; ii<nl; ++ii) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { tr_x = jj; tr_y = ii; goto found_tr; } } asfPrintError("Couldn't find top-right pixel! Entire image no data?\n"); found_tr: // find bottom left pixel -- LEFT-most non-no-data pixel in the image for (jj=0; jj<ns; ++jj) for (ii=nl-1; ii>=0; --ii) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { bl_x = jj; bl_y = ii; goto found_bl; } } asfPrintError("Couldn't find bottom-left pixel! Entire image no data?\n"); found_bl: // find bottom right pixel -- BOTTOM-most non-no-data pixel in the image for (ii=nl-1; ii>=0; --ii) for (jj=ns-1; jj>=0; --jj) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { br_x = jj; br_y = ii; goto found_br; } } asfPrintError("Couldn't find bottom-right pixel! Entire image no data?\n"); found_br: asfPrintStatus("Determining image extents in time/slant coordinates.\n"); //asfPrintStatus("Corners are at: TL (%d,%d)\n", tl_y, tl_x); //asfPrintStatus(" (line,sample) TR (%d,%d)\n", tr_y, tr_x); //asfPrintStatus(" BL (%d,%d)\n", bl_y, bl_x); //asfPrintStatus(" BR (%d,%d)\n", br_y, br_x); double tl_time, tl_slant; double tr_time, tr_slant; double bl_time, bl_slant; double br_time, br_slant; meta_get_timeSlantDop(inMeta, tl_y, tl_x, &tl_time, &tl_slant, NULL); meta_get_timeSlantDop(inMeta, tr_y, tr_x, &tr_time, &tr_slant, NULL); meta_get_timeSlantDop(inMeta, bl_y, bl_x, &bl_time, &bl_slant, NULL); meta_get_timeSlantDop(inMeta, br_y, br_x, &br_time, &br_slant, NULL); //asfPrintStatus("Corners are at: TL (%f,%f)\n", tl_time, tl_slant); //asfPrintStatus(" (time,slant) TR (%f,%f)\n", tr_time, tr_slant); //asfPrintStatus(" BL (%f,%f)\n", bl_time, bl_slant); //asfPrintStatus(" BR (%f,%f)\n", br_time, br_slant); double slant_start = min4(tl_slant, tr_slant, bl_slant, br_slant); double slant_end = max4(tl_slant, tr_slant, bl_slant, br_slant); double time_min = min4(tl_time, tr_time, bl_time, br_time); double time_max = max4(tl_time, tr_time, bl_time, br_time); double slant_incr; double time_start, time_end, time_incr; int onl, ons; if (pixel_size > 0) { slant_incr = pixel_size; ons = (slant_end - slant_start) / slant_incr; if (inMeta->sar) { // in this case, the original data has a SAR block, we will use the // same azimuth time per pixel. time_incr = inMeta->sar->azimuth_time_per_pixel; // we always want to be DECREASING in time // latest time is on top (line 1), earliest on bottom (line ONL) if (time_incr > 0) { time_incr = -time_incr; inMeta->sar->azimuth_time_per_pixel = -inMeta->sar->azimuth_time_per_pixel; } time_start = time_max; time_end = time_min; onl = (time_end - time_start) / time_incr; } else { // here, no sar block in the original data, just make a square // image with decreasing time onl = ons; time_incr = (time_min - time_max) / (double)onl; time_start = time_max; time_end = time_min; } } else { // not provided a slant range pixel size, we'll figure something out if (inMeta->sar) { // use the same azimuth time per pixel. time_incr = inMeta->sar->azimuth_time_per_pixel; // we always want to be DECREASING in time // latest time is on top (line 1), earliest on bottom (line ONL) if (time_incr > 0) { time_incr = -time_incr; inMeta->sar->azimuth_time_per_pixel = -inMeta->sar->azimuth_time_per_pixel; } time_start = time_max; time_end = time_min; onl = (time_end - time_start) / time_incr; } else { // no info... determine azimuth time per pixel by keeping // the height the same as in the original image onl = nl; time_incr = (time_min - time_max) / (double)onl; time_start = time_max; time_end = time_min; } // make it square, to get the slant range pixel size ons = onl; pixel_size = slant_incr = (slant_end - slant_start) / (double)ons; } asfRequire(onl > 0, "Internal Error: Invalid output line count: %d\n", onl); asfRequire(ons > 0, "Internal Error: Invalid output sample count: %d\n", ons); asfPrintStatus(" Slant range values: %f -> %f\n", slant_start, slant_end); asfPrintStatus(" Slant range pixel size: %f\n", pixel_size); asfPrintStatus(" Time values: %f -> %f\n", time_start, time_end); asfPrintStatus(" Output Image will be %5d x %5d LxS\n", onl, ons); asfPrintStatus(" (Input Image was %5d x %5d LxS)\n", nl, ns); // generate a grid over the image, to generate our splines // this grid size seems to work pretty well... int n = 120; asfPrintStatus("Creating %dx%d mapping grid...\n", n, n); // changed how these are calculated, so that the spline will cover // the entire value range double time_grid_incr = fabs(time_end - time_start) / (double)(n-1); if (time_incr < 0) time_grid_incr = -time_grid_incr; double slant_grid_incr = fabs(slant_end - slant_start) / (double)(n-1); if (slant_incr < 0) slant_grid_incr = -slant_grid_incr; // allocating memory for the splines, and the arrays to generate them gsl_interp_accel **samp_accels = MALLOC(sizeof(gsl_interp_accel *) * n); gsl_spline **samp_splines = MALLOC(sizeof(gsl_spline *) * n); gsl_interp_accel **line_accels = MALLOC(sizeof(gsl_interp_accel *) * n); gsl_spline **line_splines = MALLOC(sizeof(gsl_spline *) * n); double *slant_in = MALLOC(sizeof(double)*n); double *line_out = MALLOC(sizeof(double)*n); double *samp_out = MALLOC(sizeof(double)*n); // an alias -- use the same array (to save memory -- these are not used // at the same time), but create an alias for it, so it is not so confusing double *time_in = slant_in; //double max_err = 0; // set up the vertical splines for (jj=0; jj<n; ++jj) { double slant = slant_start + jj*slant_grid_incr; for (ii=0; ii<n; ++ii) { // splines need strictly increasing range variables if (time_grid_incr > 0) time_in[ii] = time_start + ii*time_grid_incr; else time_in[ii] = time_end - ii*time_grid_incr; ts2ls(inMeta, time_in[ii], slant, &line_out[ii], &samp_out[ii]); //printf("time: %f, slant: %f ==> line: %f, samp %f\n", // time_in[ii], slant, line_out[ii], samp_out[ii]); } samp_accels[jj] = gsl_interp_accel_alloc(); samp_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n); gsl_spline_init(samp_splines[jj], time_in, samp_out, n); line_accels[jj] = gsl_interp_accel_alloc(); line_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n); gsl_spline_init(line_splines[jj], time_in, line_out, n); } // now, we're on to the resampling stage.. loop through output pixels asfPrintStatus("Generating slant range image...\n"); double no_data_value = meta_is_valid_double(inMeta->general->no_data) ? inMeta->general->no_data : 0; // keep track of error sizes double max_error = 0; double avg_error = 0; int count = 0; // these stride values allow us to track when we're in between grid points int ii_n = onl/n; int jj_n = ons/n; int ii_n2 = ii_n/2; int jj_n2 = jj_n/2; // set up output metadata meta_parameters *outMeta = meta_read(infile); if (outMeta->transform) { FREE(outMeta->transform); outMeta->transform = NULL; } if (outMeta->projection) { FREE(outMeta->projection); outMeta->projection = NULL; } outMeta->general->line_count = onl; outMeta->general->sample_count = ons; if (!outMeta->sar) outMeta->sar = meta_sar_init(); outMeta->sar->image_type = 'S'; outMeta->sar->azimuth_time_per_pixel = time_incr; assert(outMeta->sar->azimuth_time_per_pixel < 0); outMeta->sar->time_shift = time_start; outMeta->general->y_pixel_size = inMeta->sar->azimuth_time_per_pixel / time_incr * inMeta->general->y_pixel_size; assert(outMeta->general->y_pixel_size > 0); outMeta->sar->slant_range_first_pixel = slant_start; outMeta->general->x_pixel_size = slant_incr; outMeta->sar->line_increment = outMeta->sar->sample_increment = 1; outMeta->general->start_sample = outMeta->general->start_line = 0; outMeta->general->no_data = no_data_value; char **band_name = extract_band_names(inMeta->general->bands, inMeta->general->band_count); // now generate output image char *img_file = appendExt(outfile, ".img"); float *out = MALLOC(sizeof(float) * ons); for (kk=0; kk<inMeta->general->band_count; ++kk) { if (inMeta->general->band_count != 1) asfPrintStatus("Working on band: %s\n", band_name[kk]); // for the 2nd and higher bands, free the band from the previous iteration, // and read in the next band from the input image if (kk>0) { float_image_free(in); asfPrintStatus("Loading input...\n"); in = float_image_band_new_from_metadata(inMeta, kk, infile); } FILE *ofp = FOPEN(img_file, kk==0 ? "wb" : "ab"); asfPrintStatus("Generating output...\n"); for (ii=0; ii<onl; ++ii) { asfLineMeter(ii,onl); double time = time_start + ii * time_incr; // set up horizontal splines for this row gsl_interp_accel *samp_accel = gsl_interp_accel_alloc(); gsl_spline *samp_spline = gsl_spline_alloc(gsl_interp_cspline, n); gsl_interp_accel *line_accel = gsl_interp_accel_alloc(); gsl_spline *line_spline = gsl_spline_alloc(gsl_interp_cspline, n); //printf("time: %f slant: %f\n", time, slant_start); for (jj=0; jj<n; ++jj) { slant_in[jj] = slant_start + jj * slant_grid_incr; //printf("time: %f slant: %f\n", time, slant_in[jj]); samp_out[jj] = gsl_spline_eval_check(samp_splines[jj], time, samp_accels[jj]); line_out[jj] = gsl_spline_eval_check(line_splines[jj], time, line_accels[jj]); //printf("samp_out: %f line_out: %f\n", samp_out[jj], line_out[jj]); } gsl_spline_init(samp_spline, slant_in, samp_out, n); gsl_spline_init(line_spline, slant_in, line_out, n); // use the splines to produce output pixels for (jj=0; jj<ons; ++jj) { double slant = slant_start + jj * slant_incr; double samp = gsl_spline_eval_check(samp_spline, slant, samp_accel); double line = gsl_spline_eval_check(line_spline, slant, line_accel); // check the spline every so often (halfway between grid points) // only do this on band #1 (the reference band) if (kk==0 && ii%ii_n2==0 && ii%ii_n!=0 && jj%jj_n2==0 && jj%jj_n!=0) { double samp_real, line_real; ts2ls(inMeta, time, slant, &line_real, &samp_real); double err = (line-line_real)*(line-line_real) + (samp-samp_real)*(samp-samp_real); //printf("(%d,%d) -- Actual: (%f,%f) Splined: (%f,%f)\n", // ii, jj, line_real, samp_real, line, samp); if (err > max_error) max_error = err; avg_error += err; ++count; } // now interpolate within the original image // if we are outside, use "no_data" from metadata double val = no_data_value; if (line > 0 && line < nl-1 && samp > 0 && samp < ns-1) val = float_image_sample(in, samp, line, sampling_method); out[jj] = (float)val; } gsl_interp_accel_free(samp_accel); gsl_spline_free(samp_spline); gsl_interp_accel_free(line_accel); gsl_spline_free(line_spline); put_float_line(ofp, outMeta, ii, out); } fclose(ofp); } // free the last band of the input float_image_free(in); FREE(slant_in); FREE(line_out); FREE(samp_out); for (ii=0; ii<n; ++ii) { gsl_interp_accel_free(samp_accels[ii]); gsl_spline_free(samp_splines[ii]); gsl_interp_accel_free(line_accels[ii]); gsl_spline_free(line_splines[ii]); } FREE(samp_accels); FREE(samp_splines); FREE(line_accels); FREE(line_splines); FREE(out); for (kk=0; kk<inMeta->general->band_count; ++kk) FREE(band_name[kk]); FREE(band_name); // see how bad our errors were avg_error /= (double)count; asfPrintStatus("Model max error: %f, avg: %f\n", max_error, avg_error); double thresh = 0.1; if (max_error > 100*thresh) asfPrintError("Maximum error exceeded threshold: %f > %f\n", max_error, 100*thresh); else if (avg_error > 10*thresh) asfPrintError("Average error exceeded threshold: %f > %f\n", avg_error, 10*thresh); if (max_error > 10*thresh) asfPrintWarning("Maximum error exceeds threshold: %f > %f\n", max_error, 10*thresh); if (avg_error > thresh) asfPrintWarning("Average error exceeds threshold: %f > %f\n", avg_error, thresh); char *meta_file = appendExt(outfile, ".meta"); asfPrintStatus("Writing %s\n", meta_file); meta_write(outMeta, meta_file); free(meta_file); free(img_file); meta_free(outMeta); meta_free(inMeta); return 0; //success }
int fftMatch_opt(char *inFile1, char *inFile2, float *offsetX, float *offsetY) { // Generate temporary directory char tmpDir[1024]; char metaFile[1024], outFile[1024], sarFile[1024], opticalFile[1024]; char *baseName = get_basename(inFile1); strcpy(tmpDir, baseName); strcat(tmpDir, "-"); strcat(tmpDir, time_stamp_dir()); create_clean_dir(tmpDir); // Cutting optical to SAR extent asfPrintStatus("Cutting optical to SAR extent ...\n"); sprintf(metaFile, "%s.meta", inFile1); sprintf(outFile, "%s%c%s_sub.img", tmpDir, DIR_SEPARATOR, inFile2); trim_to(inFile2, outFile, metaFile); // Clipping optical image including blackfill asfPrintStatus("\nClipping optical image including blackfill ...\n"); meta_parameters *metaOpt = meta_read(outFile); meta_parameters *metaSAR = meta_read(metaFile); int line_count = metaSAR->general->line_count; int sample_count = metaSAR->general->sample_count; float *floatLine = (float *) MALLOC(sizeof(float)*sample_count); unsigned char *byteLine = (unsigned char *) MALLOC(sizeof(char)*sample_count); FILE *fpOptical = FOPEN(outFile, "rb"); sprintf(sarFile, "%s.img", inFile1); FILE *fpSAR = FOPEN(sarFile, "rb"); sprintf(outFile, "%s%c%s_mask.img", tmpDir, DIR_SEPARATOR, inFile2); sprintf(metaFile, "%s%c%s_mask.meta", tmpDir, DIR_SEPARATOR, inFile2); FILE *fpOut = FOPEN(outFile, "wb"); int ii, kk; for (ii=0; ii<line_count; ii++) { get_float_line(fpSAR, metaSAR, ii, floatLine); get_byte_line(fpOptical, metaOpt, ii, byteLine); for (kk=0; kk<sample_count; kk++) { if (!FLOAT_EQUIVALENT(floatLine[kk], 0.0)) floatLine[kk] = (float) byteLine[kk]; } put_float_line(fpOut, metaSAR, ii, floatLine); } FCLOSE(fpOptical); FCLOSE(fpSAR); FCLOSE(fpOut); meta_write(metaSAR, metaFile); // Edge filtering optical image asfPrintStatus("\nEdge filtering optical image ...\n"); sprintf(opticalFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile2); kernel_filter(outFile, opticalFile, SOBEL, 3, 0, 0); // Edge filtering SAR image asfPrintStatus("\nEdge filtering SAR image ...\n"); sprintf(sarFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile1); kernel_filter(inFile1, sarFile, SOBEL, 3, 0, 0); // FFT matching on a grid asfPrintStatus("\nFFT matching on a grid ...\n"); fftMatch_proj(sarFile, opticalFile, offsetX, offsetY); // Clean up remove_dir(tmpDir); return (0); }
int fftMatch_projList(char *inFile, char *descFile) { FILE *fp = FOPEN(inFile, "r"); if (!fp) asfPrintError("Failed to open %s\n", inFile); char line[255], master[255]; float x_offs[255], y_offs[255]; int n=0; while (NULL != fgets(line, 255, fp)) { if (line[strlen(line)-1]=='\n') line[strlen(line)-1] = '\0'; if (line[0] == '#' || line[0] == '\0') continue; if (n==0) { strcpy(master, line); } else { fftMatch_proj(master, line, &x_offs[n-1], &y_offs[n-1]); } ++n; if (n>=255) asfPrintError("Too many granules: max 255"); } FCLOSE(fp); FILE *fpd=NULL; if (descFile) { fpd = FOPEN(descFile, "w"); fprintf(fpd, "master,slave,offsetX,offsetY,total offsets\n"); } int num=n-1; n=0; char best[255]; double min_dist; fp = FOPEN(inFile, "r"); while (NULL != fgets(line, 255, fp)) { if (line[strlen(line)-1]=='\n') line[strlen(line)-1] = '\0'; if (line[0] == '#' || line[0] == '\0') continue; if (n==0) { min_dist = distance_to(-1, x_offs, y_offs, num); fprintf(fpd ? fpd : stdout, "%s,%s,%.5f,%.5f,%.5f\n", master, master, 0., 0., min_dist); strcpy(best, master); } else { double d = distance_to(n-1, x_offs, y_offs, num); fprintf(fpd ? fpd : stdout, "%s,%s,%.5f,%.5f,%.5f\n", master, line, x_offs[n-1], y_offs[n-1], d); if (d < min_dist) { min_dist = d; strcpy(best, line); } } ++n; } asfPrintStatus("Best is %s\n", best); if (descFile) { asfPrintStatus("Generated match file (%s)!\n", descFile); FCLOSE(fpd); } FCLOSE(fp); if (strcmp(master, best) == 0) { asfPrintStatus("Reference granule is already the best: %s\n", master); } else { char *new = appendExt(inFile, ".new"); fpd = FOPEN(new, "w"); fprintf(fpd,"%s\n", best); fp = FOPEN(inFile, "r"); while (NULL != fgets(line, 255, fp)) { if (line[strlen(line)-1]=='\n') line[strlen(line)-1] = '\0'; if (line[0] == '#' || line[0] == '\0') continue; if (strcmp(line, best) != 0) { fprintf(fpd,"%s\n", line); } } FCLOSE(fpd); FCLOSE(fp); } return 0; }
void airsar_to_latlon(meta_parameters *meta, double xSample, double yLine, double height, double *lat, double *lon) { if (!meta->airsar) asfPrintError("airsar_to_latlon() called with no airsar block!\n"); const double a = 6378137.0; // semi-major axis const double b = 6356752.3412; // semi-minor axis const double e2 = 0.00669437999014; // ellipticity const double e12 = 0.00673949674228; // second eccentricity // we try to cache the matrices needed for the computation // this makes sure we don't reuse the cache incorrectly (i.e., on // data (=> an airsar block) which doesn't match what we cached for) static meta_airsar *cached_airsar_block = NULL; // these are the cached transformation parameters static matrix *m = NULL; static double ra=-999, o1=-999, o2=-999, o3=-999; if (!m) m = matrix_alloc(3,3); // only needs to be done once // if we aren't calculating with the exact same airsar block, we // need to recalculate the transformation block int recalc = !cached_airsar_block || cached_airsar_block->lat_peg_point != meta->airsar->lat_peg_point || cached_airsar_block->lon_peg_point != meta->airsar->lon_peg_point || cached_airsar_block->head_peg_point != meta->airsar->head_peg_point; if (recalc) { // cache airsar block, so we can be sure we're not reusing // the stored data incorrectly if (cached_airsar_block) free(cached_airsar_block); cached_airsar_block = meta_airsar_init(); *cached_airsar_block = *(meta->airsar); asfPrintStatus("Calculating airsar transformation parameters...\n"); // now precalculate data double lat_peg = meta->airsar->lat_peg_point*D2R; double lon_peg = meta->airsar->lon_peg_point*D2R; double head_peg = meta->airsar->head_peg_point*D2R; double re = a / sqrt(1-e2*sin(lat_peg)*sin(lat_peg)); double rn = (a*(1-e2)) / pow(1-e2*sin(lat_peg)*sin(lat_peg), 1.5); ra = (re*rn) / (re*cos(head_peg)*cos(head_peg)+rn*sin(head_peg)*sin(head_peg)); matrix *m1, *m2; m1 = matrix_alloc(3,3); m2 = matrix_alloc(3,3); m1->coeff[0][0] = -sin(lon_peg); m1->coeff[0][1] = -sin(lat_peg)*cos(lon_peg); m1->coeff[0][2] = cos(lat_peg)*cos(lon_peg); m1->coeff[1][0] = cos(lon_peg); m1->coeff[1][1] = -sin(lat_peg)*sin(lon_peg); m1->coeff[1][2] = cos(lat_peg)*sin(lon_peg); m1->coeff[2][0] = 0.0; m1->coeff[2][1] = cos(lat_peg); m1->coeff[2][2] = sin(lat_peg); m2->coeff[0][0] = 0.0; m2->coeff[0][1] = sin(head_peg); m2->coeff[0][2] = -cos(head_peg); m2->coeff[1][0] = 0.0; m2->coeff[1][1] = cos(head_peg); m2->coeff[1][2] = sin(head_peg); m2->coeff[2][0] = 1.0; m2->coeff[2][1] = 0.0; m2->coeff[2][2] = 0.0; o1 = re*cos(lat_peg)*cos(lon_peg)-ra*cos(lat_peg)*cos(lon_peg); o2 = re*cos(lat_peg)*sin(lon_peg)-ra*cos(lat_peg)*sin(lon_peg); o3 = re*(1-e2)*sin(lat_peg)-ra*sin(lat_peg); matrix_mult(m,m1,m2); matrix_free(m1); matrix_free(m2); } // Make sure we didn't miss anything assert(ra != -999 && o1 != -999 && o2 != -999 && o3 != -999); //------------------------------------------------------------------ // Now the actual computation, using the cached matrix etc // convenience aliases double c0 = meta->airsar->cross_track_offset; double s0 = meta->airsar->along_track_offset; double ypix = meta->general->y_pixel_size; double xpix = meta->general->x_pixel_size; // radar coordinates double c_lat = (xSample*xpix+c0)/ra; double s_lon = (yLine*ypix+s0)/ra; //height += meta->airsar->gps_altitude; // radar coordinates in WGS84 double t1 = (ra+height)*cos(c_lat)*cos(s_lon); double t2 = (ra+height)*cos(c_lat)*sin(s_lon); double t3 = (ra+height)*sin(c_lat); double c1 = m->coeff[0][0]*t1 + m->coeff[0][1]*t2 + m->coeff[0][2]*t3; double c2 = m->coeff[1][0]*t1 + m->coeff[1][1]*t2 + m->coeff[1][2]*t3; double c3 = m->coeff[2][0]*t1 + m->coeff[2][1]*t2 + m->coeff[2][2]*t3; // shift into local Cartesian coordinates double x = c1 + o1;// + 9.0; double y = c2 + o2;// - 161.0; double z = c3 + o3;// - 179.0; // local Cartesian coordinates into geographic coordinates double d = sqrt(x*x+y*y); double theta = atan2(z*a, d*b); *lat = R2D*atan2(z+e12*b*sin(theta)*sin(theta)*sin(theta), d-e2*a*cos(theta)*cos(theta)*cos(theta)); *lon = R2D*atan2(y, x); }
int fftMatch_gridded(char *inFile1, char *inFile2, char *gridFile, float *avgLocX, float *avgLocY, float *certainty, int size, double tol, int overlap) { meta_parameters *meta1 = meta_read(inFile1); meta_parameters *meta2 = meta_read(inFile2); int nl = mini(meta1->general->line_count, meta2->general->line_count); int ns = mini(meta1->general->sample_count, meta2->general->sample_count); if (size<0) size = 512; if (overlap<0) overlap = 256; if (tol<0) tol = .28; asfPrintStatus("Tile size is %dx%d pixels\n", size, size); asfPrintStatus("Tile overlap is %d pixels\n", overlap); asfPrintStatus("Match tolerance is %.2f\n", tol); long long lsz = (long long)size; int num_x = (ns - size) / (size - overlap); int num_y = (nl - size) / (size - overlap); int len = num_x*num_y; asfPrintStatus("Number of tiles is %dx%d\n", num_x, num_y); offset_point_t *matches = MALLOC(sizeof(offset_point_t)*len); int ii, jj, kk=0, nvalid=0; for (ii=0; ii<num_y; ++ii) { int tile_y = ii*(size - overlap); if (tile_y + size > nl) { if (ii != num_y - 1) asfPrintError("Bad tile_y: %d %d %d %d %d\n", ii, num_y, tile_y, size, nl); tile_y = nl - size; } for (jj=0; jj<num_x; ++jj) { int tile_x = jj*(size - overlap); if (tile_x + size > ns) { if (jj != num_x - 1) asfPrintError("Bad tile_x: %d %d %d %d %d\n", jj, num_x, tile_x, size, ns); tile_x = ns - size; } //asfPrintStatus("Matching tile starting at (L,S) (%d,%d)\n", tile_y, tile_x); char trim_append[64]; sprintf(trim_append, "_chip_%05d_%05d", tile_y, tile_x); char *trim_chip1 = appendToBasename(inFile1, trim_append); char *trim_chip2 = appendToBasename(inFile2, trim_append); trim(inFile1, trim_chip1, (long long)tile_x, (long long)tile_y, lsz, lsz); trim(inFile2, trim_chip2, (long long)tile_x, (long long)tile_y, lsz, lsz); //char smooth_append[64]; //sprintf(smooth_append, "_smooth_chip_%05d_%05d", tile_x, tile_y); //char *smooth_chip1 = appendToBasename(inFile1, smooth_append); //smooth(trim_chip1, smooth_chip1, 3, EDGE_TRUNCATE); float dx, dy, cert; int ok = fftMatchBF(trim_chip1, trim_chip2, &dx, &dy, &cert, tol); matches[kk].x_pos = tile_x; matches[kk].y_pos = tile_y; matches[kk].cert = cert; matches[kk].x_offset = dx; matches[kk].y_offset = dy; matches[kk].valid = ok && cert>tol; asfPrintStatus("%s: %5d %5d dx=%7.3f, dy=%7.3f, cert=%5.3f\n", matches[kk].valid?"GOOD":"BAD ", tile_y, tile_x, dx, dy, cert); if (matches[kk].valid) ++nvalid; ++kk; //printf("%4.1f ", dx); removeImgAndMeta(trim_chip1); FREE(trim_chip1); removeImgAndMeta(trim_chip2); FREE(trim_chip2); //unlink(smooth_chip1); //FREE(smooth_chip1); } //printf("\n"); } //print_matches(matches, num_x, num_y, stdout); asfPrintStatus("Removing grid offset outliers.\n"); asfPrintStatus("Starting with %d offsets.\n", nvalid); int removed, iter=0; do { removed = remove_outliers(matches, len); if (removed > 0) asfPrintStatus("Iteration %d: Removed %d outliers\n", ++iter, removed); } while (removed > 0); asfPrintStatus("Finished removing outliers.\n"); if (gridFile) { FILE *offset_fp = FOPEN(gridFile,"w"); print_matches(matches, num_x, num_y, offset_fp); FCLOSE(offset_fp); } char *name = appendExt(inFile1, ".offsets.txt"); FILE *fp = FOPEN(name, "w"); int valid_points = 0; for (ii=0; ii<len; ++ii) { if (matches[ii].valid) { ++valid_points; if (fp) { fprintf(fp, "%5d %5d %14.5f %14.5f %14.5f\n", matches[ii].x_pos, matches[ii].y_pos, matches[ii].x_pos + matches[ii].x_offset, matches[ii].y_pos + matches[ii].y_offset, matches[ii].cert); } } } if (valid_points < 1) { asfPrintStatus("Too few points for a good match.\n"); *avgLocX = 0; *avgLocY = 0; *certainty = 0; } else { *avgLocX = 0; *avgLocY = 0; *certainty = 0; int n = 0; for (ii=0; ii<len; ++ii) { if (matches[ii].valid) { *avgLocX += matches[ii].x_offset; *avgLocY += matches[ii].y_offset; *certainty += matches[ii].cert; ++n; } } *avgLocX /= (float)n; *avgLocY /= (float)n; //*certainty = (float)n / (float)len; *certainty /= (float)n; } asfPrintStatus("Found %d offsets.\n", valid_points); asfPrintStatus("Average tile offset: dx=%f, dy=%f, cert=%f\n", *avgLocX, *avgLocY, *certainty); meta_free(meta1); meta_free(meta2); FCLOSE(fp); asfPrintStatus("Generated grid match file: %s\n", name); FREE(matches); FREE(name); return (0); }
int main(int argc, char **argv) { FILE *fp; meta_parameters *metaSrc, *metaTrg; envi_header *envi; extern int currArg; // Pre-initialized to 1 radiometry_t radiometry=r_AMP; filter_type_t filter_type; char srcImage[255], trgImage[255], *inFile, outFile[255], filter_str[25]; int startX_src, startY_src, startX_trg, startY_trg, lines, samples, size; int subset=FALSE, filter=FALSE, geotiff=FALSE, line_count, sample_count; double lat_UL, lon_UL, lat_LR, lon_LR, yLine, xSample; float mean, scale; register float *img, *filtered_img=NULL; register int x, y, l; /* parse command line */ logflag=quietflag=FALSE; while (currArg < (argc-2)) { char *key = argv[currArg++]; if (strmatch(key,"-startX")) { CHECK_ARG(1); startX_src = atoi(GET_ARG(1)); subset = TRUE; } else if (strmatch(key,"-startY")) { CHECK_ARG(1); startY_src = atoi(GET_ARG(1)); subset = TRUE; } else if (strmatch(key,"-lines")) { CHECK_ARG(1); lines = atoi(GET_ARG(1)); subset = TRUE; } else if (strmatch(key,"-samples")) { CHECK_ARG(1); samples = atoi(GET_ARG(1)); subset = TRUE; } else if (strmatch(key,"-filter")) { CHECK_ARG(2); strcpy(filter_str, GET_ARG(2)); size = atoi(GET_ARG(1)); filter = TRUE; } else if (strmatch(key,"-geotiff")) { geotiff = TRUE; } else { printf( "\n**Invalid option: %s\n", argv[currArg-1]); usage(argv[0]); } } if ((argc-currArg)<2) {printf("Insufficient arguments.\n"); usage(argv[0]);} strcpy (srcImage, argv[currArg]); strcpy (trgImage, argv[currArg+1]); asfSplashScreen(argc, argv); // Ingesting CEOS files into ASF internal format asfPrintStatus("Ingesting source image: %s ...\n", srcImage); asf_import(radiometry, FALSE, FALSE, FALSE, "CEOS", "", "geocoded_image", NULL, NULL, -99.0, -99.0, NULL, NULL, NULL, TRUE, NULL, srcImage, "", srcImage); metaSrc = meta_read(srcImage); asfPrintStatus("Ingesting target image: %s ...\n", trgImage); asf_import(radiometry, FALSE, FALSE, FALSE, "CEOS", "", "geocoded_image", NULL, NULL, -99.0, -99.0, NULL, NULL, NULL, TRUE, NULL, trgImage, "", trgImage); metaTrg = meta_read(trgImage); // Check subset values for source image line_count = metaSrc->general->line_count; sample_count = metaSrc->general->sample_count; if (subset) { if (startX_src < 0 || startX_src > sample_count) startX_src = 0; if (startY_src < 0 || startY_src > line_count) startY_src = 0; if (lines < 0 || (lines-startY_src) > line_count) lines = line_count - startY_src; if (samples < 0 || (samples-startX_src) > sample_count) samples = sample_count - startX_src; } else { startX_src = startY_src = 0; lines = line_count; samples = sample_count; } // Assign filter if (filter) { if (strcmp(uc(filter_str), "AVERAGE") == 0) filter_type = AVERAGE; else if (strcmp(uc(filter_str), "SOBEL") == 0) filter_type = SOBEL; else if (strcmp(uc(filter_str), "FROST") == 0) filter_type = FROST; else if (strcmp(uc(filter_str), "LEE") == 0) filter_type = LEE; else if (strcmp(uc(filter_str), "GAMMA_MAP") == 0) filter_type = GAMMA_MAP; else { asfPrintWarning("Unsupported filter type '%s'- ignoring the filter" " settings\n", filter_str); filter = FALSE; } if (size%2 == 0 && filter_type != AVERAGE) { size--; asfPrintWarning("Filter kernel must have an odd number of lines and" "samples!\n"); } } // Allocate some memory for the subsets line_count = metaTrg->general->line_count; sample_count = metaTrg->general->sample_count; img = (float *) MALLOC(sizeof(float)*lines*samples); if (filter) filtered_img = (float *) MALLOC(sizeof(float)*lines*samples); // Determine geographic location of subset meta_get_latLon(metaSrc, startY_src, startX_src, 0.0, &lat_UL, &lon_UL); meta_get_latLon(metaSrc, startY_src+lines, startX_src+samples, 0.0, &lat_LR, &lon_LR); meta_get_lineSamp(metaTrg, lat_UL, lon_UL, 0.0, &yLine, &xSample); startX_trg = (int) (xSample + 0.5); startY_trg = (int) (yLine + 0.5); // READ IN SUBSETS // Read target image subset first to determine average brightness asfPrintStatus("\nGenerating subset for target image ...\n"); asfPrintStatus("start line: %d, start sample: %d, lines: %d, samples: %d\n", startY_trg, startX_trg, lines, samples); inFile = appendExt(trgImage, ".img"); sprintf(outFile, "%s_sub.img", trgImage); fp = FOPEN(inFile, "rb"); read_subset(fp, metaTrg, startX_trg, startY_trg, samples, lines, 0.0, &mean, img); FCLOSE(fp); // Compute scale factor mean *= -1; scale = 1.0 / (lines * samples); // Subtract this average off of target image for (y=0; y<lines; y++) { l = samples * y; for (x=0; x<samples; x++) img[l+x] = (img[l+x] + mean) * scale; } if (filter) { asfPrintStatus("\nFiltering target image subset with %s (%dx%d) ...\n", uc(filter_str), size, size); filter_image(img, filtered_img, filter_type, size, lines, samples); } // Update metadata and write target subset to file metaTrg->general->line_count = lines; metaTrg->general->sample_count = samples; metaTrg->general->start_line = startY_trg; metaTrg->general->start_sample = startX_trg; meta_write(metaTrg, outFile); envi = meta2envi(metaTrg); write_envi_header(outFile, outFile, metaTrg, envi); fp = FOPEN(outFile, "wb"); if (filter) put_float_lines(fp, metaTrg, 0, lines, filtered_img); else put_float_lines(fp, metaTrg, 0, lines, img); FCLOSE(fp); // Read source image subset applying for brightness asfPrintStatus("\nGenerating subset for source image ...\n"); asfPrintStatus("start line: %d, start sample: %d, lines: %d, samples: %d\n", startY_src, startX_src, lines, samples); inFile = appendExt(srcImage, ".img"); sprintf(outFile, "%s_sub.img", srcImage); fp = FOPEN(inFile, "rb"); read_subset(fp, metaSrc, startX_src, startY_src, samples, lines, mean, NULL, img); FCLOSE(fp); if (filter) { asfPrintStatus("\nFiltering source image subset with %s (%dx%d) ...\n", uc(filter_str), size, size); filter_image(img, filtered_img, filter_type, size, lines, samples); } // Update metadata and write source subset to file metaSrc->general->line_count = lines; metaSrc->general->sample_count = samples; metaSrc->general->start_line = startY_src; metaSrc->general->start_sample = startX_src; meta_write(metaSrc, outFile); envi = meta2envi(metaSrc); write_envi_header(outFile, outFile, metaSrc, envi); fp = FOPEN(outFile, "wb"); if (filter) put_float_lines(fp, metaSrc, 0, lines, filtered_img); else put_float_lines(fp, metaSrc, 0, lines, img); FCLOSE(fp); // Clean up FREE(img); meta_free(metaSrc); meta_free(metaTrg); // Exporting subsets to GeoTIFF if (geotiff) { output_format_t output_format=GEOTIFF; scale_t sample_mapping=SIGMA; asfPrintStatus("\nExporting source image subset to GeoTIFF ...\n"); sprintf(outFile, "%s_sub", srcImage); asf_export(output_format, sample_mapping, outFile, outFile); asfPrintStatus("\nExporting target image subset to GeoTIFF ...\n"); sprintf(outFile, "%s_sub", trgImage); asf_export(output_format, sample_mapping, outFile, outFile); } return (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<2) 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; int no_blackfill = extract_flag_options(&argc, &argv, "-no_blackfill", "--no_blackfill", NULL); 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, no_blackfill); 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 = (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; }
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); }
int main(int argc, char *argv[]) { dem_config *cfg=NULL; int createFlag = FLAG_NOT_SET; char configFile[255]; // Check for all those little helper options if ( (checkForOption("--help", argc, argv) != FLAG_NOT_SET) || (checkForOption("-h", argc, argv) != FLAG_NOT_SET) || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) { print_help(); } handle_license_and_version_args(argc, argv, ASF_NAME_STRING); // Check which options were provided createFlag = checkForOption("-create", argc, argv); // We need to make sure the user specified the proper number of arguments int needed_args = 1 + REQUIRED_ARGS; // command & REQUIRED_ARGS if (createFlag != FLAG_NOT_SET) needed_args += 1; // option // Make sure we have the right number of args if(argc != needed_args) { print_usage(); } if (createFlag != FLAG_NOT_SET) createFlag = 1; else createFlag = 0; // Fetch required arguments strcpy(configFile, argv[argc-1]); // Report the command line asfSplashScreen(argc, argv); // If requested, create a config file and exit (if the file does not exist), // otherwise read it if ( createFlag==TRUE && !fileExists(configFile) ) { init_config(configFile); exit(EXIT_SUCCESS); } // Extend the configuration file if the file already exist else if ( createFlag==TRUE && fileExists(configFile) ) { cfg = read_config(configFile, createFlag); // Assign names for results to be kept sprintf(cfg->igram_coh->igram, "%s_igram", cfg->general->base); sprintf(cfg->igram_coh->coh, "%s_coh.img", cfg->general->base); sprintf(cfg->coreg->master_power, "%s_a_pwr.img", cfg->general->base); sprintf(cfg->coreg->slave_power, "%s_b_pwr.img", cfg->general->base); sprintf(cfg->refine->seeds, "%s.seeds", cfg->general->base); sprintf(cfg->dinsar->igram, "%s_digram.img", cfg->general->base); sprintf(cfg->unwrap->qc, "%s_qc_phase.img", cfg->general->base); sprintf(cfg->elevation->dem, "%s_ht.img", cfg->general->base); sprintf(cfg->elevation->error, "%s_err_ht.img", cfg->general->base); sprintf(cfg->geocode->dem, "%s_dem", cfg->general->base); sprintf(cfg->geocode->amp, "%s_amp", cfg->general->base); sprintf(cfg->geocode->error, "%s_error", cfg->general->base); sprintf(cfg->geocode->coh, "%s_coh", cfg->general->base); asfRequire( 0==write_config(configFile, cfg), "Could not update configuration file"); asfPrintStatus(" Initialized complete configuration file\n\n"); exit(EXIT_SUCCESS); } else if (!fileExists(configFile)) asfPrintError("Configuration file does not exist!\n"); else { cfg = read_config(configFile, createFlag); } /* Setup log file */ sprintf(logFile, "%s.log", cfg->general->base); if (strncmp(cfg->general->status, "new", 3)==0) fLog = FOPEN(logFile, "w"); else fLog = FOPEN(logFile, "a"); if (argc == 3) { sprintf(logbuf, "\nCommand line: ips -c %s\n", configFile); printLog(logbuf); } else { sprintf(logbuf, "\nCommand line: ips %s\n", configFile); printLog(logbuf); } sprintf(logbuf, "Program: ips\n\n"); printLog(logbuf); FCLOSE(fLog); return ips(cfg, configFile, createFlag); }
int fftMatch(char *inFile1, char *inFile2, char *corrFile, float *bestLocX, float *bestLocY, float *certainty) { int nl,ns; int mX,mY; /*Invariant: 2^mX=ns; 2^mY=nl.*/ int chipX, chipY; /*Chip location (top left corner) in second image*/ int chipDX,chipDY; /*Chip size in second image.*/ int searchX,searchY; /*Maximum distance to search for peak*/ int x,y; float doubt; float *corrImage=NULL; FILE *corrF=NULL,*in1F,*in2F; meta_parameters *metaMaster, *metaSlave, *metaOut; in1F = fopenImage(inFile1,"rb"); in2F = fopenImage(inFile2,"rb"); metaMaster = meta_read(inFile1); metaSlave = meta_read(inFile2); /*Round to find nearest power of 2 for FFT size.*/ mX = (int)(log((float)(metaMaster->general->sample_count))/log(2.0)+0.5); mY = (int)(log((float)(metaMaster->general->line_count))/log(2.0)+0.5); /* Keep size of fft's reasonable */ if (mX > 13) mX = 13; if (mY > 15) mY = 15; ns = 1<<mX; nl = 1<<mY; /* Test chip size to see if we have enough memory for it */ /* Reduce it if necessary, but not below 1024x1024 (which needs 4 Mb of memory) */ float *test_mem = (float *)malloc(sizeof(float)*ns*nl*2); if (!test_mem && !quietflag) asfPrintStatus("\n"); while (!test_mem) { mX--; mY--; ns = 1<<mX; nl = 1<<mY; if (ns < 1024 || nl < 1024) { asfPrintError("FFT Size too small (%dx%d)...\n", ns, nl); } if (!quietflag) asfPrintStatus(" Not enough memory... reducing FFT Size to %dx%d\n", ns, nl); test_mem = (float *)malloc(sizeof(float)*ns*nl*2); } FREE(test_mem); if (!quietflag) asfPrintStatus("\n"); /*Set up search chip size.*/ chipDX=MINI(metaSlave->general->sample_count,ns)*3/4; chipDY=MINI(metaSlave->general->line_count,nl)*3/4; chipX=MINI(metaSlave->general->sample_count,ns)/8; chipY=MINI(metaSlave->general->line_count,nl)/8; searchX=MINI(metaSlave->general->sample_count,ns)*3/8; searchY=MINI(metaSlave->general->line_count,nl)*3/8; fft2dInit(mY, mX); if (!quietflag && ns*nl*2*sizeof(float)>20*1024*1024) { asfPrintStatus( " These images will take %d megabytes of memory to match.\n\n", ns*nl*2*sizeof(float)/(1024*1024)); } /*Optionally open the correlation image file.*/ if (corrFile) { metaOut = meta_read(inFile1); metaOut->general->data_type= REAL32; metaOut->general->line_count = 2*searchY; metaOut->general->sample_count = 2*searchX; corrF=fopenImage(corrFile,"w"); } /*Perform the correlation.*/ fftProd(in1F,metaMaster,in2F,metaSlave,&corrImage,ns,nl,mX,mY, chipX,chipY,chipDX,chipDY,searchX,searchY); /*Optionally write out correlation image.*/ if (corrFile) { int outY=0; float *outBuf=(float*)MALLOC(sizeof(float)*metaOut->general->sample_count); for (y=chipY-searchY;y<chipY+searchY;y++) { int index=ns*modY(y,nl); int outX=0; for (x=chipX-searchX;x<chipX+searchX;x++) { outBuf[outX++]=corrImage[index+modX(x,ns)]; } put_float_line(corrF,metaOut,outY++,outBuf); } meta_write(metaOut, corrFile); meta_free(metaOut); FREE(outBuf); FCLOSE(corrF); } /*Search correlation image for a peak.*/ findPeak(corrImage,bestLocX,bestLocY,&doubt,nl,ns, chipX,chipY,searchX,searchY); *certainty = 1-doubt; FREE(corrImage); if (!quietflag) { asfPrintStatus(" Offset slave image: dx = %f, dy = %f\n" " Certainty: %f%%\n",*bestLocX,*bestLocY,100*(1-doubt)); } meta_free(metaSlave); meta_free(metaMaster); FCLOSE(in1F); FCLOSE(in2F); return (0); }
static void determine_extents(char **infiles, int n_inputs, int *size_x, int *size_y, double *start_x, double *start_y, double *per_x, double *per_y) { // the first input file is the "reference" -- all other metadata // must match the first (at least as far as projection, etc) meta_parameters *meta0 = meta_read(infiles[0]); if (!meta0) { asfPrintError("Couldn't read metadata for %s!\n", infiles[0]); } if (!meta0->projection) { asfPrintError("%s is not geocoded!\n", infiles[0]); } asfPrintStatus("Reference image is: %s\nGeocoding:\n", infiles[0]); print_proj_info(meta0); // these values must be matched by all images double px, py; px = *per_x = meta0->projection->perX; py = *per_y = meta0->projection->perY; // these don't have to be matched, we will update as we go along double x0, y0, xL, yL; get_corners(meta0, &x0, &y0, &xL, &yL); projection_type_t proj_type = meta0->projection->type; int i, n_ok = 1, n_bad = 0; for (i=1; i<n_inputs; ++i) { char *file = infiles[i]; //asfPrintStatus(" Processing metadata for %s...\n", file); meta_parameters *meta = meta_read(file); char *why=""; if (!meta) why = "Couldn't read metadata"; else if (!meta->projection) why = "Image is not geocoded"; else if (meta->projection->perX != px) why = "X pixel size doesn't match reference image"; else if (meta->projection->perY != py) why = "Y pixel size doesn't match reference image"; else if (meta->projection->type != proj_type) why = "Image is in a different projection"; else if (!proj_parms_match(meta0, meta)) why = "Projection parameters differ"; if (strlen(why) > 0) { ++n_bad; asfPrintStatus("Image '%s': NOT OK (%s)\n", file, why); infiles[i] = NULL; // mark for future ignore-ation } else { ++n_ok; asfPrintStatus("Image '%s': ok (%dx%d LxS)\n", file, meta->general->line_count, meta->general->sample_count); double this_x0, this_y0, this_xL, this_yL; get_corners(meta, &this_x0, &this_y0, &this_xL, &this_yL); update_corners(px, py, &x0, &y0, &xL, &yL, this_x0, this_y0, this_xL, this_yL); } meta_free(meta); } if (n_ok < 2) { asfPrintError("Not enough images to mosaic.\n"); } *start_x = x0; *start_y = y0; // calculate number of lines/samples from corner to corner *size_x = (int) ((xL-x0)/px + .5); *size_y = (int) ((yL-y0)/py + .5); meta_free(meta0); }
// Functions to inform the user about the program void usage(void) { quietflag=0; asfPrintStatus(ASF_USAGE_STRING); exit(EXIT_FAILURE); }
// Main program body. int main (int argc, char *argv[]) { char *inFile, *demFile, *inMaskFile, *outFile; double pixel_size = -1; int dem_grid_size = 20; int currArg = 1; int clean_files = TRUE; int do_resample = TRUE; int do_interp = TRUE; int do_fftMatch_verification = TRUE; int do_corner_matching = FALSE; int generate_water_mask = FALSE; int save_clipped_dem = FALSE; int doRadiometric = FALSE; int update_original_metadata_with_offsets = FALSE; float mask_height_cutoff = 1.0; int mask_height_cutoff_specified = FALSE; int smooth_dem_holes = FALSE; int no_matching = FALSE; int use_gr_dem = FALSE; int add_speckle = TRUE; int if_coreg_fails_use_zero_offsets = FALSE; int save_ground_dem = FALSE; int save_incid_angles = FALSE; double range_offset = 0.0; double azimuth_offset = 0.0; char *other_files[MAX_OTHER]; int i,n_other = 0; for (i=0; i<MAX_OTHER; ++i) other_files[i]=NULL; // -1 -> no masking, other values mean fill it with that value int fill_value = 0; handle_common_asf_args(&argc, &argv, ASF_NAME_STRING); asfSplashScreen(argc, argv); inMaskFile = NULL; if (argc<=1) usage(ASF_NAME_STRING); else if (strmatches(argv[1],"-help","--help",NULL)) print_help(); while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key,"-keep","--keep","-k",NULL)) { clean_files = FALSE; } else if (strmatches(key,"-no-resample","--no-resample",NULL)) { do_resample = FALSE; } else if (strmatches(key,"-no-verify-match","--no-verify-match",NULL)) { do_fftMatch_verification = FALSE; } else if (strmatches(key,"-no-corner-match","--no-corner-match",NULL)) { do_corner_matching = FALSE; } else if (strmatches(key,"-no-interp","--no-interp",NULL)) { do_interp = FALSE; } else if (strmatches(key,"-no-match","--no-match",NULL)) { no_matching = TRUE; } else if (strmatches(key,"-use-gr-dem", "--use-gr-dem",NULL)) { use_gr_dem = TRUE; } else if (strmatches(key,"-use-sr-dem", "--use-sr-dem",NULL)) { use_gr_dem = FALSE; } else if (strmatches(key,"-no-speckle", "--no-speckle",NULL)) { add_speckle = FALSE; } else if (strmatches(key,"-use-zero-offsets-if-match-fails", "--use-zero-offsets-if-match-fails",NULL)) { if_coreg_fails_use_zero_offsets = TRUE; } else if (strmatches(key,"-pixel-size","--pixel-size","-ps",NULL)) { CHECK_ARG(1); pixel_size = atof(GET_ARG(1)); } else if (strmatches(key,"-dem-grid-size","--dem-grid-size",NULL)) { CHECK_ARG(1); dem_grid_size = atoi(GET_ARG(1)); } else if (strmatches(key,"-mask-file","--mask-file",NULL)) { CHECK_ARG(1); inMaskFile = GET_ARG(1); } else if (strmatches(key,"-auto-water-mask","--auto-water-mask",NULL)) { generate_water_mask = TRUE; } else if (strmatches(key,"-mask-height-cutoff","--mask-height-cutoff",NULL)) { CHECK_ARG(1); mask_height_cutoff = atof(GET_ARG(1)); mask_height_cutoff_specified = TRUE; } else if (strmatches(key, "-u", "-update-original-meta", "--update-original-meta", NULL)) { update_original_metadata_with_offsets = TRUE; } else if (strmatches(key,"-fill","--fill",NULL)) { CHECK_ARG(1); fill_value = atoi(GET_ARG(1)); // user requested a specific fill value } else if (strmatches(key,"-offsets","--offsets",NULL)) { CHECK_ARG(2); range_offset = atof(GET_ARG(2)); azimuth_offset = atof(GET_ARG(1)); no_matching = TRUE; } else if (strmatches(key,"-no-fill","--no-fill",NULL)) { // leave masked regions alone - fill with sar data fill_value = LEAVE_MASK; } else if (strmatches(key,"-do-radiometric","--do-radiometric",NULL)) { // for the 3.1 release, we will always do formula #5 // it's the only one we've had time to test. In later releases, // we can switch to the other version ... this does mean // that -do-radiometric will change from a flag to an option with // an argument. #ifndef ALLOW_ALL_RADIOMETRIC_TC_FORMULAS doRadiometric = 5; #else CHECK_ARG(1); char *form = strdup(GET_ARG(1)); doRadiometric = atoi(form); // give the do-radiometric help in here for now, later should be // put into the rest of the help (when it is officially supported) if (strmatches(form, "help", "?", NULL) || doRadiometric==0) { asfPrintStatus( "Specify a radiometric terrain correction formula to use.\n" "Formula numbers are as follows:\n" " 1 : LI\n" " 2 : GO\n" " 3 : SQ\n" " 4 : VX\n" " 5 : 1 - .7*pow(cos(li), 7)\n" "\n" "e.g.,\n" " asf_terrcorr -do-radiometric 1 ...\n\n"); exit(1); } free(form); #endif } else if (strmatches(key,"-smooth-dem-holes","--smooth-dem-holes",NULL)) { smooth_dem_holes = TRUE; } else if (strmatches(key,"-save-ground-range-dem","--save-ground-range-dem", NULL)) { save_ground_dem = TRUE; } else if (strmatches(key,"-save-incidence-angles","--save_incidence-angles",NULL)) { save_incid_angles = TRUE; } else if (strmatches(key,"-help","--help",NULL)) { print_help(); // doesn't return } else if (strmatches(key,"-other-file","--other-file",NULL)) { CHECK_ARG(1); if (n_other >= MAX_OTHER) asfPrintError("-other-file option only supported %d times.\n", MAX_OTHER); other_files[n_other++] = STRDUP(GET_ARG(1)); } else { printf( "\n**Invalid option: %s\n", argv[currArg-1]); usage(ASF_NAME_STRING); } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments.\n"); usage(ASF_NAME_STRING); } if (mask_height_cutoff_specified && !generate_water_mask) { asfPrintWarning("Ignoring -mask-height-cutoff option, as you did not " "request a water mask.\n"); } inFile = argv[currArg]; demFile = argv[currArg+1]; outFile = argv[currArg+2]; int ret = asf_terrcorr_ext(inFile, demFile,inMaskFile,outFile, pixel_size, clean_files, do_resample, do_corner_matching, do_interp, do_fftMatch_verification, dem_grid_size, TRUE, fill_value, generate_water_mask, save_clipped_dem, update_original_metadata_with_offsets, mask_height_cutoff, doRadiometric, smooth_dem_holes, other_files, no_matching, range_offset, azimuth_offset, use_gr_dem, add_speckle, if_coreg_fails_use_zero_offsets, save_ground_dem, save_incid_angles); for (i=0; i<MAX_OTHER; ++i) if (other_files[i]) free(other_files[i]); return ret==0 ? EXIT_SUCCESS : EXIT_FAILURE; }
void help(void) { quietflag=0; asfPrintStatus(ASF_HELP_STRING); exit(EXIT_FAILURE); }
void c2p_ext(const char *inDataName, const char *inMetaName, const char *outfile, int multilook, int banded) { meta_parameters *in_meta = meta_read(inMetaName); int data_type = in_meta->general->data_type; // the old code did this, but why?? in_meta->general->data_type = meta_polar2complex(data_type); // some sanity checks switch (data_type) { case COMPLEX_BYTE: case COMPLEX_INTEGER16: case COMPLEX_INTEGER32: case COMPLEX_REAL32: case COMPLEX_REAL64: break; default: asfPrintError("c2p: %s is not a complex image.\n", inDataName); } if (in_meta->general->band_count != 1) asfPrintError("c2p: %s is not a single-band image.\n", inDataName); if (!in_meta->sar) asfPrintError("c2p: %s is missing a SAR block.\n", inDataName); asfPrintStatus("Converting complex image to amplitude/phase...\n"); int nl = in_meta->general->line_count; int ns = in_meta->general->sample_count; // process 1 line at a time when not multilooking, otherwise grab nlooks int nlooks = multilook ? in_meta->sar->look_count : 1; if (nlooks == 1 && multilook) { asfPrintStatus("Not multilooking, look_count is 1.\n"); multilook = FALSE; } if (multilook) asfPrintStatus("Multilooking with %d looks.\n", nlooks); meta_parameters *out_meta = meta_read(inMetaName); out_meta->general->data_type = meta_complex2polar(data_type); // set up input/output files FILE *fin = fopenImage(inDataName, "rb"); // we either have 1 or 2 output files, per the "banded" flag. char *outfile_img = appendExt(outfile, ".img"); char *amp_name=NULL, *phase_name=NULL; FILE *fout_banded=NULL, *fout_amp=NULL, *fout_phase=NULL; if (banded) { asfPrintStatus("Output is 2-band image: %s\n", outfile_img); fout_banded = fopenImage(outfile_img, "wb"); } else { amp_name = appendToBasename(outfile_img, "_amp"); phase_name = appendToBasename(outfile_img, "_phase"); asfPrintStatus("Output amplitude file: %s\n", amp_name); asfPrintStatus("Output phase file: %s\n", phase_name); fout_amp = fopenImage(amp_name, "wb"); fout_phase = fopenImage(phase_name, "wb"); } if (banded) assert(fout_banded && !fout_amp && !fout_phase); else assert(!fout_banded && fout_amp && fout_phase); // get the metadata band_count correct, needed in the put_* calls if (banded) { out_meta->general->band_count = 2; strcpy(out_meta->general->bands, "AMP,PHASE"); } // input buffer complexFloat *cpx = MALLOC(sizeof(complexFloat)*ns*nlooks); // output buffers float *amp = MALLOC(sizeof(float)*ns*nlooks); float *phase = MALLOC(sizeof(float)*ns*nlooks); int line_in; // line in the input image int line_out=0; // line in the output image int samp; // sample #, loop index int l; // line loop index, iterates over the lines in the block out_meta->general->line_count = (int)ceil((double)nl/(double)nlooks); for (line_in=0; line_in<nl; line_in+=nlooks) { // lc = "line count" -- how many lines to read. normally we will read // nlooks lines, but near eof we might have to read fewer int lc = nlooks; if (line_in + lc > nl) lc = nl - line_in; // read "nlooks" (or possibly fewer, if near eof) lines of data int blockSize = get_complexFloat_lines(fin,in_meta,line_in,lc,cpx); if (blockSize != lc*ns) asfPrintError("bad blockSize: bs=%d nlooks=%d ns=%d\n", blockSize, nlooks, ns); // first, compute the power/phase for (l=0; l<lc; ++l) { for (samp=0; samp<ns; ++samp) { int k = l*ns + samp; // index into the block float re = cpx[k].real; float im = cpx[k].imag; if (re != 0.0 || im != 0.0) { amp[k] = re*re + im*im; phase[k] = atan2(im, re); } else { amp[k] = phase[k] = 0.0; } } } // now multilook, if requested if (multilook) { // put the multilooked data in the first "row" of amp,phase for (samp=0; samp<ns; ++samp) { float value = 0.0; for (l=0; l<lc; ++l) value += amp[l*ns + samp]; amp[samp] = sqrt(value/(float)lc); value = 0.0; for (l=0; l<lc; ++l) value += phase[l*ns + samp]; phase[samp] = value/(float)lc; } } else { for (samp=0; samp<ns*lc; ++samp) amp[samp] = sqrt(amp[samp]); } // write out a line (multilooked) or a bunch of lines (not multi) if (multilook) { if (banded) { put_band_float_line(fout_banded, out_meta, 0, line_out, amp); put_band_float_line(fout_banded, out_meta, 1, line_out, phase); } else { put_float_line(fout_amp, out_meta, line_out, amp); put_float_line(fout_phase, out_meta, line_out, phase); } ++line_out; } else { for (l=0; l<lc; ++l) { if (banded) { put_band_float_line(fout_banded, out_meta, 0, line_in+l, amp); put_band_float_line(fout_banded, out_meta, 1, line_in+l, phase); } else { put_float_line(fout_amp, out_meta, line_in+l, amp); put_float_line(fout_phase, out_meta, line_in+l, phase); } ++line_out; } } asfPercentMeter((float)line_in/(float)(nl)); } asfPercentMeter(1.0); fclose(fin); if (fout_banded) fclose(fout_banded); if (fout_amp) fclose(fout_amp); if (fout_phase) fclose(fout_phase); if (multilook) { if (out_meta->general->line_count != line_out) asfPrintError("Line counts don't match: %d != %d\n", out_meta->general->line_count, line_out); out_meta->general->y_pixel_size *= nlooks; out_meta->sar->azimuth_time_per_pixel *= nlooks; out_meta->sar->multilook = TRUE; } else assert(line_out == nl); // write out the metadata, different whether multi-banded or not if (banded) { assert(!amp_name && !phase_name); meta_write(out_meta, outfile); } else { assert(amp_name && phase_name); out_meta->general->image_data_type = AMPLITUDE_IMAGE; meta_write(out_meta, amp_name); out_meta->general->image_data_type = PHASE_IMAGE; meta_write(out_meta, phase_name); } if (multilook) asfPrintStatus("Original line count: %d, after multilooking: %d " "(%d looks)\n", nl, line_out, nlooks); meta_free(in_meta); meta_free(out_meta); FREE(amp); FREE(phase); FREE(cpx); FREE(outfile_img); FREE(amp_name); FREE(phase_name); }
// The program itself! int main (int argc, char **argv) { struct stat stat_buf; size_t wordsize=0; size_t bytesread=0; size_t byteswritten=0; size_t nitems=0; size_t ret=0; int done=FALSE; char *in_fname=NULL; char *out_fname=NULL; FILE *in_fp=NULL; FILE *out_fp=NULL; void *buf=NULL; void (*byteswap)(unsigned char *); // Search the command line for help & report if requested if (extract_flag_options(&argc, &argv, "-h", "-help", "--help", NULL)) { help(); } // Grab the common asf options (eg -version, -quiet, etc) handle_common_asf_args(&argc, &argv, ASF_NAME_STRING); // Since handle_common_asf_args reduces argc for all the options // we can check argc to see if we've got 3 arguments & the progname if (argc != 4) { usage(); } /* // Make sure data types are of the size we expect asfRequire( sizeof(short) == SHORT_INT_SIZE, "Short integers need to be %d bytes (%d-bits)," " they appear to be %d bytes.\n", SHORT_INT_SIZE, SHORT_INT_SIZE*8, sizeof(short)); asfRequire( sizeof(int) == INT_SIZE, "Regular integers need to be %d bytes (%d-bits)," " they appear to be %d bytes.\n", INT_SIZE, INT_SIZE*8, sizeof(int)); asfRequire( sizeof(long long) == LL_INT_SIZE, "Long long integers need to be %d bytes (%d-bits)," " they appear to be %d bytes.\n", LL_INT_SIZE, LL_INT_SIZE*8, sizeof(long long)); asfRequire( sizeof(long long) == FLOAT_SIZE, "Floats need to be %d bytes (%d-bits)," " they appear to be %d bytes.\n", FLOAT_SIZE, FLOAT_SIZE*8, sizeof(long long)); asfRequire( sizeof(long long) == DOUBLE_SIZE, "Doubles need to be %d bytes (%d-bits)," " they appear to be %d bytes.\n", DOUBLE_SIZE, DOUBLE_SIZE*8, sizeof(long long)); */ // Fetch our required arguments wordsize = atoi(argv[1]); if ( ! (wordsize==16 || wordsize==32 || wordsize==64) ) { asfPrintError("Wordsize must be 16, 32, or 64 bits, you gave " "%d... Exiting.\n", wordsize); } wordsize /= 8; // change wordsize from bits to bytes in_fname = (char*)CALLOC(strlen(argv[2])+3,sizeof(char)); strcpy(in_fname,argv[2]); out_fname = (char*)CALLOC(strlen(argv[3])+3,sizeof(char)); strcpy(out_fname,argv[3]); // Set the byteswap function for the proper number of bytes switch (wordsize) { case 2: byteswap = (void(*)(unsigned char*))swap16; break; case 4: byteswap = (void(*)(unsigned char*))swap32; break; case 8: byteswap = (void(*)(unsigned char*))swap64; break; default: asfPrintError("Unrecognized wordsize %d\n",wordsize*8); } // Open the needed files in_fp = FOPEN(in_fname,"rb"); out_fp = FOPEN(out_fname,"wb"); // Prepare for the byteswapping loop bytesread = byteswritten = ret = 0; nitems = MEGABYTE / wordsize; buf = CALLOC(MEGABYTE,sizeof(char)); done = FALSE; // Actual byteswapping routine asfPrintStatus("Swapping bytes (each '.' represents one megabyte)\n"); while (!done) { int ii; if (nitems != (ret=fread(buf, wordsize, nitems, in_fp))) { if (feof(in_fp)) { done=TRUE; } } bytesread += ret*wordsize; for (ii=0; ii<nitems; ii++) { byteswap((unsigned char *)(buf+ii*wordsize)); } ret = fwrite(buf, wordsize, ret, out_fp); byteswritten += ret*wordsize; asfPrintStatus("."); } // Make sure things look right before quitting stat(in_fname, &stat_buf); asfRequire((long long)bytesread==(long long)stat_buf.st_size, "(%lld==%lld)\n" "Problem likely occurred during file reading.\n", (long long)bytesread, (long long)stat_buf.st_size); asfRequire((long long)bytesread==(long long)byteswritten, "(%lld==%lld)\n" "Problem likely occurred during file writing.\n", (long long)bytesread, (long long)byteswritten); asfPrintStatus("\n" " Successfully wrote file '%s'\n" " in reverse endian order than '%s'.\n", out_fname, in_fname); // Yay, success! exit(EXIT_SUCCESS); }
// Main program body. int main (int argc, char *argv[]) { output_format_t format = 0; meta_parameters *md; char *in_base_name, *output_name; char **band_names=NULL; int rgb=0; int true_color; int false_color; int num_bands_found; int ignored[3] = {0, 0, 0}; int num_ignored = 0; in_base_name = (char *) MALLOC(sizeof(char)*255); output_name = (char *) MALLOC(sizeof(char)*255); /**********************BEGIN COMMAND LINE PARSING STUFF**********************/ // Command line input goes in it's own structure. command_line_parameters_t command_line; strcpy (command_line.format, ""); command_line.size = NO_MAXIMUM_OUTPUT_SIZE; strcpy (command_line.in_data_name, ""); strcpy (command_line.in_meta_name, ""); strcpy (command_line.output_name, ""); command_line.verbose = FALSE; command_line.quiet = FALSE; strcpy (command_line.leader_name, ""); strcpy (command_line.cal_params_file, ""); strcpy (command_line.cal_comment, ""); command_line.sample_mapping = 0; strcpy(command_line.red_channel, ""); strcpy(command_line.green_channel, ""); strcpy(command_line.blue_channel, ""); strcpy(command_line.band, ""); strcpy(command_line.look_up_table_name, ""); int formatFlag, logFlag, quietFlag, byteFlag, rgbFlag, bandFlag, lutFlag; int truecolorFlag, falsecolorFlag; int needed_args = 3; //command & argument & argument int ii; char sample_mapping_string[25]; //Check to see which options were specified if ( (checkForOption("--help", argc, argv) != FLAG_NOT_SET) || (checkForOption("-h", argc, argv) != FLAG_NOT_SET) || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) { print_help(); } get_asf_share_dir_with_argv0(argv[0]); handle_license_and_version_args(argc, argv, ASF_NAME_STRING); formatFlag = checkForOption ("-format", argc, argv); logFlag = checkForOption ("-log", argc, argv); quietFlag = checkForOption ("-quiet", argc, argv); byteFlag = checkForOption ("-byte", argc, argv); rgbFlag = checkForOption ("-rgb", argc, argv); bandFlag = checkForOption ("-band", argc, argv); lutFlag = checkForOption ("-lut", argc, argv); truecolorFlag = checkForOption("-truecolor", argc, argv); falsecolorFlag = checkForOption("-falsecolor", argc, argv); if ( formatFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( quietFlag != FLAG_NOT_SET ) { needed_args += 1; // Option & parameter. } if ( logFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( byteFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( rgbFlag != FLAG_NOT_SET ) { needed_args += 4; // Option & 3 parameters. } if ( bandFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( lutFlag != FLAG_NOT_SET ) { needed_args += 2; // Option & parameter. } if ( truecolorFlag != FLAG_NOT_SET ) { needed_args += 1; // Option only } if ( falsecolorFlag != FLAG_NOT_SET ) { needed_args += 1; // Option only } if ( argc != needed_args ) { print_usage (); // This exits with a failure. } // We also need to make sure the last three options are close to // what we expect. if ( argv[argc - 1][0] == '-' || argv[argc - 2][0] == '-' ) { print_usage (); // This exits with a failure. } // Make sure any options that have parameters are followed by // parameters (and not other options) Also make sure options' // parameters don't bleed into required arguments. if ( formatFlag != FLAG_NOT_SET ) { if ( argv[formatFlag + 1][0] == '-' || formatFlag >= argc - 3 ) { print_usage (); } } if ( byteFlag != FLAG_NOT_SET ) { if ( argv[byteFlag + 1][0] == '-' || byteFlag >= argc - 3 ) { print_usage (); } } if ( rgbFlag != FLAG_NOT_SET ) { if (( argv[rgbFlag + 1][0] == '-' && argv[rgbFlag + 2][0] == '-' && argv[rgbFlag + 3][0] == '-' ) || rgbFlag >= argc - 5 ) { print_usage (); } } if ( bandFlag != FLAG_NOT_SET ) { if ( argv[bandFlag + 1][0] == '-' || bandFlag >= argc - 3 ) { print_usage (); } } if ( lutFlag != FLAG_NOT_SET ) { if ( argv[lutFlag + 1][0] == '-' || lutFlag >= argc - 3 ) { print_usage (); } } if ( logFlag != FLAG_NOT_SET ) { if ( argv[logFlag + 1][0] == '-' || logFlag >= argc - 3 ) { print_usage (); } } // Make sure there are no flag incompatibilities if ( (rgbFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (bandFlag != FLAG_NOT_SET && (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (truecolorFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || rgbFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET)) || (falsecolorFlag != FLAG_NOT_SET && (bandFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || rgbFlag != FLAG_NOT_SET)) ) { asfPrintWarning("The following options may only be used one at a time:\n" " %s\n %s\n %s\n %s\n %s\n %s\n", "-rgb", "-truecolor", "-falsecolor", "-band"); print_help(); } if ( (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) && lutFlag != FLAG_NOT_SET ) asfPrintError("Look up table option can only be used on single-band " "images.\n"); if( logFlag != FLAG_NOT_SET ) { strcpy(logFile, argv[logFlag+1]); } else { sprintf(logFile, "tmp%i.log", (int)getpid()); } logflag = TRUE; // Since we always log, set the old school logflag to true fLog = FOPEN (logFile, "a"); // Set old school quiet flag (for use in our libraries) quietflag = ( quietFlag != FLAG_NOT_SET ) ? TRUE : FALSE; // We're good enough at this point... print the splash screen. asfSplashScreen (argc, argv); // Grab the input and output name strcpy (in_base_name, argv[argc - 2]); strcpy (output_name, argv[argc - 1]); strcpy (command_line.output_name, output_name); // If user added ".img", strip it. char *ext = findExt(in_base_name); if (ext && strcmp(ext, ".img") == 0) *ext = '\0'; // Set default output type if( formatFlag != FLAG_NOT_SET ) { strcpy (command_line.format, argv[formatFlag + 1]); } else { // Default behavior: produce a geotiff. strcpy (command_line.format, "geotiff"); } // Compose input metadata name strcpy (command_line.in_meta_name, in_base_name); strcat (command_line.in_meta_name, ".meta"); // for some validation, need the metadata md = meta_read (command_line.in_meta_name); // Convert the string to upper case. for ( ii = 0 ; ii < strlen (command_line.format) ; ++ii ) { command_line.format[ii] = toupper (command_line.format[ii]); } if (strcmp (command_line.format, "PGM") == 0 && (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) ) { asfPrintWarning("Greyscale PGM output is not compatible with color options:\n" "(RGB, True Color, False Color, color look-up tables, etc\n)" "...Defaulting to producing separate greyscale PGM files for available band.\n"); rgbFlag = FLAG_NOT_SET; truecolorFlag = FLAG_NOT_SET; falsecolorFlag = FLAG_NOT_SET; } // Set the default byte scaling mechanisms if (md->optical) { // for optical data, default sample mapping is NONE command_line.sample_mapping = NONE; } // for other data, default is based on the output type else if (strcmp (command_line.format, "TIFF") == 0 || strcmp (command_line.format, "TIF") == 0 || strcmp (command_line.format, "JPEG") == 0 || strcmp (command_line.format, "JPG") == 0 || strcmp (command_line.format, "PNG") == 0 || strcmp (command_line.format, "PGM") == 0 || strcmp (command_line.format, "PNG_ALPHA") == 0 || strcmp (command_line.format, "PNG_GE") == 0) { command_line.sample_mapping = SIGMA; } else if (strcmp (command_line.format, "GEOTIFF") == 0) { command_line.sample_mapping = NONE; } if ( quietFlag != FLAG_NOT_SET ) command_line.quiet = TRUE; else command_line.quiet = FALSE; // Set rgb combination if ( rgbFlag != FLAG_NOT_SET ) { int i; for (i=0, num_ignored = 0; i<3; i++) { ignored[i] = strncmp("IGNORE", uc(argv[rgbFlag + i + 1]), 6) == 0 ? 1 : 0; num_ignored += ignored[i] ? 1 : 0; } asfRequire(num_ignored < 3, "Cannot ignore all bands. Exported image would be blank.\n"); strcpy (command_line.red_channel, ignored[0] ? "Ignored" : argv[rgbFlag + 1]); strcpy (command_line.green_channel, ignored[1] ? "Ignored" : argv[rgbFlag + 2]); strcpy (command_line.blue_channel, ignored[2] ? "Ignored" : argv[rgbFlag + 3]); // Check to see if the bands are numeric and in range int r_channel = atoi(command_line.red_channel); int g_channel = atoi(command_line.green_channel); int b_channel = atoi(command_line.blue_channel); /////////// Numeric channel case //////////// // Remove trailing non-numeric characters from the channel number // string and pad front end nicely with a zero if (!ignored[0] && is_numeric(command_line.red_channel) && r_channel >= 1 && r_channel <= MAX_BANDS) { sprintf(command_line.red_channel, "%02d", atoi(command_line.red_channel)); } if (!ignored[1] && is_numeric(command_line.green_channel) && g_channel >= 1 && g_channel <= MAX_BANDS) { sprintf(command_line.green_channel, "%02d", atoi(command_line.green_channel)); } if (!ignored[2] && is_numeric(command_line.blue_channel) && b_channel >= 1 && b_channel <= MAX_BANDS) { sprintf(command_line.blue_channel, "%02d", atoi(command_line.blue_channel)); } } // Set up the bands for true or false color optical data true_color = false_color = 0; int with_sigma = FALSE; if (truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { int ALOS_optical = (md->optical && strncmp(md->general->sensor, "ALOS", 4) == 0) ? 1 : 0; if (md->optical && truecolorFlag != FLAG_NOT_SET) { if (ALOS_optical) { with_sigma = TRUE; strcpy(command_line.red_channel, "03"); strcpy(command_line.green_channel, "02"); strcpy(command_line.blue_channel, "01"); true_color = 1; asfPrintStatus("Applying True Color contrast expansion to following channels:"); } else { char **bands = extract_band_names(md->general->bands, 3); asfRequire(bands != NULL, "-truecolor option specified for non-true color optical image.\n"); asfPrintWarning("Attempting to use the -truecolor option with non-ALOS\n" "optical data.\n"); strcpy(command_line.red_channel, bands[2]); strcpy(command_line.green_channel, bands[1]); strcpy(command_line.blue_channel, bands[0]); int i; for (i=0; i<3; i++) { FREE(bands[i]); } FREE(bands); } } if (md->optical && falsecolorFlag != FLAG_NOT_SET) { if (ALOS_optical) { with_sigma = TRUE; strcpy(command_line.red_channel, "04"); strcpy(command_line.green_channel, "03"); strcpy(command_line.blue_channel, "02"); false_color = 1; asfPrintStatus("Applying False Color contrast expansion to the following channels:"); } else { char **bands = extract_band_names(md->general->bands, 4); asfRequire(bands != NULL, "-falsecolor option specified for an optical image with fewer than 4 bands.\n"); asfPrintWarning("Attempting to use the -falsecolor option with non-ALOS\n" "optical data.\n"); strcpy(command_line.red_channel, bands[3]); strcpy(command_line.green_channel, bands[2]); strcpy(command_line.blue_channel, bands[1]); int i; for (i=0; i<3; i++) { FREE(bands[i]); } FREE(bands); } } if (!ALOS_optical && !md->optical) { asfPrintError("-truecolor or -falsecolor option selected with non-optical data\n"); } } if (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { char red_band[16], green_band[16], blue_band[16]; asfPrintStatus("\nRed channel : %s %s\n", command_line.red_channel, sigma_str(with_sigma)); asfPrintStatus("Green channel: %s %s\n", command_line.green_channel, sigma_str(with_sigma)); asfPrintStatus("Blue channel : %s %s\n\n", command_line.blue_channel, sigma_str(with_sigma)); if (is_numeric(command_line.red_channel) && is_numeric(command_line.green_channel) && is_numeric(command_line.blue_channel)) { sprintf(red_band, "%02d", atoi(command_line.red_channel)); sprintf(green_band, "%02d", atoi(command_line.green_channel)); sprintf(blue_band, "%02d", atoi(command_line.blue_channel)); band_names = find_bands(in_base_name, rgbFlag, red_band, green_band, blue_band, &num_bands_found); } else { band_names = find_bands(in_base_name, rgbFlag, command_line.red_channel, command_line.green_channel, command_line.blue_channel, &num_bands_found); } } // Set band if ( bandFlag != FLAG_NOT_SET) { strcpy (command_line.band, argv[bandFlag + 1]); band_names = find_single_band(in_base_name, command_line.band, &num_bands_found); } else if (rgbFlag == FLAG_NOT_SET && truecolorFlag == FLAG_NOT_SET && falsecolorFlag == FLAG_NOT_SET && bandFlag == FLAG_NOT_SET) { bandFlag=1; // For proper messaging to the user strcpy (command_line.band, "all"); band_names = find_single_band(in_base_name, command_line.band, &num_bands_found); } // Read look up table name if ( lutFlag != FLAG_NOT_SET) { strcpy(command_line.look_up_table_name, argv[lutFlag + 1]); rgb = 1; } // Set scaling mechanism if ( byteFlag != FLAG_NOT_SET ) { strcpy (sample_mapping_string, argv[byteFlag + 1]); for ( ii = 0; ii < strlen(sample_mapping_string); ii++) { sample_mapping_string[ii] = toupper (sample_mapping_string[ii]); } if ( strcmp (sample_mapping_string, "TRUNCATE") == 0 ) command_line.sample_mapping = TRUNCATE; else if ( strcmp(sample_mapping_string, "MINMAX") == 0 ) command_line.sample_mapping = MINMAX; else if ( strcmp(sample_mapping_string, "SIGMA") == 0 ) command_line.sample_mapping = SIGMA; else if ( strcmp(sample_mapping_string, "HISTOGRAM_EQUALIZE") == 0 ) command_line.sample_mapping = HISTOGRAM_EQUALIZE; else if ( strcmp(sample_mapping_string, "NONE") == 0 ) { asfPrintWarning("Sample remapping method (-byte option) is set to NONE\n" "which doesn't make sense. Defaulting to TRUNCATE...\n"); command_line.sample_mapping = TRUNCATE; } else asfPrintError("Unrecognized byte scaling method '%s'.\n", sample_mapping_string); } int is_polsarpro = (md->general->bands && strstr(md->general->bands, "POLSARPRO") != NULL) ? 1 : 0; if ( !is_polsarpro && lutFlag != FLAG_NOT_SET && bandFlag == FLAG_NOT_SET && md->general->band_count > 1) { asfPrintError("Look up tables can only be applied to single band" " images\n"); } if ( !is_polsarpro && lutFlag != FLAG_NOT_SET && command_line.sample_mapping == NONE && md->general->data_type != BYTE && md->general->band_count == 1) { asfPrintError("Look up tables can only be applied to byte output" " images\n"); } // Report what is going to happen if (rgbFlag != FLAG_NOT_SET || truecolorFlag != FLAG_NOT_SET || falsecolorFlag != FLAG_NOT_SET) { if (num_bands_found >= 3) { asfPrintStatus("Exporting multiband image ...\n\n"); rgb = 1; } else { asfPrintError("Not all RGB channels found.\n"); } } else if (bandFlag != FLAG_NOT_SET) { if (strcmp_case(command_line.band, "ALL") == 0) { if (multiband(command_line.format, extract_band_names(md->general->bands, md->general->band_count), md->general->band_count)) asfPrintStatus("Exporting multiband image ...\n\n"); else if (num_bands_found > 1) asfPrintStatus("Exporting each band into individual greyscale files ...\n\n"); } else if (num_bands_found == 1) { if (lutFlag != FLAG_NOT_SET) asfPrintStatus("Exporting band '%s' applying look up table ...\n\n", command_line.band); else asfPrintStatus("Exporting band '%s' as greyscale ...\n\n", command_line.band); } else asfPrintError("Band could not be found in the image.\n"); } else if (lutFlag != FLAG_NOT_SET) asfPrintStatus("Exporting applying look up table.\n\n"); else asfPrintStatus("Exporting as greyscale.\n\n"); //If user added ".img", strip it. ext = findExt(in_base_name); if (ext && strcmp(ext, ".img") == 0) *ext = '\0'; meta_free(md); /***********************END COMMAND LINE PARSING STUFF***********************/ if ( strcmp (command_line.format, "ENVI") == 0 ) { format = ENVI; } else if ( strcmp (command_line.format, "ESRI") == 0 ) { format = ESRI; } else if ( strcmp (command_line.format, "GEOTIFF") == 0 || strcmp (command_line.format, "GEOTIF") == 0) { format = GEOTIFF; } else if ( strcmp (command_line.format, "TIFF") == 0 || strcmp (command_line.format, "TIF") == 0) { format = TIF; } else if ( strcmp (command_line.format, "JPEG") == 0 || strcmp (command_line.format, "JPG") == 0) { format = JPEG; } else if ( strcmp (command_line.format, "PGM") == 0 ) { format = PGM; } else if ( strcmp (command_line.format, "PNG") == 0 ) { format = PNG; } else if ( strcmp (command_line.format, "PNG_ALPHA") == 0 ) { format = PNG_ALPHA; } else if ( strcmp (command_line.format, "PNG_GE") == 0 ) { format = PNG_GE; } else if ( strcmp (command_line.format, "KML") == 0 ) { format = KML; } else if ( strcmp (command_line.format, "POLSARPRO") == 0 ) { format = POLSARPRO_HDR; } else if ( strcmp (command_line.format, "HDF5") == 0 ) { format = HDF; } else if ( strcmp (command_line.format, "NETCDF") == 0 ) { format = NC; } else { asfPrintError("Unrecognized output format specified\n"); } /* Complex data generally can't be output into meaningful images, so we refuse to deal with it. */ /* md = meta_read (command_line.in_meta_name); asfRequire ( md->general->data_type == BYTE || md->general->data_type == INTEGER16 || md->general->data_type == INTEGER32 || md->general->data_type == REAL32 || md->general->data_type == REAL64, "Cannot cope with complex data, exiting...\n"); meta_free (md); */ // Do that exporting magic! asf_export_bands(format, command_line.sample_mapping, rgb, true_color, false_color, command_line.look_up_table_name, in_base_name, command_line.output_name, band_names, NULL, NULL); // If the user didn't ask for a log file then nuke the one that's been kept // since everything has finished successfully if (logFlag == FLAG_NOT_SET) { fclose (fLog); remove(logFile); } for (ii = 0; ii<num_bands_found; ii++) { FREE(band_names[ii]); } FREE(band_names); FREE(in_base_name); FREE(output_name); exit (EXIT_SUCCESS); }
int asf_import(radiometry_t radiometry, int db_flag, int complex_flag, int multilook_flag, int azimuth_look_count, int range_look_count, int amp0_flag, input_format_t format_type, char *band_id, char *data_type, char *image_data_type, char *lutName, char *prcPath, double lowerLat, double upperLat, double lowerLon, double upperLon, int line, int sample, int width, int height, int save_intermediates, double *p_range_scale, double *p_azimuth_scale, double *p_correct_y_pixel_size, int apply_ers2_gain_fix, char *inMetaNameOption, char *inBaseName, char *ancillary_file, char *colormapName, char *slave_file, char *interferogram_file, char *coherence_file, char *baseline_file, int complex_gamma, char *uavsar_type, int metaonly, char *outBaseName) { char outDataName[256], outMetaName[256]; asfPrintStatus(" Importing: %s\n", inBaseName); /* printf("\nradiometry: %d\n", radiometry); printf("db_flag: %d\n", db_flag); printf("complex_flag: %d\n", complex_flag); printf("multilook_flag: %d\n", multilook_flag); printf("amp0_flag: %d\n", amp0_flag); printf("format_type: %d\n", format_type); printf("band_id: %s\n", band_id); printf("data_type: %s\n", data_type); printf("image_data_type: %s\n", image_data_type); printf("lutName: %s\n", lutName); printf("line: %d\n", line); printf("sample: %d\n", sample); printf("width: %d\n", width); printf("height: %d\n", height); printf("p_range_scale: %f\n", &p_range_scale); printf("p_azimuth_scale: %f\n", &p_azimuth_scale); printf("p_correct_y_pixel_size: %f\n", &p_correct_y_pixel_size); printf("apply_ers2_gain_fix: %d\n", apply_ers2_gain_fix); printf("inMetaNameOption: %s\n", inMetaNameOption); printf("inBaseName: %s\n", inBaseName); printf("outBaseName: %s\n\n", outBaseName); */ strcpy(outDataName, outBaseName); strcpy(outMetaName, outBaseName); strcat(outMetaName, TOOLS_META_EXT); if (metaonly) { create_xml_meta(inBaseName, outBaseName, format_type); return 0; } if ((radiometry == r_SIGMA || radiometry == r_BETA || radiometry == r_GAMMA || radiometry == r_POWER) && !(format_type == CEOS || format_type == STF || format_type == AIRSAR || format_type == ALOS_MOSAIC || format_type == TERRASAR)) { // A power flag is on, but the input file is not CEOS or STF format // so it will be ignored asfPrintWarning("Power flags %s%s will be only accepted for the following\n" "data formats since other formats do not indicate what " "type of data is in the file:\n" "CEOS, TERRASAR, STF, AirSAR and ALOS mosaics.\n" "Assuming the input data is an AMPLITUDE image...\n", radiometry == r_SIGMA ? "SIGMA" : radiometry == r_BETA ? "BETA" : radiometry == r_GAMMA ? "GAMMA" : radiometry == r_POWER ? "POWER" : "UNKNOWN", db_flag ? " scaled to DECIBELS" : ""); } // Ingest all sorts of flavors of CEOS data/ if (format_type == CEOS) { asfPrintStatus(" Data format: CEOS\n"); import_ceos(inBaseName, outBaseName, band_id, lutName, p_range_scale, p_azimuth_scale, p_correct_y_pixel_size, line, sample, width, height, inMetaNameOption, radiometry, db_flag, complex_flag, multilook_flag, azimuth_look_count, range_look_count, amp0_flag, apply_ers2_gain_fix); // Replace the restituted state vectors that comes with the image data with // precision state vectors from Delft if (prcPath != NULL && strlen(prcPath) > 0) { update_state_vectors(outBaseName, prcPath); } } // Ingest Vexcel Sky Telemetry Format (STF) data else if (format_type == STF) { asfPrintStatus(" Data format: STF\n"); int lat_constrained = upperLat != -99 && lowerLat != -99; import_stf(inBaseName, outBaseName, radiometry, inMetaNameOption, lat_constrained, lowerLat, upperLat, prcPath); } else if (format_type == GENERIC_GEOTIFF) { asfPrintStatus(" Data format: GEOTIFF\n"); if (band_id != NULL && strlen(band_id) > 0 && strncmp(uc(band_id), "ALL", 3) != 0) { asfPrintWarning("The -band option is not supported for data files containing\n" "multiple bands within a single file (such as GeoTIFF or TIFF)\n" "rather than in individual band files (such as ALOS etc).\n" "\nThe import will continue, but all available bands will be\n" "imported into a single ASF-format file. You may select any\n" "individual band for export however.\n"); } char *ext = findExt(inBaseName); if (ext != NULL) { *ext = '\0'; } GString *inGeotiffName = find_geotiff_name (inBaseName); if ( inGeotiffName == NULL ) { asfPrintError ("Couldn't find a GeoTIFF file (i.e. a file with " "extension '.tif', '.tiff',\n'.TIF', or '.TIFF') " "corresponding to specified inBaseName:\n" "%s\n", inBaseName); } if (strlen(image_data_type) && strncmp(image_data_type, MAGIC_UNSET_STRING, strlen(MAGIC_UNSET_STRING)) != 0) { import_generic_geotiff (inGeotiffName->str, outBaseName, image_data_type); } else { import_generic_geotiff (inGeotiffName->str, outBaseName, NULL); } g_string_free(inGeotiffName,TRUE); } else if (format_type == BIL) { asfPrintStatus(" Data format: BIL\n"); import_bil(inBaseName, outBaseName); } else if (format_type == GRIDFLOAT) { asfPrintStatus(" Data format: GRIDFLOAT\n"); import_gridfloat(inBaseName, outBaseName); } else if (format_type == AIRSAR) { asfPrintStatus(" Data format: AIRSAR\n"); import_airsar(inBaseName, update(radiometry, db_flag), outBaseName); } else if (format_type == UAVSAR) { asfPrintStatus(" Data format: UAVSAR\n"); import_uavsar(inBaseName, line, sample, width, height, update(radiometry, db_flag), uavsar_type, outBaseName); } else if (format_type == VP) { asfPrintStatus(" Data format: VP\n"); import_vexcel_plain(inBaseName, outBaseName); } else if (format_type == JAXA_L0) { asfPrintStatus(" Data format: JAXA_L0 (ALOS AVNIR-2 Level 0)\n"); import_jaxa_L0(inBaseName, outBaseName); } else if (format_type == ALOS_MOSAIC) { asfPrintStatus(" Data format: ALOS MOSAIC\n"); import_alos_mosaic(inBaseName, update(radiometry, db_flag), outBaseName); } else if (format_type == TERRASAR) { asfPrintStatus(" Data format: TERRASAR\n"); import_terrasar(inBaseName, update(radiometry, db_flag), outBaseName, 0); } else if (format_type == RADARSAT2) { asfPrintStatus(" Data format: RADARSAT2\n"); import_radarsat2(inBaseName, update(radiometry, db_flag), outBaseName, 0); } else if (format_type == POLSARPRO) { asfPrintStatus(" Data format: POLSARPRO\n"); import_polsarpro(inBaseName, ancillary_file, colormapName, image_data_type, db_flag, outBaseName); } else if (format_type == GAMMA) { asfPrintStatus(" Data format: GAMMA\n"); import_gamma(inBaseName, inMetaNameOption, slave_file, interferogram_file, coherence_file, baseline_file, complex_gamma, outBaseName); } else if (format_type == ROIPAC) { asfPrintStatus(" Data format: ROI_PAC\n"); import_roipac(inBaseName, outBaseName); } else if (format_type == SMAP) { asfPrintStatus(" Data format: SMAP\n"); import_smap(inBaseName, outBaseName, upperLat, upperLon, lowerLat, lowerLon); } // Don't recognize this data format; report & quit else { asfPrintError("Unrecognized data format: '%d'\n",format_type); } int num_elements = 0; int is_jasc_palette = 0; if (format_type == AIRSAR && colormapName != NULL) asfPrintError("Colormaps not supported for AirSAR data.\n"); if (format_type != AIRSAR && format_type != UAVSAR) { meta_parameters *meta = meta_read(outMetaName); if (meta->colormap) { if (!(colormapName != NULL && (meta->general->data_type == ASF_BYTE || is_PolSARpro(inBaseName)))) { // Ooops. Tried to apply a colormap to the wrong type of data asfPrintWarning( "Color map specified with the -colormap option (%s) not\n" "applied during ingest. Color maps can only be applied to byte or\n" "PolSARpro data. Data was imported as-is.\n", colormapName); } else { // Apply the user-selected color map to the metadata FILE *fp = NULL; unsigned char * lut_buffer; char *lut_basename = STRDUP(colormapName); char *ext = findExt(lut_basename); if (ext) *ext = '\0'; // Check LUT file validity and allocate appropriately sized buffer // to read into char magic_str[1024]; char version_s[1024]; char num_elements_s[1024]; char lut_path[1024]; sprintf(lut_path, "%s%clook_up_tables%c%s.pal", get_asf_share_dir(), DIR_SEPARATOR, DIR_SEPARATOR, lut_basename); if (fileExists(lut_path)) { fp = (FILE*)FOPEN(lut_path, "rt"); fgets(magic_str, 1024, fp); fgets(version_s, 1024, fp); fgets(num_elements_s, 1024, fp); FCLOSE(fp); int version = atoi(version_s); num_elements = atoi(num_elements_s); is_jasc_palette = (strncmp(magic_str, "JASC", 4) == 0 && version == 100) ? 1 : 0; if (is_jasc_palette && (num_elements <= 0 || num_elements > 512)) { asfPrintWarning( "Found invalid JASC-PAL type color map file (%s) ...color map\n" "not applied.\n", colormapName); } if (num_elements > 256) { asfPrintWarning( "PolSARpro look-up table contains more than 256 elements (%d).\n" "Only the first 256 will be read and mapped to data.\n", num_elements); } } else { sprintf(lut_path, "%s%clook_up_tables%c%s.lut", get_asf_share_dir(), DIR_SEPARATOR, DIR_SEPARATOR, lut_basename); if (fileExists(lut_path)) { is_jasc_palette = 0; // Assume ASF format } else { strcpy(lut_path, ""); } } lut_buffer = MALLOC(sizeof(unsigned char) * 3 * MAX_LUT_DN); // Read the LUT if (strlen(lut_path) > 0) { int max_dn = read_lut(lut_path, lut_buffer); // Populate the metadata colormap if (!meta->colormap) meta->colormap = meta_colormap_init(); if (is_jasc_palette) { meta->colormap->num_elements = (num_elements <= 256) ? num_elements : 256; sprintf(meta->colormap->look_up_table, "%s.pal", lut_basename); } else { num_elements = max_dn + 1; meta->colormap->num_elements = num_elements; sprintf(meta->colormap->look_up_table, "%s.lut", lut_basename); } meta->colormap->rgb = (meta_rgb*)CALLOC(meta->colormap->num_elements, sizeof(meta_rgb)); int i; for (i = 0; i < meta->colormap->num_elements; i++) { meta->colormap->rgb[i].red = lut_buffer[i*3]; meta->colormap->rgb[i].green = lut_buffer[i*3+1]; meta->colormap->rgb[i].blue = lut_buffer[i*3+2]; } } FREE(lut_basename); meta_write(meta, outMetaName); } } meta_free(meta); } asfPrintStatus("Import complete.\n\n"); return 0; }
static char * do_convert(int pid, GtkTreeIter *iter, char *cfg_file, int save_dem, int keep_files, char **intermediates_file) { FILE *output; char *logFile = appendExt(cfg_file, ".log"); gtk_list_store_set(list_store, iter, COL_STATUS, "Processing...", -1); #ifdef win32 STARTUPINFO si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); char *cmd = MALLOC(sizeof(char)* (strlen(cfg_file) + strlen(logFile) + strlen(get_asf_bin_dir_win()) + 256)); sprintf(cmd, "\"%s/asf_mapready.exe\" %s-log \"%s\" \"%s\"", get_asf_bin_dir_win(), save_dem ? "--save-dem " : "", logFile, cfg_file); fLog = fopen(logFile, "a"); log_summary_text(fLog); FCLOSE(fLog); //printf("Running command> %s\n", cmd); if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { DWORD dw = GetLastError(); //printf( "CreateProcess failed (%ld)\n", dw ); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); printf("CreateProcess() failed with error %ld: %s\n", dw, (char*)lpMsgBuf); printf("Failed command: %s\n", cmd); } char *statFile = appendExt(cfg_file, ".status"); DWORD dwWaitResult; int counter = 1; // now wait for process to finish do { while (gtk_events_pending()) gtk_main_iteration(); if (++counter % 200 == 0) { // check status file char buf[256]; FILE *fStat = fopen(statFile, "r"); if (fStat) { fgets(buf, sizeof(buf), fStat); fclose(fStat); gtk_list_store_set(list_store, iter, COL_STATUS, buf, -1); } } dwWaitResult = WaitForSingleObject(pi.hProcess, 50); } while (dwWaitResult == WAIT_TIMEOUT); remove_file(statFile); free(statFile); // Don't do this, CreateProcess() takes it //free(cmd); #else extern int logflag; extern FILE *fLog; pid = fork(); if (pid == 0) { /* child */ logflag = TRUE; fLog = fopen(logFile, "a"); asfPrintStatus("Running MapReady with configuration file: %s\n", cfg_file); log_summary_text(fLog); asf_convert_ext(FALSE, cfg_file, save_dem); FCLOSE(fLog); exit(EXIT_SUCCESS); } else { /* parent */ int counter = 1; char *statFile = appendExt(cfg_file, ".status"); while (waitpid(pid, NULL, WNOHANG) == 0) { while (gtk_events_pending()) gtk_main_iteration(); g_usleep(50); if (++counter % 200 == 0) { /* check status file */ char buf[256]; FILE *fStat = fopen(statFile, "r"); if (fStat) { if (fgets(buf, sizeof(buf), fStat)) fclose(fStat); else strcpy(buf,""); gtk_list_store_set(list_store, iter, COL_STATUS, buf, -1); if (strcmp(buf, "Done")==0 || strcmp(buf, "Error")==0) { // kludge: // Status file says "Done" but we're still here. // This could happen because it *just* finished // during the most recent g_usleep(), but a much more // likely reason is that the waitpid() detection // failed. (I say "much more likely" because waitpid // is checked 200x more often than the status file) // UPDATE! // We figured out why this is occurring on Linux, // it is a bug in the GtkFileChooser. Since the // chooser is much nicer than the older FileSelector, // we'll keep this kludge... seems to be no other // side effects... hopefully... // Expanded the kludge to update the status file // with "Error", so that even if the process exits // with an error we'll still be ok. This only // leaves the core-dump case as a loose end. #ifdef linux // On Linux (which is actually the only platform // I have seen this problem), we can try to kill // the zombie process. kill(pid, 9); #endif // We'll break out of the loop now, and // possibly leave a zombie process around, if this // were to occur somewhere other than Linux break; } } } } remove_file(statFile); free(statFile); } #endif gchar *the_output = NULL; output = fopen(logFile, "r"); // see if we got a file containing a list of useful intermediate files *intermediates_file = appendExt(cfg_file, ".files"); if (!fileExists(*intermediates_file)) { free(*intermediates_file); *intermediates_file = NULL; } if (!output) { the_output = (gchar *)g_malloc(512); sprintf(the_output, "Error Opening Log File: %s\n", strerror(errno)); } else { gchar buffer[4096]; gchar *p = fgets(buffer, sizeof(buffer), output); while (!feof(output)) { if (p && !g_str_has_prefix(p, "Processing ")) { if (the_output) { the_output = (gchar *)g_realloc(the_output, sizeof(gchar) * (strlen(the_output) + strlen(buffer) + 1)); strcat(the_output, buffer); } else { the_output = (gchar *) g_malloc(sizeof(gchar) * (strlen(buffer) + 1)); strcpy(the_output, buffer); } } p = fgets(buffer, sizeof(buffer), output); } fclose(output); if (!keep_files) remove_file(logFile); } if (!the_output) { /* Log file existed, but had immediate EOF */ /* This is most likely caused by a "Disk Full" situation... */ /* ... or a segmentation fault! */ the_output = g_strdup("Error Opening Log File: Disk Full?\n"); } free(logFile); return the_output; }
// Input: // meta_parameters *meta_sar-- SAR geometry to subset the DEM // const char *demImg -- DEM data filename // const char *demMeta -- DEM metadata filename // int pad -- number of lines to add at the top/bottom/left/right // double tolerance -- how accurate the approximation mapping needs to be, // in units of pixels // const char *output_name -- output filename (basename) // int test_mode -- adds checks for the accuracy of the mapping, and // does some unit testing // Output: // no output parameters, the output is the output_name files (.img and .meta) // Return Value: // return TRUE on success, FALSE on fail // int make_gr_dem_ext(meta_parameters *meta_sar, const char *demImg, const char *demMeta, int pad, double tolerance, const char *output_name, int test_mode) { if (test_mode) test_interp(); asfPrintStatus("Reading DEM...\n"); meta_parameters *meta_dem = meta_read(demMeta); float *demData = read_dem(meta_dem, demImg); int dnl = meta_dem->general->line_count; int dns = meta_dem->general->sample_count; char *outImg = appendExt(output_name, ".img"); char *output_name_tmp, *outImgTmp; // do not do DEM smoothing if the DEM pixel size is better or close to the // SAR image's pixel size. int do_averaging = TRUE; if (meta_dem->general->y_pixel_size - 10 < meta_sar->general->y_pixel_size) do_averaging = FALSE; asfPrintStatus("Averaging: %s (DEM %f, SAR: %f)\n", do_averaging ? "YES" : "NO", meta_dem->general->y_pixel_size, meta_sar->general->y_pixel_size); if (do_averaging) { output_name_tmp = appendStr(output_name, "_unsmoothed"); outImgTmp = appendExt(output_name_tmp, ".img"); } else { output_name_tmp = STRDUP(output_name); outImgTmp = STRDUP(outImg); } // add the padding if requested meta_parameters *meta_out = meta_copy(meta_sar); meta_out->general->line_count += pad*2; meta_out->general->sample_count += pad*2; meta_out->general->start_line -= pad; meta_out->general->start_sample -= pad; // fixing up the output metadata. Note that we must keep the SAR section // intact since that specifies our geometry which is the whole point of // this exercise. strcpy(meta_out->general->basename, meta_dem->general->basename); strcpy(meta_out->general->sensor, MAGIC_UNSET_STRING); strcpy(meta_out->general->processor, MAGIC_UNSET_STRING); strcpy(meta_out->general->mode, MAGIC_UNSET_STRING); strcpy(meta_out->general->sensor_name, MAGIC_UNSET_STRING); meta_out->general->image_data_type = DEM; meta_out->general->radiometry = MAGIC_UNSET_INT; strcpy(meta_out->general->acquisition_date, meta_dem->general->acquisition_date); meta_out->general->orbit = MAGIC_UNSET_INT; meta_out->general->orbit_direction = MAGIC_UNSET_CHAR; meta_out->general->frame = MAGIC_UNSET_INT; meta_out->general->band_count = 1; strcpy(meta_out->general->bands, "DEM"); int nl = meta_out->general->line_count; int ns = meta_out->general->sample_count; // finding the right grid size int size = find_grid_size(meta_sar, meta_dem, 512, .1*tolerance); asfPrintStatus("Creating ground range image...\n"); float *buf = MALLOC(sizeof(float)*ns*size); FILE *fpOut = FOPEN(outImgTmp, "wb"); // 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; int ii, jj; for (ii=0; ii<nl; ii += size) { int line_lo = ii; int line_hi = ii + size; for (jj=0; jj<ns; jj += size) { double lines[4], samps[4]; int samp_lo = jj; int samp_hi = jj + size; get_interp_params(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi, lines, samps); int iii, jjj; for (iii=0; iii<size; ++iii) { for (jjj=0; jjj<size && jj+jjj<ns; ++jjj) { int index = iii*ns + jj + jjj; assert(index < ns*size); double line_out, samp_out; xy_interp(ii+iii, jj+jjj, line_lo, line_hi, samp_lo, samp_hi, lines, samps, &line_out, &samp_out); // random checking of the quality of our interpolations if (test_mode && iii%11==0 && jjj%13==0) { double real_line, real_samp; sar_to_dem(meta_sar, meta_dem, ii+iii, jj+jjj, &real_line, &real_samp); double err = hypot(real_line - line_out, real_samp - samp_out); avg_err += err; if (err > max_err) max_err = err; if (err > tolerance) { asfPrintStatus("Out of tolerance at %d,%d: (%f,%f) vs (%f,%f) -> %f\n", ii+iii, jj+jjj, line_out, samp_out, real_line, real_samp, err); ++num_out_of_tol; } if (err > .5) { asfPrintStatus("Error is larger than 1 pixel!\n"); ++num_bad; } ++num_checked; } buf[index] = interp_demData(demData, dnl, dns, line_out, samp_out); } } } put_float_lines(fpOut, meta_out, ii, size, buf); asfPrintStatus("Completed %.1f%% \r", 100.*ii/(double)nl); } asfPrintStatus("Completed 100%% \n"); if (test_mode) { asfPrintStatus("Tolerance was %f\n", tolerance); asfPrintStatus("%d/%d checked pixels had error exceeding tolerance. (%.1f%%)\n", num_out_of_tol, num_checked, 100.*num_out_of_tol/(double)num_checked); asfPrintStatus("%d/%d checked pixels had error larger than half a pixel. (%.1f%%)\n", num_bad, num_checked, 100.*num_bad/(double)num_checked); asfPrintStatus("Maximum error: %f pixels\n", max_err); avg_err /= (double)num_checked; asfPrintStatus("Average error: %f pixels\n", avg_err); } FCLOSE(fpOut); meta_write(meta_out, outImgTmp); meta_free(meta_out); meta_free(meta_dem); FREE(buf); FREE(demData); // now apply 3x3 filter if (do_averaging) { asfPrintStatus("Smoothing with 3x3 kernel ...\n"); smooth(outImgTmp, outImg, 3, EDGE_TRUNCATE); } FREE(outImg); FREE(outImgTmp); FREE(output_name_tmp); return FALSE; }
int open_asf_data(const char *filename, const char *band, int multilook, meta_parameters *meta, ClientInterface *client) { ReadAsfClientInfo *info = MALLOC(sizeof(ReadAsfClientInfo)); info->is_rgb = FALSE; info->band_gs = info->band_r = info->band_g = info->band_b = 0; info->ml = multilook; // special hack for Avnir data! if (!band && strcmp_case(meta->general->sensor_name, "AVNIR") == 0 && meta->general->band_count >= 3) { // no band was specifed -- show true color (3,2,1) asfPrintStatus("Avnir data: defaulting to TRUE color -- " "Red=3, Green=2, Blue=1\n"); band = "03,02,01"; } if (band) { char *r, *b, *g; if (split3(band, &r, &g, &b, ',')) { // Looks like we were given 3 bands -- so, we are doing rgb info->band_r = get_band_number(meta->general->bands, meta->general->band_count, r); if (info->band_r < 0) asfPrintWarning("Red band '%s' not found.\n", r); else asfPrintStatus("Red band is band #%d: %s\n", info->band_r+1, r); info->band_g = get_band_number(meta->general->bands, meta->general->band_count, g); if (info->band_g < 0) asfPrintWarning("Green band '%s' not found.\n", g); else asfPrintStatus("Green band is band #%d: %s\n", info->band_g+1, g); info->band_b = get_band_number(meta->general->bands, meta->general->band_count, b); if (info->band_b < 0) asfPrintWarning("Blue band '%s' not found.\n", b); else asfPrintStatus("Blue band is band #%d: %s\n", info->band_b+1, b); if (info->band_r < 0 && info->band_g < 0 && info->band_b < 0) { // none of the bands were found return FALSE; } info->is_rgb = TRUE; FREE(r); FREE(g); FREE(b); set_bands_rgb(info->band_r, info->band_g, info->band_b); } else { // Single band name given info->band_gs = get_band_number(meta->general->bands, meta->general->band_count, (char*)band); if (info->band_gs < 0) { asfPrintWarning("Band '%s' not found.\n", band); return FALSE; } else { asfPrintStatus("Reading band #%d: %s\n", info->band_gs+1, band); } set_bands_greyscale(info->band_gs); } } info->fp = fopen(filename, "rb"); if (!info->fp) { asfPrintWarning("Failed to open ASF Internal file %s: %s\n", filename, strerror(errno)); return FALSE; } client->read_client_info = info; client->read_fn = read_asf_client; client->thumb_fn = get_asf_thumbnail_data; client->free_fn = free_asf_client_info; if (meta->general->data_type == ASF_BYTE) client->data_type = info->is_rgb ? RGB_BYTE : GREYSCALE_BYTE; else client->data_type = info->is_rgb ? RGB_FLOAT : GREYSCALE_FLOAT; // special sanity checks for ASF data if (meta->general->line_count == 0 || meta->general->sample_count == 0) { asfPrintStatus("Line count: %d\n", meta->general->line_count); asfPrintStatus("Sample count: %d\n", meta->general->sample_count); asfPrintWarning("Line count or sample count is 0.\n"); return FALSE; } long long sz = fileSize(filename); int mult = (info->is_rgb ? 3 : 1) * (meta->general->data_type == ASF_BYTE ? 1 : 4); long long expected_sz = meta->general->line_count * meta->general->sample_count * mult; if (sz < expected_sz) { asfPrintWarning("File is too short! Truncating lines...\n"); int orig = meta->general->line_count; asfPrintStatus("Original line count: %d\n", orig); meta->general->line_count = sz / mult / meta->general->sample_count; asfPrintStatus("Truncated line count (calculated from file size): %d\n", meta->general->line_count); asfPrintWarning("Truncated %d lines!\n", orig - meta->general->line_count); } return TRUE; }
void baseline_catalog(char *sensor, char *beam_mode, char *input_dir, char *output_dir) { struct dirent *dp; DIR *dir; FILE *fpTxt, *fpKml, *fpShape, *fpDB; int track, nOrbits, nFrames, nPairs, nTracks, orbit=0; report_level_t report = REPORT_LEVEL_STATUS; struct base_pair *base_pairs=NULL; struct srf_orbit *srf_orbit=NULL; char cmd[255], tmp_dir[1024], track_list[1024]; // Some more error checking on beam modes if (strcmp_case(sensor, "R1") == 0) { if (strcmp_case(beam_mode, "FN1") != 0 && strcmp_case(beam_mode, "FN2") != 0 && strcmp_case(beam_mode, "FN3") != 0 && strcmp_case(beam_mode, "FN4") != 0 && strcmp_case(beam_mode, "FN5") != 0 && strcmp_case(beam_mode, "ST1") != 0 && strcmp_case(beam_mode, "ST2") != 0 && strcmp_case(beam_mode, "ST3") != 0 && strcmp_case(beam_mode, "ST4") != 0 && strcmp_case(beam_mode, "ST5") != 0 && strcmp_case(beam_mode, "ST6") != 0 && strcmp_case(beam_mode, "ST7") != 0) asfPrintError("Unknown beam mode '%s' for sensor '%s'.\n", beam_mode, sensor); } else if ((strcmp_case(sensor, "E1") == 0 || strcmp_case(sensor, "E2") == 0) && strcmp_case(beam_mode, "STD") != 0) asfPrintError("Unknown beam mode '%s' for sensor '%s'.\n", beam_mode, sensor); else if (strcmp_case(sensor, "J1") == 0 && strcmp_case(beam_mode, "STD") != 0) asfPrintError("Unknown beam mode '%s' for sensor '%s'.\n", beam_mode, sensor); else if (strcmp_case(sensor, "PALSAR") == 0 && strcmp_case(beam_mode, "PLR") != 0) asfPrintError("Unknown beam mode '%s' for sensor '%s'.\n", beam_mode, sensor); // Report what is going on asfReport(report, "Calculating baseline catalog for satellite '%s' in " "beam mode '%s'\n\n", sensor, beam_mode); // Create temporary directory for list files sprintf(tmp_dir, "%s/%s", output_dir, time_stamp_dir()); create_clean_dir(tmp_dir); // Setup the baseline calculation setup_files(sensor, beam_mode, input_dir, tmp_dir, &nTracks, &nFrames); // Step through the archive track by track - save plenty of memory for (track=0; track<nTracks; track++) { asfPrintStatus("\nTrack: %d (out of %d)\n", track+1, nTracks); nOrbits = 0; nPairs = 0; // Get a list of recent SRFs if (strcmp(sensor, "PSR") == 0) asfPrintStatus("Reading metadata file ...\n"); else asfPrintStatus("Reading SRFs ...\n"); sprintf(track_list, "%s/%s_track%d.lst", tmp_dir, sensor, track); if (fileExists(track_list)) { if (strcmp(sensor, "PSR") == 0) read_palsar(track_list, &srf_orbit, &nOrbits); else read_srf(input_dir, track_list, &srf_orbit, &nOrbits); } else continue; // Determine baselines if (nOrbits) { asfPrintStatus("Determining baselines ...\n"); determine_baseline(sensor, sensor, beam_mode, track, orbit, srf_orbit, nOrbits, &base_pairs, &nPairs); } // Generate products if (nPairs) { asfPrintStatus("Generate products ...\n"); generate_products(output_dir, base_pairs, nPairs); } // Clean up before last track if (srf_orbit) FREE(srf_orbit); if (base_pairs) FREE(base_pairs); srf_orbit = NULL; base_pairs = NULL; //exit(0); } // Pack text, KML and shape files for entire mode chdir(output_dir); fpTxt = FOPEN("txt.lst", "w"); fpKml = FOPEN("kml.lst", "w"); fpShape = FOPEN("shape.lst", "w"); fpDB = FOPEN("db.lst", "w"); dir = opendir(output_dir); while ((dp = readdir(dir)) != NULL) { if (strstr(dp->d_name, ".txt")) fprintf(fpTxt, "%s\n", dp->d_name); if (strstr(dp->d_name, ".kml")) fprintf(fpKml, "%s\n", dp->d_name); if (strstr(dp->d_name, ".tgz")) fprintf(fpShape, "%s\n", dp->d_name); if (strstr(dp->d_name, ".db") && !strstr(dp->d_name, ".dbf")) fprintf(fpDB, "%s\n", dp->d_name); } closedir(dir); FCLOSE(fpTxt); FCLOSE(fpKml); FCLOSE(fpShape); FCLOSE(fpDB); printf("\nZipping text files ...\n"); sprintf(cmd, "tar czf %s_%s_txt.tgz -T txt.lst", sensor, beam_mode); asfSystem(cmd); printf("\nZipping KML files ...\n"); sprintf(cmd, "tar czf %s_%s_kml.tgz -T kml.lst", sensor, beam_mode); asfSystem(cmd); printf("\nZipping shape files ...\n"); sprintf(cmd, "tar czf %s_%s_shape.tgz -T shape.lst", sensor, beam_mode); asfSystem(cmd); printf("\nZipping database files ...\n"); sprintf(cmd, "tar czf %s_%s_db.tgz -T db.lst", sensor, beam_mode); asfSystem(cmd); sprintf(cmd, "rm txt.lst kml.lst shape.lst db.lst"); asfSystem(cmd); printf("\n\n"); }
void calc_stats_from_file(const char *inFile, char *band, double mask, double *min, double *max, double *mean, double *stdDev, gsl_histogram **histogram) { int ii,jj; *min = 999999; *max = -999999; *mean = 0.0; meta_parameters *meta = meta_read(inFile); int band_number; if (!band || strlen(band) == 0 || strcmp(band, "???") == 0 || meta->general->band_count == 1) { band_number = 0; } else { band_number = get_band_number(meta->general->bands, meta->general->band_count, band); } long offset = meta->general->line_count * band_number; float *data = MALLOC(sizeof(float) * meta->general->sample_count); // pass 1 -- calculate mean, min & max FILE *fp = FOPEN(inFile, "rb"); long long pixel_count=0; asfPrintStatus("\nCalculating min, max, and mean...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter(((double)ii/(double)meta->general->line_count)); get_float_line(fp, meta, ii + offset, data); for (jj=0; jj<meta->general->sample_count; ++jj) { if (ISNAN(mask) || !FLOAT_EQUIVALENT(data[jj], mask)) { if (data[jj] < *min) *min = data[jj]; if (data[jj] > *max) *max = data[jj]; *mean += data[jj]; ++pixel_count; } } } asfPercentMeter(1.0); FCLOSE(fp); *mean /= pixel_count; // Guard against weird data if(!(*min<*max)) *max = *min + 1; // Initialize the histogram. const int num_bins = 256; gsl_histogram *hist = gsl_histogram_alloc (num_bins); gsl_histogram_set_ranges_uniform (hist, *min, *max); *stdDev = 0.0; // pass 2 -- update histogram, calculate standard deviation fp = FOPEN(inFile, "rb"); asfPrintStatus("\nCalculating standard deviation and histogram...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter(((double)ii/(double)meta->general->line_count)); get_float_line(fp, meta, ii + offset, data); for (jj=0; jj<meta->general->sample_count; ++jj) { if (ISNAN(mask) || !FLOAT_EQUIVALENT(data[jj], mask)) { *stdDev += (data[jj] - *mean) * (data[jj] - *mean); gsl_histogram_increment (hist, data[jj]); } } } asfPercentMeter(1.0); FCLOSE(fp); *stdDev = sqrt(*stdDev/(pixel_count - 1)); FREE(data); meta_free(meta); *histogram = hist; }
int asf_igram_coh(int lookLine, int lookSample, int stepLine, int stepSample, char *masterFile, char *slaveFile, char *outBase, float *average) { char ampFile[255], phaseFile[255]; //, igramFile[512]; char cohFile[512], ml_ampFile[255], ml_phaseFile[255]; //, ml_igramFile[512]; FILE *fpMaster, *fpSlave, *fpAmp, *fpPhase, *fpCoh, *fpAmp_ml, *fpPhase_ml; int line, sample_count, line_count, count; float bin_high, bin_low, max=0.0, sum_a, sum_b, ampScale; double hist_sum=0.0, percent, percent_sum; long long hist_val[HIST_SIZE], hist_cnt=0; meta_parameters *inMeta,*outMeta, *ml_outMeta; complexFloat *master, *slave, *sum_igram, *sum_ml_igram; float *amp, *phase, *sum_cpx_a, *sum_cpx_b, *coh, *pCoh; float *ml_amp, *ml_phase; // FIXME: Processing flow with two-banded interferogram needed - backed out // for now create_name(ampFile, outBase,"_igram_amp.img"); create_name(phaseFile, outBase,"_igram_phase.img"); create_name(ml_ampFile, outBase,"_igram_ml_amp.img"); create_name(ml_phaseFile, outBase,"_igram_ml_phase.img"); //create_name(igramFile, outBase,"_igram.img"); //create_name(ml_igramFile, outBase, "_igram_ml.img"); //sprintf(cohFile, "coherence.img"); create_name(cohFile, outBase, "_coh.img"); // Read input meta file inMeta = meta_read(masterFile); line_count = inMeta->general->line_count; sample_count = inMeta->general->sample_count; ampScale = 1.0/(stepLine*stepSample); // Generate metadata for single-look images outMeta = meta_read(masterFile); outMeta->general->data_type = REAL32; // Write metadata for interferometric amplitude outMeta->general->image_data_type = AMPLITUDE_IMAGE; meta_write(outMeta, ampFile); // Write metadata for interferometric phase outMeta->general->image_data_type = PHASE_IMAGE; meta_write(outMeta, phaseFile); /* // Write metadata for interferogram outMeta->general->image_data_type = INTERFEROGRAM; outMeta->general->band_count = 2; strcpy(outMeta->general->bands, "IGRAM-AMP,IGRAM-PHASE"); meta_write(outMeta, igramFile); */ // Generate metadata for multilooked images ml_outMeta = meta_read(masterFile); ml_outMeta->general->data_type = REAL32; ml_outMeta->general->line_count = line_count/stepLine; ml_outMeta->general->sample_count = sample_count/stepSample; ml_outMeta->general->x_pixel_size *= stepSample; ml_outMeta->general->y_pixel_size *= stepLine; ml_outMeta->sar->multilook = 1; ml_outMeta->sar->line_increment *= stepLine; ml_outMeta->sar->sample_increment *= stepSample; // FIXME: This is the wrong increment but create_dem_grid does not know any // better at the moment. //ml_outMeta->sar->line_increment = 1; //ml_outMeta->sar->sample_increment = 1; // Write metadata for multilooked interferometric amplitude ml_outMeta->general->image_data_type = AMPLITUDE_IMAGE; meta_write(ml_outMeta, ml_ampFile); // Write metadata for multilooked interferometric phase ml_outMeta->general->image_data_type = PHASE_IMAGE; meta_write(ml_outMeta, ml_phaseFile); // Write metadata for coherence image ml_outMeta->general->image_data_type = COHERENCE_IMAGE; meta_write(ml_outMeta, cohFile); /* // Write metadata for multilooked interferogram ml_outMeta->general->image_data_type = INTERFEROGRAM; strcpy(ml_outMeta->general->bands, "IGRAM-AMP,IGRAM-PHASE"); ml_outMeta->general->band_count = 2; meta_write(ml_outMeta, ml_igramFile); */ // Allocate memory master = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count*lookLine); slave = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count*lookLine); amp = (float *) MALLOC(sizeof(float)*sample_count*lookLine); phase = (float *) MALLOC(sizeof(float)*sample_count*lookLine); ml_amp = (float *) MALLOC(sizeof(float)*sample_count/stepSample); ml_phase = (float *) MALLOC(sizeof(float)*sample_count/stepSample); coh = (float *) MALLOC(sizeof(float)*sample_count/stepSample); sum_cpx_a = (float *) MALLOC(sizeof(float)*sample_count); sum_cpx_b = (float *) MALLOC(sizeof(float)*sample_count); sum_igram = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count); sum_ml_igram = (complexFloat *) MALLOC(sizeof(complexFloat)*sample_count); // Open files fpMaster = FOPEN(masterFile,"rb"); fpSlave = FOPEN(slaveFile,"rb"); fpAmp = FOPEN(ampFile,"wb"); fpPhase = FOPEN(phaseFile,"wb"); fpAmp_ml = FOPEN(ml_ampFile,"wb"); fpPhase_ml = FOPEN(ml_phaseFile,"wb"); //FILE *fpIgram = FOPEN(igramFile, "wb"); //FILE *fpIgram_ml = FOPEN(ml_igramFile, "wb"); fpCoh = FOPEN(cohFile,"wb"); // Initialize histogram for (count=0; count<HIST_SIZE; count++) hist_val[count] = 0; asfPrintStatus(" Calculating interferogram and coherence ...\n\n"); for (line=0; line<line_count; line+=stepLine) { register int offset, row, column, limitLine; double igram_real, igram_imag; int inCol; limitLine=MIN(lookLine, line_count-line); printf("Percent completed %3.0f\r",(float)line/line_count*100.0); pCoh = coh; // Read in the next lines of data get_complexFloat_lines(fpMaster, inMeta, line, limitLine, master); get_complexFloat_lines(fpSlave, inMeta, line, limitLine, slave); // Add the remaining rows into sum vectors offset = sample_count; for (column=0; column<sample_count; column++) { offset = column; sum_cpx_a[column] = 0.0; sum_cpx_b[column] = 0.0; sum_igram[column].real = 0.0; sum_igram[column].imag = 0.0; sum_ml_igram[column].real = 0.0; sum_ml_igram[column].imag = 0.0; igram_real = 0.0; igram_imag = 0.0; for (row=0; row<limitLine; row++) { // Complex multiplication for interferogram generation igram_real = master[offset].real*slave[offset].real + master[offset].imag*slave[offset].imag; igram_imag = master[offset].imag*slave[offset].real - master[offset].real*slave[offset].imag; amp[offset] = sqrt(igram_real*igram_real + igram_imag*igram_imag); if (FLOAT_EQUIVALENT(igram_real, 0.0) || FLOAT_EQUIVALENT(igram_imag, 0.0)) phase[offset]=0.0; else phase[offset] = atan2(igram_imag, igram_real); sum_cpx_a[column] += AMP(master[offset])*AMP(master[offset]); sum_cpx_b[column] += AMP(slave[offset])*AMP(slave[offset]); sum_igram[column].real += igram_real; sum_igram[column].imag += igram_imag; if (line % stepLine == 0 && row < stepLine) { sum_ml_igram[column].real += igram_real; sum_ml_igram[column].imag += igram_imag; } offset += sample_count; } ml_amp[column] = sqrt(sum_ml_igram[column].real*sum_ml_igram[column].real + sum_ml_igram[column].imag*sum_ml_igram[column].imag)*ampScale; if (FLOAT_EQUIVALENT(sum_ml_igram[column].real, 0.0) || FLOAT_EQUIVALENT(sum_ml_igram[column].imag, 0.0)) ml_phase[column] = 0.0; else ml_phase[column] = atan2(sum_ml_igram[column].imag, sum_ml_igram[column].real); } // Write single-look and multilooked amplitude and phase put_float_lines(fpAmp, outMeta, line, stepLine, amp); put_float_lines(fpPhase, outMeta, line, stepLine, phase); put_float_line(fpAmp_ml, ml_outMeta, line/stepLine, ml_amp); put_float_line(fpPhase_ml, ml_outMeta, line/stepLine, ml_phase); //put_band_float_lines(fpIgram, outMeta, 0, line, stepLine, amp); //put_band_float_lines(fpIgram, outMeta, 1, line, stepLine, phase); //put_band_float_line(fpIgram_ml, ml_outMeta, 0, line/stepLine, ml_amp); //put_band_float_line(fpIgram_ml, ml_outMeta, 1, line/stepLine, ml_phase); // Calculate the coherence by adding from sum vectors for (inCol=0; inCol<sample_count; inCol+=stepSample) { register int limitSample = MIN(lookSample,sample_count-inCol); sum_a = 0.0; sum_b = 0.0; igram_real = 0.0; igram_imag = 0.0; // Step over multilook area and sum output columns for (column=0; column<limitSample; column++) { igram_real += sum_igram[inCol+column].real; igram_imag += sum_igram[inCol+column].imag; sum_a += sum_cpx_a[inCol+column]; sum_b += sum_cpx_b[inCol+column]; } if (FLOAT_EQUIVALENT((sum_a*sum_b), 0.0)) *pCoh = 0.0; else { *pCoh = (float) sqrt(igram_real*igram_real + igram_imag*igram_imag) / sqrt(sum_a * sum_b); if (*pCoh>1.0001) { printf(" coh = %f -- setting to 1.0\n",*pCoh); printf(" You shouldn't have seen this!\n"); printf(" Exiting.\n"); exit(EXIT_FAILURE); *pCoh=1.0; } } pCoh++; } // Write out values for coherence put_float_line(fpCoh, ml_outMeta, line/stepLine, coh); // Keep filling coherence histogram for (count=0; count<sample_count/stepSample; count++) { register int tmp; tmp = (int) (coh[count]*HIST_SIZE); /* Figure out which bin this value is in */ /* This shouldn't happen */ if(tmp >= HIST_SIZE) tmp = HIST_SIZE-1; if(tmp < 0) tmp = 0; hist_val[tmp]++; // Increment that bin for the histogram hist_sum += coh[count]; // Add up the values for the sum hist_cnt++; // Keep track of the total number of values if (coh[count]>max) max = coh[count]; // Calculate maximum coherence } } // End for line printf("Percent completed %3.0f\n",(float)line/line_count*100.0); // Sum and print the statistics percent_sum = 0.0; printf(" Coherence : Occurrences : Percent\n"); printf(" ---------------------------------------\n"); for (count=0; count<HIST_SIZE; count++) { bin_low = (float)(count)/(float)HIST_SIZE; bin_high = (float)(count+1)/(float)HIST_SIZE; percent = (double)hist_val[count]/(double)hist_cnt; percent_sum += (float)100*percent; printf(" %.2f -> %.2f : %.8lld %2.3f \n", bin_low,bin_high, (long long) hist_val[count],100*percent); } *average = (float)hist_sum/(float)hist_cnt; printf(" ---------------------------------------\n"); printf(" Maximum Coherence: %.3f\n", max); printf(" Average Coherence: %.3f (%.1f / %lld) %f\n", *average,hist_sum, hist_cnt, percent_sum); // Free and exit FREE(master); FREE(slave); FREE(amp); FREE(phase); FREE(ml_amp); FREE(ml_phase); FREE(coh); FCLOSE(fpMaster); FCLOSE(fpSlave); FCLOSE(fpAmp); FCLOSE(fpPhase); FCLOSE(fpAmp_ml); FCLOSE(fpPhase_ml); //FCLOSE(fpIgram); //FCLOSE(fpIgram_ml); FCLOSE(fpCoh); meta_free(inMeta); meta_free(outMeta); meta_free(ml_outMeta); return(0); }