static void get_asf_line(ReadAsfClientInfo *info, meta_parameters *meta, int row, float *buf) { // wrapper for get_float_line() that multilooks if needed if (info->ml) { assert(meta->sar); int k,j,nlooks = meta->sar->azimuth_look_count; row *= nlooks; // we fudged the line count in the metadata for the // viewer (which is displaying a multilooked image), we must // put the correct value back for the reader int lc = meta->general->line_count; meta->general->line_count = g_saved_line_count; // FIXME: figure a nice way to avoid allocating every time we read a line get_float_line(info->fp, meta, row, buf); float *tmp = MALLOC(sizeof(float)*meta->general->sample_count); for (k=1; k<nlooks; ++k) { get_float_line(info->fp, meta, row+k, tmp); for (j=0; j<meta->general->sample_count; ++j) buf[j] += tmp[j]; } for (j=0; j<meta->general->sample_count; ++j) buf[j] /= nlooks; free(tmp); meta->general->line_count = lc; } else { // no multilooking case get_float_line(info->fp, meta, row, buf); } }
static void get_uavsar_line(ReadUavsarClientInfo *info, meta_parameters *meta, int row, float *buf) { // wrapper for get_float_line() that multilooks if needed int j,ns=meta->general->sample_count; if (info->ml) { assert(meta->sar); int k,nlooks = meta->sar->azimuth_look_count; row *= nlooks; // we fudged the line count in the metadata for the // viewer (which is displaying a multilooked image), we must // put the correct value back for the reader int lc = meta->general->line_count; meta->general->line_count = g_saved_line_count; // FIXME: figure a nice way to avoid allocating every time we read a line get_float_line(info->fp, meta, row, buf); float *tmp = MALLOC(sizeof(float)*meta->general->sample_count); for (k=1; k<nlooks; ++k) { get_float_line(info->fp, meta, row+k, tmp); for (j=0; j<ns; ++j) ieee_big32(tmp[j]); for (j=0; j<ns; ++j) buf[j] += tmp[j]; } for (j=0; j<ns; ++j) buf[j] /= nlooks; free(tmp); // restore fudged value meta->general->line_count = lc; } else { // no multilooking case if (info->is_complex) { complexFloat *cf_buf = MALLOC(sizeof(complexFloat)*ns); get_complexFloat_line(info->fp, meta, row, cf_buf); for (j=0; j<ns; ++j) { ieee_big32(cf_buf[j].real); ieee_big32(cf_buf[j].imag); buf[j] = hypot(cf_buf[j].real, cf_buf[j].imag); //buf[j] = atan2_check(cf_buf[j].imag, cf_buf[j].real); } FREE(cf_buf); } else { get_float_line(info->fp, meta, row, buf); for (j=0; j<ns; ++j) ieee_big32(buf[j]); } } }
void calc_minmax_polsarpro(const char *inFile, double *min, double *max) { int ii,jj; *min = 999999; *max = -999999; char *enviName = (char *) MALLOC(sizeof(char)*(strlen(inFile) + 10)); sprintf(enviName, "%s.hdr", inFile); envi_header *envi = read_envi(enviName); meta_parameters *meta = envi2meta(envi); float *data = MALLOC(sizeof(float) * meta->general->sample_count); FILE *fp = FOPEN(inFile, "rb"); asfPrintStatus("\nCalculating min and max ...\n"); for (ii=0; ii<meta->general->line_count; ++ii) { asfPercentMeter(((double)ii/(double)meta->general->line_count)); get_float_line(fp, meta, ii, data); for (jj=0; jj<meta->general->sample_count; ++jj) { ieee_big32(data[jj]); if (data[jj] < *min) *min = data[jj]; if (data[jj] > *max) *max = data[jj]; } } asfPercentMeter(1.0); FCLOSE(fp); FREE(data); meta_free(meta); FREE(envi); FREE(enviName); }
int main(int argc, char *argv[]) { // Allocate some memory char *inFile = (char *) MALLOC(sizeof(char)*512); char *outFile = (char *) MALLOC(sizeof(char)*512); // Parse command line if (argc < 3) { printf("Insufficient arguments.\n"); usage(argv[0]); } strcpy(inFile, argv[1]); strcpy(outFile, argv[2]); int grid_line_count = atoi(argv[3]); asfSplashScreen (argc, argv); // Deal with metadata meta_parameters *metaIn = meta_read(inFile); meta_parameters *metaOut = meta_read(inFile); int nl = metaIn->general->line_count; int ns = metaIn->general->sample_count; metaOut->general->data_type = ASF_BYTE; meta_write(metaOut, outFile); // Replace image with grid float on_grid = 0.0; float off_grid = 255.0; float *outLine = (float *) MALLOC(sizeof(float)*ns); float *inLine = (float *) MALLOC(sizeof(float)*ns); FILE *fpIn = FOPEN(appendExt(inFile, ".img"), "rb"); FILE *fpOut = FOPEN(appendExt(outFile, ".img"), "wb"); int ii, kk;; for (ii=0; ii<nl; ii++) { get_float_line(fpIn, metaIn, ii, inLine); for (kk=0; kk<ns; kk++) { if (ii == 0 || ii == nl -1 || ii % (ns/grid_line_count) == 0) outLine[kk] = on_grid; else if (kk % (ns/grid_line_count) == 0) outLine[kk] = on_grid; else outLine[kk] = off_grid; } outLine[0] = outLine[ns-1] = on_grid; put_float_line(fpOut, metaOut, ii, outLine); asfLineMeter(ii, nl); } // Clean up FREE(inFile); FREE(outFile); meta_free(metaIn); meta_free(metaOut); exit(0); }
static void get_asf_lines(ReadAsfClientInfo *info, meta_parameters *meta, int row, int n, float *buf) { // wrapper for get_float_line() that multilooks if needed if (info->ml) { assert(meta->sar); int i,j,k; int nlooks = meta->sar->azimuth_look_count; int ns = meta->general->sample_count; row *= nlooks; // we fudged the line count in the metadata for the // viewer (which is displaying a multilooked image), we must // put the correct value back for the reader int lc = meta->general->line_count; meta->general->line_count = g_saved_line_count; float *tmp = MALLOC(sizeof(float)*ns); for (i=0; i<n; ++i) { float *this_row = buf + i*ns; get_float_line(info->fp, meta, row+i*nlooks, this_row); int n_read = nlooks; for (k=1; k<nlooks; ++k) { if (row+n*nlooks+k >= meta->general->line_count) { --n_read; } else { get_float_line(info->fp, meta, row+i*nlooks+k, tmp); for (j=0; j<meta->general->sample_count; ++j) this_row[j] += tmp[j]; } } for (j=0; j<meta->general->sample_count; ++j) this_row[j] /= n_read; } free(tmp); meta->general->line_count = lc; } else { // no multilooking case get_float_lines(info->fp, meta, row, n, buf); } }
static void add_pixels(FloatImage *out, char *file, double start_x, double start_y, double per_x, double per_y) { meta_parameters *meta = meta_read(file); if (!meta) { asfPrintError("Couldn't read metadata for: %s!\n", file); } // figure out where in the giant image these pixels will go int start_line, start_sample; // this should work even if per_x / per_y are negative... start_sample = (int) ((meta->projection->startX - start_x) / per_x + .5); start_line = (int) ((meta->projection->startY - start_y) / per_y + .5); int ns = meta->general->sample_count; int nl = meta->general->line_count; asfPrintStatus(" Location in combined is S:%d-%d, L:%d-%d\n", start_sample, start_sample + ns, start_line, start_line + nl); if (start_sample + ns > out->size_x || start_line + nl > out->size_y) { asfPrintError("Image extents were not calculated correctly!\n"); } FILE *img = fopenImage(file, "rb"); if (!img) { asfPrintError("Couldn't open image file: %s!\n", file); } float *line = MALLOC(sizeof(float)*ns); int y; for (y=0; y<nl; ++y) { get_float_line(img, meta, y, line); int x; for (x=0; x<ns; ++x) { float v = line[x]; // don't write out "no data" values if (v != meta->general->no_data) float_image_set_pixel(out, x + start_sample, y + start_line, v); } asfLineMeter(y, nl); } fclose(img); free(line); meta_free(meta); }
/* readImg: reads the image file given by in into the (nl x ns) float array dest. Reads a total of (delY x delX) pixels into topleft corner of dest, starting at (startY , startX) in the input file. */ static void readImage(FILE *in,meta_parameters *meta, int startX,int startY,int delX,int delY, float add,float *sum, float *dest, int nl, int ns) { float *inBuf=(float *)MALLOC(sizeof(float)*(meta->general->sample_count)); register int x,y,l; double tempSum=0; // We've had some problems matching images with some extremely large // or NaN values. If only some pixels in the image have these values, // we should still be able to match. // Hard to say what a "crazy big" value would be... // We'll make the maximum allowed value MAXFLOAT (the maximum single // precision floating point number), divided by the number of pixels. const double maxval = ((double)MAXFLOAT) / ((double)ns*nl); /*Read portion of input image into topleft of dest array.*/ for (y=0;y<delY;y++) { l=ns*y; get_float_line(in,meta,startY+y,inBuf); if (sum==NULL) { for (x=0;x<delX;x++) { if (fabs(inBuf[startX+x]) < maxval && meta_is_valid_double(inBuf[startX+x])) { dest[l+x]=inBuf[startX+x]+add; } } } else { for (x=0;x<delX;x++) { if (fabs(inBuf[startX+x]) < maxval && meta_is_valid_double(inBuf[startX+x])) { tempSum+=inBuf[startX+x]; dest[l+x]=inBuf[startX+x]+add; } } } for (x=delX;x<ns;x++) { dest[l+x]=0.0; /*Fill rest of line with zeros.*/ } } /*Fill remainder of array (bottom portion) with zero lines.*/ for (y=delY;y<nl;y++) { l=ns*y; for (x=0;x<ns;x++) { dest[l+x]=0.0; /*Fill rest of in2 with zeros.*/ } } if (sum!=NULL) { *sum=(float)tempSum; } FREE(inBuf); }
/* Estimate mean and standard deviation of an image by taking regular sampling points and doing the math with those. A mask value can be defined that is excluded from this calculation. If no mask value is supposed to be used, pass the mask value as NAN. */ void estimate_stats(FILE *fpIn, meta_parameters *meta, int lines, int samples, double mask, double *min, double *max, double *mean, double *stdDev) { float *imgLine = (float *) MALLOC(sizeof(float) * samples); double *stats, sum=0.0, variance=0.0; int ii, kk, line_increment, sample_increment; long pix=0, valid=0; #define grid 100 /* Define the necessary parameters */ stats = (double *) MALLOC(sizeof(double) * grid * grid); line_increment = lines / grid; sample_increment = samples / grid; /* Collect values from sample grid */ for (ii=0; ii<lines; ii+=line_increment) { get_float_line(fpIn, meta, ii, imgLine); for (kk=0; kk<samples; kk+=sample_increment) { if (!ISNAN(mask)) { if (FLOAT_EQUIVALENT(imgLine[kk], mask)) stats[pix] = NAN; else { stats[pix] = imgLine[kk]; valid++; } } else { stats[pix] = imgLine[kk]; valid++; } pix++; } } FSEEK64(fpIn, 0, 0); /* Estimate min, max, mean and standard deviation */ *min = 99999; *max = -99999; for (ii=0; ii<grid*grid; ii++) if (!ISNAN(stats[ii])) { if (stats[ii] < *min) *min = stats[ii]; if (stats[ii] > *max) *max = stats[ii]; sum += stats[ii]; } *mean = sum / valid; for (ii=0; ii<grid*grid; ii++) if (!ISNAN(stats[ii])) variance += (stats[ii]-*mean) * (stats[ii]-*mean); *stdDev = sqrt(variance / (valid-1)); return; }
int dem_to_mask(char *inDemFile, char *outMaskFile, float cutoff) { meta_parameters *inDemMeta = meta_read(inDemFile); meta_parameters *outDemMeta = meta_read(inDemFile); // out metadata will differ from in only in the data type outDemMeta->general->data_type = ASF_BYTE; int x_size = inDemMeta->general->sample_count; int y_size = inDemMeta->general->line_count; float *maskbuffer = MALLOC(sizeof(float) * x_size); float *floatbuffer = MALLOC(sizeof(float) * x_size); FILE *in = fopenImage(inDemFile, "rb"); FILE *out = fopenImage(outMaskFile, "wb"); float mv = masked_value(); float umv = unmasked_value(); int y,x; for (y=0; y<y_size; y++) { get_float_line(in, inDemMeta, y, floatbuffer); for (x=0; x < x_size; x++) maskbuffer[x] = floatbuffer[x] <= cutoff ? mv : umv; put_float_line(out, outDemMeta, y, maskbuffer); asfLineMeter(y, y_size); } FCLOSE(in); FCLOSE(out); FREE(floatbuffer); FREE(maskbuffer); meta_write(outDemMeta, outMaskFile); meta_free(inDemMeta); meta_free(outDemMeta); asfPrintStatus("Created Mask file '%s' from DEM '%s'.\n", outMaskFile, inDemFile); return 0; }
static float * read_dem(meta_parameters *meta_dem, const char *demImg) { int ns = meta_dem->general->sample_count; int nl = meta_dem->general->line_count; float *demData = MALLOC(sizeof(float)*ns*nl); FILE *fp = FOPEN(demImg, "rb"); int ii; for (ii=0; ii<nl; ++ii) { get_float_line(fp, meta_dem, ii, demData + ii*ns); asfLineMeter(ii,nl); } FCLOSE(fp); return demData; }
END_TEST START_TEST(test_get_float_line_from_real_star_8) { meta_parameters *meta = meta_read(REAL_STAR_8_META_FILE); FILE *image_file_p = FOPEN(REAL_STAR_8_IMG_FILE, "r"); /* Destination for data read from test file. */ float *dest = MALLOC(meta->general->sample_count * sizeof(float)); int idx; /* Index for samples. */ get_float_line(image_file_p, meta, TEST_LINE_NUMBER, dest); /* Check line data against its expected values. */ for ( idx = 0 ; idx < meta->general->sample_count ; idx++ ) fail_unless(UNIT_TESTS_FLOAT_COMPARE(dest[idx], FIRST_FLOAT_SAMPLE_TEST_VALUE + idx), "unexpected floating point value in fetched line data"); meta_free(meta); FCLOSE(image_file_p); }
void deskew(const char *infile, const char *outfile) { meta_parameters *meta = meta_read(infile); int nl = meta->general->line_count; int np = meta->general->sample_count; int nb = meta->general->band_count; char **band_name = extract_band_names(meta->general->bands, nb); int band, line, samp, deskewed = meta->sar->deskewed != 0; if (!meta->sar) asfPrintError("Cannot deskew data without a sar block!\n"); char *tmp_outfile; int do_rename = FALSE; if (strcmp(infile, outfile) == 0 && nb>1) { // user wants to deskew in-place // we can't actually do that on multi-band data, too much to keep in memory // use a temporary file, then clobber input file tmp_outfile = appendToBasename(outfile, "_tmp"); do_rename = TRUE; } else { // normal case: either // 1) single-band in-place deskew // 2) not in-place deskew (single or multi) tmp_outfile = STRDUP(outfile); } // calculate the amount of shift necessary double fac = calc_shift(meta, 0, 0); // Not sure if we need this or not... //fac *= meta->general->x_pixel_size / meta->general->y_pixel_size; // the "lower" array stores the required shifts, indexed by column // (the amount of shift is row-independent) int *lower = MALLOC(np * sizeof(int)); for (samp=0; samp<np; ++samp) lower[samp] = (int) floor(fac*(double)samp); if (meta->sar->deskewed) { asfPrintStatus("Data is already deskewed.\n"); } else { asfPrintStatus("Far-range shift amount: "); if (lower[np-1] > 0) asfPrintStatus("%d pixels down.\n", lower[np-1]); else asfPrintStatus("%d pixels up.\n", -lower[np-1]); } float *ibuf = MALLOC(np * sizeof(float)); float *obuf = CALLOC(np*nl, sizeof(float)); FILE *fpi = fopenImage(infile, "rb"); for (band=0; band<nb; ++band) { if (nb>1) asfPrintStatus("Deskewing band: %s\n", band_name[band]); // apply deskewing to this band for (line=0; line<nl; ++line) { get_float_line(fpi, meta, line + nl*band, ibuf); for (samp=0; samp<np; ++samp) { int out_line = deskewed ? line : line + lower[samp]; if (out_line >= 0 && out_line < nl) obuf[out_line*np+samp] = ibuf[samp]; } asfLineMeter(line,nl); } // write out this band FILE *fpo = fopenImage(tmp_outfile, band>0 ? "ab" : "wb"); put_float_lines(fpo, meta, band*nl, nl, obuf); FCLOSE(fpo); } FCLOSE(fpi); FREE(obuf); FREE(ibuf); FREE(lower); // if we output to a temporary file, clobber the input if (do_rename) { char *tmp_outfile_img = appendExt(tmp_outfile, ".img"); char *outfile_img = appendExt(outfile, ".img"); //printf("Renaming: %s -> %s\n", tmp_outfile_img, outfile_img); rename(tmp_outfile_img, outfile_img); FREE(tmp_outfile_img); FREE(outfile_img); } FREE(tmp_outfile); // only need to update the deskewed flag in the metadata meta->sar->deskewed = 1; meta_write(meta, outfile); meta_free(meta); }
void asf_airsar_import(char *inFile, char *outFile, int insar, int polar) { airsar_header *header = NULL; meta_parameters *metaIn = NULL, *metaOut = NULL; FILE *fpIn, *fpOut; float *floatBuf; char dataName[1024], *airsar_basename=NULL; int ii, kk, create=TRUE, line_count; int dem=FALSE, amp=FALSE, coh=FALSE; long line_offset; // First check for the existence of the input file. In this case we ingest // a single AirSAR file and ignore any other option that is passed in. if (fileExists(inFile) && strstr(inFile, "_meta.airsar") == NULL) { // Check what kind of data it is if (strstr(inFile, ".demi2")) dem = TRUE; else if (strstr(inFile, ".vvi2")) amp = TRUE; else if (strstr(inFile, ".corgr")) coh = TRUE; // FIX ME: Does not deal with polarimetric data yet header = read_airsar_header(inFile); metaIn = import_airsar_meta(inFile, airsar_basename, TRUE); line_offset = header->first_data_offset/metaIn->general->sample_count/2; metaIn->general->line_count += line_offset; metaOut = import_airsar_meta(inFile, airsar_basename, TRUE); // Assign appropriate data type if (dem || amp) metaIn->general->data_type = INTEGER16; else metaIn->general->data_type = ASF_BYTE; metaOut->general->data_type = REAL32; floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count); fpIn = FOPEN(inFile, "rb"); append_ext_if_needed(outFile, ".img", NULL); fpOut = FOPEN(outFile, "wb"); for (ii=0; ii<metaOut->general->line_count; ii++) { // Interferometric data can be read using get_float_line if (dem || amp || coh) get_float_line(fpIn, metaIn, ii+line_offset, floatBuf); // DEM needs some additional treatment if (dem) { for (kk=0; kk<metaIn->general->sample_count; kk++) floatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment + metaIn->airsar->elevation_offset; } // Writing away should work the same way put_float_line(fpOut, metaOut, ii, floatBuf); asfLineMeter(ii, metaOut->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); if (dem) { metaOut->general->image_data_type = DEM; strcpy(metaOut->general->bands, "DEM"); } else if (amp) { metaOut->general->image_data_type = AMPLITUDE_IMAGE; strcpy(metaOut->general->bands, "AMPLITUDE"); } else if (coh) { metaOut->general->image_data_type = COHERENCE_IMAGE; strcpy(metaOut->general->bands, "COHERENCE"); } meta_write(metaOut, outFile); } // Take care of interferometric layer stack else if (insar) { // Check for DEM sprintf(dataName, "%s.demi2", inFile); if (!fileExists(dataName)) asfPrintError("Could not find DEM (%s)\nDEM is required for reliable" "geometry and geolocation\n", dataName); else { printf("Ingesting DEM (%s) ...\n", dataName); metaIn = import_airsar_meta(dataName, inFile, TRUE); line_count = metaIn->general->line_count; ingest_insar_data(dataName, inFile, "DEM", sizeof(short), line_count, outFile, create); create = FALSE; } // Check for amplitude image sprintf(dataName, "%s.vvi2", inFile); if (!fileExists(dataName)) asfPrintWarning("Could not find amplitude image (%s)\n", dataName); else { printf("Ingesting amplitude image (%s) ...\n", dataName); ingest_insar_data(dataName, inFile, "AMPLITUDE", sizeof(short), line_count, outFile, create); create = FALSE; } // Check for coherence image sprintf(dataName, "%s.corgr", inFile); if (!fileExists(dataName)) asfPrintWarning("Could not find coherence image (%s)\n", dataName); else { printf("Ingesting coherence image (%s) ...\n", dataName); ingest_insar_data(dataName, inFile, "COHERENCE", sizeof(char), line_count, outFile, create); create = FALSE; } } // Take care of polarimetric layer stack // We will just put all available power images into a multiband image else if (polar) { // Check for C-band data sprintf(dataName, "%s_c.datgr", inFile); if (!fileExists(dataName)) sprintf(dataName, "%s_c.dat", inFile); if (!fileExists(dataName)) asfPrintWarning("Could not find polarimetric data set (%s)\n", dataName); else { printf("Ingesting C band data (%s) ...\n", dataName); ingest_polarimetry_data(dataName, inFile, outFile, 'C', create); create = FALSE; } // Check for L-band data sprintf(dataName, "%s_l.datgr", inFile); if (!fileExists(dataName)) sprintf(dataName, "%s_l.dat", inFile); if (!fileExists(dataName)) asfPrintWarning("Could not find polarimetric data set (%s)\n", dataName); else { printf("Ingesting L band data (%s) ...\n", dataName); ingest_polarimetry_data(dataName, inFile, outFile, 'L', create); create = FALSE; } // Check for P-band data sprintf(dataName, "%s_p.datgr", inFile); if (!fileExists(dataName)) sprintf(dataName, "%s_p.dat", inFile); if (!fileExists(dataName)) asfPrintWarning("Could not find polarimetric data set (%s)\n", dataName); else { printf("Ingesting P band data (%s) ...\n", dataName); ingest_polarimetry_data(dataName, inFile, outFile, 'P', create); create = FALSE; } } // Regular ingest else import_airsar(inFile, r_AMP, outFile); // Clean up time if (metaIn) meta_free(metaIn); if (metaOut) meta_free(metaOut); }
/* Create histogram of the data and get the summation of the * square of (sample-mean) to use in calculation of rmse & stdev */ stat_parameters calc_hist(stat_parameters stats, char *sar_name, int band, meta_parameters *meta, double sum_of_samples, long samples_counted, int mask_flag) { FILE *fp; long start_line, start_sample, window_height, window_width; long percent_complete, line, sample, ii, band_offset; double diff_squared_sum=0.0; float *data_line; start_line = stats.upper_left_line; start_sample = stats.upper_left_samp; window_height = stats.lower_right_line - start_line; window_width = stats.lower_right_samp - start_sample; data_line = (float *)MALLOC(sizeof(float)*meta->general->sample_count); fp = FOPEN(sar_name, "r"); /* Initialize the histogram array */ for (ii=0; ii<256; ii++) stats.histogram[ii] = 0; if (meta->general->data_type != ASF_BYTE) { /* Set slope and offset, to map pixels to [0..255]. * byte = slope * in + offset * 0 = slope * min + offset * 255 = slope * max + offset * Therefore: */ stats.slope = 255.0 / (stats.max-stats.min); stats.offset = -stats.slope * stats.min; } /* Get histogram of the data. If its byte data just slap it into the * histogram; otherwise use slope & offset to scale the data */ stats.mean = sum_of_samples / (double)samples_counted; percent_complete=0; band_offset = band * meta->general->line_count; for (line=start_line+band_offset; line<start_line+window_height+band_offset; line++) { if (!quietflag) asfPercentMeter((float)(line-start_line-band_offset)/(float)(window_height-start_line)); get_float_line(fp, meta, line, data_line); for (sample=start_sample; sample<start_sample+window_width; sample++) { int bin = (meta->general->data_type == ASF_BYTE) ? (int)data_line[sample] : (int)(stats.slope*data_line[sample]+stats.offset); if (bin < 0) bin = 0; else if (bin > 255) bin = 255; if ( mask_flag && FLOAT_EQUIVALENT(data_line[sample],stats.mask) ) continue; stats.histogram[bin]++; diff_squared_sum += SQR(data_line[sample] - stats.mean); } } if (!quietflag) asfPercentMeter(1.0); FREE(data_line); FCLOSE(fp); /* Populate stats structure */ stats.rmse = sqrt( fabs( diff_squared_sum / (double)samples_counted ) ); stats.std_deviation = sqrt( fabs( diff_squared_sum / (double)(samples_counted-1) ) ); return stats; }
int main(int argc, char **argv) { double min, max; /* Minimum & maximum sample values */ double sum_of_samples=0.0; /* Sum of all samples accounted for */ double sum_of_squared_samples=0.0; /* Sum of all squared samples accounted for*/ double trim_fraction; /* Fraction used to trim the histogram */ int ii; /* Loop index */ long samples_counted=0; /* Number of all samples accounted for */ float *data_line; /* Buffer for a line of samples */ long line, sample; /* Line and sample indices */ long num_lines, num_samples; /* Number of lines and samples */ int percent_complete=0; /* Percent of data sweep completed */ int overmeta_flag=FALSE; /* If TRUE write over current .meta file */ int overstat_flag=FALSE; /* If TRUE write over current .stat file */ int nometa_flag=FALSE; /* If TRUE do not write .meta file */ int nostat_flag=FALSE; /* If TRUE do not write .stat file */ int mask_flag=FALSE; /* TRUE if user specifies a mask value */ int trim_flag=FALSE; /* If TRUE trim histogram */ double mask=NAN; /* Value to ignore while caculating stats*/ char meta_name[261]; /* Meta file name */ meta_parameters *meta; /* SAR meta data structure */ char sar_name[256]; /* SAR file name WITH extention */ FILE *sar_file; /* SAR data file pointer to take stats on*/ stat_parameters *stats; /* Statistics structure */ char stat_name[261]; /* Stats file name */ extern int currArg; /* Pre-initialized to 1 */ /* We initialize these to a magic number for checking. */ long start_line = -1; /* Window starting line. */ long start_sample = -1; /* Window starting sample. */ long window_height = -1; /* Window height in lines. */ long window_width = -1; /* Window width in samples. */ /* parse command line */ handle_license_and_version_args(argc, argv, "stats"); logflag=quietflag=FALSE; while (currArg < (argc-1)) { char *key = argv[currArg++]; if (strmatch(key,"-quiet")) { quietflag=TRUE; } else if (strmatch(key,"-log")) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag=TRUE; } else if (strmatch(key,"-mask")) { CHECK_ARG(1); mask = atof(GET_ARG(1)); mask_flag=TRUE; } else if (strmatch(key,"-overmeta")) { overmeta_flag=TRUE; } else if (strmatch(key,"-overstat")) { overstat_flag=TRUE; } else if (strmatch(key,"-nometa")) { nometa_flag=TRUE; } else if (strmatch(key,"-nostat")) { nostat_flag=TRUE; } else if (strmatch(key,"-startline")) { CHECK_ARG(1); nometa_flag=TRUE; /* Implied. */ start_line = atol(GET_ARG(1)); if ( start_line < 0 ) { printf("error: -startline argument must be greater than or equal to zero\n"); usage(argv[0]); } } else if (strmatch(key,"-startsample")) { CHECK_ARG(1); nometa_flag=TRUE; /* Implied. */ start_sample = atol(GET_ARG(1)); if ( start_sample < 0 ) { printf("error: -startsample argument must be greater than or equal to zero\n"); usage(argv[0]); } } else if (strmatch(key,"-width")) { CHECK_ARG(1); nometa_flag=TRUE; /* Implied. */ window_width = atol(GET_ARG(1)); if ( window_width < 0 ) { printf("error: -width argument must be greater than or equal to zero\n"); usage(argv[0]); } } else if (strmatch(key,"-height")) { CHECK_ARG(1); nometa_flag=TRUE; /* Implied. */ window_height = atol(GET_ARG(1)); if ( window_height < 0 ) { printf("error: -height argument must be greater than or equal to zero\n"); usage(argv[0]); } } else if (strmatch(key,"-trim")) { CHECK_ARG(1); trim_flag=TRUE; /* Implied. */ trim_fraction = atof(GET_ARG(1)); } else {printf( "\n**Invalid option: %s\n",argv[currArg-1]); usage(argv[0]);} } if ((argc-currArg)<1) {printf("Insufficient arguments.\n"); usage(argv[0]);} strcpy (sar_name, argv[currArg]); char *ext = findExt(sar_name); if (ext == NULL || strcmp("IMG", uc(ext)) != 0) { strcpy(sar_name, appendExt(sar_name, ".img")); } create_name(meta_name, sar_name, ".meta"); create_name(stat_name, sar_name, ".stat"); printf("\nProgram: stats\n\n"); if (logflag) { fprintf(fLog, "\nProgram: stats\n\n"); } printf("\nCalculating statistics for %s\n\n", sar_name); if (logflag) { fprintf(fLog,"\nCalculating statistics for %s\n\n", sar_name); } meta = meta_read(meta_name); num_lines = meta->general->line_count; num_samples = meta->general->sample_count; if ( start_line == -1 ) start_line = 0; if ( start_line > num_lines ) { printf("error: -startline argument is larger than index of last line in image\n"); exit(EXIT_FAILURE); } if ( start_sample == -1 ) start_sample = 0; if ( start_sample > num_samples ) { printf("error: -startsample argument is larger than index of last sample in image\n"); exit(EXIT_FAILURE); } if ( window_height == -1 ) window_height = num_lines; if ( start_line + window_height > num_lines ) { printf("warning: window specified with -startline, -height options doesn't fit in image\n"); } if ( window_width == -1 ) window_width = num_samples; if ( start_sample + window_width > num_samples ) { printf("warning: window specified with -startsample, -width options doesn't fit in image\n"); } /* Make sure we don't over write any files that we don't want to */ if (meta->stats && !overmeta_flag && !nometa_flag) { printf(" ** The meta file already has a populated statistics structure.\n" " ** If you want to run this program and replace that structure,\n" " ** then use the -overmeta option to do so. If you want to run\n" " ** this program, but don't want to replace the structure, use\n" " ** the -nometa option.\n"); if (logflag) { fprintf(fLog, " ** The meta file already has a populated statistics structure.\n" " ** If you want to run this program and replace that structure,\n" " ** then use the -overmeta option to do so. If you want to run\n" " ** this program, but don't want to replace the structure, use\n" " ** the -nometa option.\n"); } exit(EXIT_FAILURE); } if (fileExists(stat_name) && !overstat_flag && !nostat_flag) { printf(" ** The file, %s, already exists. If you want to\n" " ** overwrite it, then use the -overstat option to do so.\n" " ** If you want to run the progam but don't want to write\n" " ** over the current file, then use the -nostat option.\n", stat_name); if (logflag) { fprintf(fLog, " ** The file, %s, already exists. If you want to\n" " ** overwrite it, then use the -overstat option to do so.\n" " ** If you want to run the progam but don't want to write\n" " ** over the current file, then use the -nostat option.\n", stat_name); } exit(EXIT_FAILURE); } /* Let user know the window in which the stats will be taken */ if ((start_line!=0) || (start_sample!=0) || (window_height!=num_lines) || (window_width!=num_samples)) { if (!quietflag) { printf("Taking statistics on a window with upper left corner (%ld,%ld)\n" " and lower right corner (%ld,%ld)\n", start_sample, start_line, window_width+start_sample, window_height+start_line); } if (logflag && !quietflag) { fprintf(fLog, "Taking statistics on a window with upper left corner (%ld,%ld)\n" " and lower right corner (%ld,%ld)\n", start_sample, start_line, window_width+start_sample, window_height+start_line); } } /* Allocate line buffer */ data_line = (float *)MALLOC(sizeof(float)*num_samples); if (meta->stats) FREE(meta->stats); if (meta->general->band_count <= 0) { printf(" ** Band count in the existing data is missing or less than zero.\nDefaulting to one band.\n"); if (logflag) { fprintf(fLog, " ** Band count in the existing data is missing or less than zero.\nDefaulting to one band.\n"); } meta->general->band_count = 1; } meta->stats = meta_statistics_init(meta->general->band_count); if (!meta->stats) { printf(" ** Cannot allocate memory for statistics data structures.\n"); if (logflag) { fprintf(fLog, " ** Cannot allocate memory for statistics data structures.\n"); } exit(EXIT_FAILURE); } stats = (stat_parameters *)MALLOC(sizeof(stat_parameters) * meta->stats->band_count); if (!stats) { printf(" ** Cannot allocate memory for statistics data structures.\n"); if (logflag) { fprintf(fLog, " ** Cannot allocate memory for statistics data structures.\n"); } exit(EXIT_FAILURE); } int band; long band_offset; for (band = 0; band < meta->stats->band_count; band++) { /* Find min, max, and mean values */ if (!quietflag) printf("\n"); if (logflag && !quietflag) fprintf(fLog,"\n"); min = 100000000; max = -100000000; sum_of_samples=0.0; sum_of_squared_samples=0.0; percent_complete=0; band_offset = band * meta->general->line_count; sar_file = FOPEN(sar_name, "r"); for (line=start_line+band_offset; line<start_line+window_height+band_offset; line++) { if (!quietflag) asfPercentMeter((float)(line-start_line-band_offset)/(float)(window_height-start_line)); get_float_line(sar_file, meta, line, data_line); for (sample=start_sample; sample<start_sample+window_width; sample++) { if ( mask_flag && FLOAT_EQUIVALENT(data_line[sample],mask) ) continue; if (data_line[sample] < min) min=data_line[sample]; if (data_line[sample] > max) max=data_line[sample]; sum_of_samples += data_line[sample]; sum_of_squared_samples += SQR(data_line[sample]); samples_counted++; } } if (!quietflag) asfPercentMeter(1.0); // if (!quietflag) printf("\rFirst data sweep: 100%% complete.\n"); FCLOSE(sar_file); stats[band].min = min; stats[band].max = max; stats[band].upper_left_line = start_line; stats[band].upper_left_samp = start_sample; stats[band].lower_right_line = start_line + window_height; stats[band].lower_right_samp = start_sample + window_width; stats[band].mask = mask; stats[band] = calc_hist(stats[band], sar_name, band, meta, sum_of_samples, samples_counted, mask_flag); /* Remove outliers and trim the histogram by resetting the minimum and and maximum */ if (trim_flag) { register int sum=0, num_pixels, minDex=0, maxDex=255; double overshoot, width; num_pixels = (int)(samples_counted*trim_fraction); minDex = 0; while (sum < num_pixels) sum += stats[band].histogram[minDex++]; if (minDex-1>=0) overshoot = (double)(num_pixels-sum)/stats[band].histogram[minDex-1]; else overshoot = 0; stats[band].min = (minDex-overshoot-stats[band].offset)/stats[band].slope; sum=0; while (sum < num_pixels) sum += stats[band].histogram[maxDex--]; if (maxDex+1<256) overshoot = (double)(num_pixels-sum)/stats[band].histogram[maxDex+1]; else overshoot = 0; stats[band].max = (maxDex+1+overshoot-stats[band].offset)/stats[band].slope; /* Widening the range for better visual effect */ width = (stats[band].max-stats[band].min)*(1/(1.0-2*trim_fraction)-1); stats[band].min -= width/2; stats[band].max += width/2; /* Couple useful corrections borrowed from SARview */ if ((stats[band].max-stats[band].min) < 0.01*(max-min)) { stats[band].max = max; stats[band].min = min; } if (min == 0.0) stats[band].min=0.0; if (stats[band].min == stats[band].max) stats[band].max = stats[band].min + MICRON; stats[band].slope = 255.0/(stats[band].max-stats[band].min); stats[band].offset = -stats[band].slope*stats[band].min; stats[band] = calc_hist(stats[band], sar_name, band, meta, sum_of_samples, samples_counted, mask_flag); } } if(data_line)FREE(data_line); /* Populate meta->stats structure */ char **band_names = NULL; if (meta_is_valid_string(meta->general->bands) && strlen(meta->general->bands) && meta->general->band_count > 0) { band_names = extract_band_names(meta->general->bands, meta->general->band_count); } else { if (meta->general->band_count <= 0) meta->general->band_count = 1; band_names = (char **) MALLOC (meta->general->band_count * sizeof(char *)); int i; for (i=0; i<meta->general->band_count; i++) { band_names[i] = (char *) MALLOC (64 * sizeof(char)); sprintf(band_names[i], "%02d", i); } } int band_no; for (band_no = 0; band_no < meta->stats->band_count; band_no++) { strcpy(meta->stats->band_stats[band_no].band_id, band_names[band_no]); meta->stats->band_stats[band_no].min = stats[band_no].min; meta->stats->band_stats[band_no].max = stats[band_no].max; meta->stats->band_stats[band_no].mean = stats[band_no].mean; meta->stats->band_stats[band_no].rmse = stats[band_no].rmse; meta->stats->band_stats[band_no].std_deviation = stats[band_no].std_deviation; meta->stats->band_stats[band_no].mask = stats[band_no].mask; } if (band_names) { int i; for (i=0; i<meta->general->band_count; i++) { if (band_names[i]) FREE (band_names[i]); } FREE(band_names); } /* Print findings to the screen (and log file if applicable)*/ if (!quietflag) { printf("\n"); printf("Statistics found:\n"); if (mask_flag) { printf("Used mask %-16.11g\n",mask); } printf("Number of bands: %d\n", meta->stats->band_count); for (band=0; band<meta->stats->band_count; band++) { printf("\n\nBand name = \"%s\"\n", meta->stats->band_stats[band].band_id); printf("Minimum = %-16.11g\n",stats[band].min); printf("Maximum = %-16.11g\n",stats[band].max); printf("Mean = %-16.11g\n",stats[band].mean); printf("Root mean squared error = %-16.11g\n", stats[band].rmse); printf("Standard deviation = %-16.11g\n", stats[band].std_deviation); printf("\n"); printf("Data fit to [0..255] using equation: byte = %g * sample + %g\n", stats[band].slope, stats[band].offset); if (trim_flag) printf("Trimming fraction = %.3g\n", trim_fraction); printf("\n"); printf("Histogram:\n"); for (ii=0; ii<256; ii++) { if (ii%8 == 0) { printf("%s%3i-%3i:", (ii==0) ? "" : "\n", ii, ii+7); } printf(" %8i", stats[band].histogram[ii]); } printf("\n"); } } if (logflag && !quietflag) { fprintf(fLog,"Statistics found:\n"); if (mask_flag) { fprintf(fLog,"Used mask %-16.11g\n",mask); } fprintf(fLog,"Number of bands: %d\n", meta->stats->band_count); for (band=0; band<meta->stats->band_count; band++) { fprintf(fLog,"\n\nBand name = \"%s\"\n", meta->stats->band_stats[band].band_id); fprintf(fLog,"Minimum = %-16.11g\n",stats[band].min); fprintf(fLog,"Maximum = %-16.11g\n",stats[band].max); fprintf(fLog,"Mean = %-16.11g\n",stats[band].mean); fprintf(fLog,"Root mean squared error = %-16.11g\n", stats[band].rmse); fprintf(fLog,"Standard deviation = %-16.11g\n", stats[band].std_deviation); fprintf(fLog,"\n"); fprintf(fLog,"Data fit to [0..255] using equation: byte = %g * sample + %g\n", stats[band].slope, stats[band].offset); if (trim_flag) fprintf(fLog,"Trimming fraction = %.3g\n", trim_fraction); fprintf(fLog,"\n"); fprintf(fLog,"Histogram:\n"); for (ii=0; ii<256; ii++) { if (ii%8 == 0) { fprintf(fLog,"%s%3i-%3i:", (ii==0) ? "" : "\n", ii, ii+7); } fprintf(fLog," %8i", stats[band].histogram[ii]); } fprintf(fLog,"\n"); } } /* Write out .meta and .stat files */ if (!nometa_flag) meta_write(meta, meta_name); if (!nostat_flag) stat_write(stats, stat_name, meta->stats->band_count); /* Free the metadata structure */ meta_free(meta); /* Report */ if (!quietflag) { printf("\n"); printf("Statistics taken on image file %s.\n",sar_name); if (!nometa_flag) printf("Statistics written to the stats block in %s.\n", meta_name); if (!nostat_flag) printf("Statistics plus histogram written to %s.\n", stat_name); printf("\n"); } if (logflag && !quietflag) { fprintf(fLog,"\n"); fprintf(fLog,"Statistics taken on image file '%s'\n",sar_name); if (!nometa_flag) fprintf(fLog,"Statistics written to the stats block in %s\n", meta_name); if (!nostat_flag) fprintf(fLog,"Statistics plus histogram written to %s\n", stat_name); fprintf(fLog,"\n"); } if (fLog) FCLOSE(fLog); return 0; }
int fftMatch_opt(char *inFile1, char *inFile2, float *offsetX, float *offsetY) { // Generate temporary directory char tmpDir[1024]; char metaFile[1024], outFile[1024], sarFile[1024], opticalFile[1024]; char *baseName = get_basename(inFile1); strcpy(tmpDir, baseName); strcat(tmpDir, "-"); strcat(tmpDir, time_stamp_dir()); create_clean_dir(tmpDir); // Cutting optical to SAR extent asfPrintStatus("Cutting optical to SAR extent ...\n"); sprintf(metaFile, "%s.meta", inFile1); sprintf(outFile, "%s%c%s_sub.img", tmpDir, DIR_SEPARATOR, inFile2); trim_to(inFile2, outFile, metaFile); // Clipping optical image including blackfill asfPrintStatus("\nClipping optical image including blackfill ...\n"); meta_parameters *metaOpt = meta_read(outFile); meta_parameters *metaSAR = meta_read(metaFile); int line_count = metaSAR->general->line_count; int sample_count = metaSAR->general->sample_count; float *floatLine = (float *) MALLOC(sizeof(float)*sample_count); unsigned char *byteLine = (unsigned char *) MALLOC(sizeof(char)*sample_count); FILE *fpOptical = FOPEN(outFile, "rb"); sprintf(sarFile, "%s.img", inFile1); FILE *fpSAR = FOPEN(sarFile, "rb"); sprintf(outFile, "%s%c%s_mask.img", tmpDir, DIR_SEPARATOR, inFile2); sprintf(metaFile, "%s%c%s_mask.meta", tmpDir, DIR_SEPARATOR, inFile2); FILE *fpOut = FOPEN(outFile, "wb"); int ii, kk; for (ii=0; ii<line_count; ii++) { get_float_line(fpSAR, metaSAR, ii, floatLine); get_byte_line(fpOptical, metaOpt, ii, byteLine); for (kk=0; kk<sample_count; kk++) { if (!FLOAT_EQUIVALENT(floatLine[kk], 0.0)) floatLine[kk] = (float) byteLine[kk]; } put_float_line(fpOut, metaSAR, ii, floatLine); } FCLOSE(fpOptical); FCLOSE(fpSAR); FCLOSE(fpOut); meta_write(metaSAR, metaFile); // Edge filtering optical image asfPrintStatus("\nEdge filtering optical image ...\n"); sprintf(opticalFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile2); kernel_filter(outFile, opticalFile, SOBEL, 3, 0, 0); // Edge filtering SAR image asfPrintStatus("\nEdge filtering SAR image ...\n"); sprintf(sarFile, "%s%c%s_sobel.img", tmpDir, DIR_SEPARATOR, inFile1); kernel_filter(inFile1, sarFile, SOBEL, 3, 0, 0); // FFT matching on a grid asfPrintStatus("\nFFT matching on a grid ...\n"); float certainty; fftMatch_proj(sarFile, opticalFile, offsetX, offsetY, &certainty); // Clean up remove_dir(tmpDir); return (0); }
/* Main program */ int main(int argc, char *argv[]) { FILE *fpLook=NULL, *fpIncid=NULL, *fpRange=NULL, *fpIn=NULL, *fpMask=NULL; meta_parameters *meta; stateVector stVec; int ii, kk, ll; char inFile[255], metaFile[255], dataFile[255], outLook[255], outIncid[255]; char outRange[255], outBase[255], outFile[255], *maskFile=NULL; char cmd[255], *bufMask=NULL; float *bufImage=NULL, *bufLook=NULL, *bufIncid=NULL, *bufRange=NULL; double latitude, longitude, time, doppler, earth_radius=0, satellite_height, range; double look_angle, incidence_angle, height; double line, sample, re=6378144.0, rp=6356754.9, px, py; double firstLook=0.0, firstIncid=0.0, firstRange=0.0; flag_indices_t flags[NUM_FLAGS]; /* Set all flags to 'not set' */ for (ii=0; ii<NUM_FLAGS; ii++) { flags[ii] = FLAG_NOT_SET; } /**********************BEGIN COMMAND LINE PARSING STUFF**********************/ /* Check to see if any options were provided */ if (checkForOption("-help", argc, argv) != -1) /* Most important */ help_page(); flags[f_LOOK] = checkForOption("-look", argc, argv); flags[f_INCIDENCE] = checkForOption("-incidence", argc, argv); flags[f_RANGE] = checkForOption("-range", argc, argv); flags[f_LINE] = checkForOption("-line", argc, argv); flags[f_SAMPLE] = checkForOption("-sample", argc, argv); flags[f_MIN] = checkForOption("-min", argc, argv); flags[f_MAX] = checkForOption("-max", argc, argv); flags[f_BINS] = checkForOption("-bins", argc, argv); flags[f_INTERVAL] = checkForOption("-interval", argc, argv); /* Make sure to set log & quiet flags (for use in our libraries) */ logflag = (flags[f_LOG]!=FLAG_NOT_SET) ? TRUE : FALSE; quietflag = (flags[f_QUIET]!=FLAG_NOT_SET) ? TRUE : FALSE; { /* We need to make sure the user specified the proper number of arguments */ int needed_args = 4;/*command & in_base & out_base */ if (flags[f_MIN] != FLAG_NOT_SET) needed_args += 2; /* option & value */ if (flags[f_MAX] != FLAG_NOT_SET) needed_args += 2; /* option & value */ if (flags[f_BINS] != FLAG_NOT_SET) needed_args += 2; /* option & value */ if (flags[f_INTERVAL] != FLAG_NOT_SET) needed_args += 2; /* option & value */ /*Make sure we have enough arguments*/ if (argc != needed_args) usage();/*This exits with a failure*/ } /* We must be close to good enough at this point...start filling in fields as needed */ if (flags[f_MIN] != FLAG_NOT_SET) min = atof(argv[flags[f_MIN] + 1]); if (flags[f_MAX] != FLAG_NOT_SET) max = atof(argv[flags[f_MAX] + 1]); if (flags[f_BINS] != FLAG_NOT_SET) bins = atoi(argv[flags[f_BINS] + 1]); if (flags[f_INTERVAL] != FLAG_NOT_SET) interval = atof(argv[flags[f_INTERVAL] + 1]); if (flags[f_QUIET] == FLAG_NOT_SET) /* display splash screen if not quiet */ print_splash_screen(argc, argv); if (flags[f_LOG] != FLAG_NOT_SET) strcpy(logFile, argv[flags[f_LOG] + 1]); else /* default behavior: log to tmp<pid>.log */ sprintf(logFile, "tmp%i.log", (int)getpid()); fLog = FOPEN(logFile, "a"); /* Fetch required arguments */ strcpy(inFile,argv[argc - 2]); strcpy(outBase,argv[argc - 1]); /***********************END COMMAND LINE PARSING STUFF***********************/ create_name(metaFile, inFile, ".meta"); create_name(dataFile, inFile, ".img"); /* Read metadata */ meta = meta_read(inFile); lines = meta->general->line_count; samples = meta->general->sample_count; /* Set some values */ doppler = 0.0; /* Determine what kind of image it is */ if (meta->sar->image_type=='P') { if (meta->projection->type==SCANSAR_PROJECTION) printf(" Detected ScanSAR "); } else if (meta->sar->image_type=='S') printf(" Detected slant range "); else if (meta->sar->image_type=='G') printf(" Detected ground range "); /* switch (meta->general->image_data_type) { case AMPLITUDE_IMAGE: printf("amplitude image ...\n"); break; case SIGMA_IMAGE: printf("sigma image ...\n"); break; case GAMMA_IMAGE: printf("gamma image ...\n"); break; case BETA_IMAGE: printf("beta image ...\n"); break; case RAW_IMAGE: case COMPLEX_IMAGE: case PHASE_IMAGE: case POWER_IMAGE: case COHERENCE_IMAGE: case GEOREFERENCED_IMAGE: case GEOCODED_IMAGE: case POLARIMETRIC_IMAGE: case LUT_IMAGE: case ELEVATION: case DEM: case IMAGE: case MASK: break; } */ /* Create a mask file for background fill - required only for ScanSAR */ if (meta->sar->image_type=='P') { if (meta->projection->type==SCANSAR_PROJECTION) { fpIn = fopenImage(inFile, "rb"); bufImage = (float *) MALLOC(samples * sizeof(float)); printf(" Generating mask file ...\n"); maskFile = (char *) MALLOC(255*sizeof(char)); sprintf(maskFile, "tmp%i.mask", (int)getpid()); fpMask = fopenImage(maskFile, "wb"); bufMask = (unsigned char *) MALLOC(samples * sizeof(char)); for (ii=0; ii<lines; ii++) { get_float_line(fpIn, meta, ii, bufImage); for (kk=0; kk<samples; kk++) { if (bufImage[kk]>0.0) bufMask[kk] = 1; else bufMask[kk] = 0; } ASF_FWRITE(bufMask, sizeof(char), samples, fpMask); } FCLOSE(fpMask); FREE(bufMask); FCLOSE(fpIn); FREE(bufImage); } } /* Create grid for least square approach */ printf(" Initialization ...\n"); if (flags[f_LOOK] != FLAG_NOT_SET) { sprintf(outLook, "tmp%i.look", (int)getpid()); fpLook = FOPEN(outLook, "w"); } if (flags[f_INCIDENCE] != FLAG_NOT_SET) { sprintf(outIncid, "tmp%i.incid", (int)getpid()); fpIncid = FOPEN(outIncid, "w"); } if (flags[f_RANGE] != FLAG_NOT_SET) { sprintf(outRange, "tmp%i.range", (int)getpid()); fpRange = FOPEN(outRange, "w"); } if (flags[f_LOOK] != FLAG_NOT_SET || flags[f_INCIDENCE] != FLAG_NOT_SET || flags[f_RANGE] != FLAG_NOT_SET) { for (ll=0; ll<=RES_X; ll++) for (kk=0; kk<=RES_Y; kk++) { line = ll * lines / RES_Y; sample = kk * samples / RES_X; if (meta->sar->image_type=='P') { px = meta->projection->startX + meta->projection->perX * sample; py = meta->projection->startY + meta->projection->perY * line; proj_to_latlon(meta->projection, px, py, 0.0, &latitude, &longitude, &height); latLon2timeSlant(meta, latitude, longitude, &time, &range, &doppler); } else time = meta_get_time(meta, line, sample); stVec = meta_get_stVec(meta, time); if (meta->sar->image_type=='P') { if (meta->projection->type==SCANSAR_PROJECTION) earth_radius = meta->projection->param.atct.rlocal; else asfPrintError("Unable to determine earth radius.\n"); } else earth_radius = my_get_earth_radius(time, stVec, re, rp); satellite_height = my_get_satellite_height(time, stVec); range = my_get_slant_range(meta, earth_radius, satellite_height, line, sample); look_angle = my_get_look_angle(earth_radius, satellite_height, range); incidence_angle = my_get_incidence_angle(earth_radius, satellite_height, range); if (ll==0 && kk==0) { firstLook = look_angle * R2D; firstIncid = incidence_angle * R2D; firstRange = range; } if (flags[f_LOOK] != FLAG_NOT_SET) fprintf(fpLook, "%.18f %.12f %.12f\n", (float)look_angle*R2D, line, sample); if (flags[f_INCIDENCE] != FLAG_NOT_SET) fprintf(fpIncid, "%.18f %.12f %.12f\n", (float)incidence_angle*R2D, line, sample); if (flags[f_RANGE] != FLAG_NOT_SET) fprintf(fpRange, "%.18f %.12f %.12f\n", (float)range, line, sample); } } /* Close files for now */ if (flags[f_LOOK] != FLAG_NOT_SET) { FCLOSE(fpLook); FREE(bufLook); } if (flags[f_INCIDENCE] != FLAG_NOT_SET) { FCLOSE(fpIncid); FREE(bufIncid); } if (flags[f_RANGE] != FLAG_NOT_SET) { FCLOSE(fpRange); FREE(bufRange); } /* Calculate plots */ if (flags[f_LOOK] != FLAG_NOT_SET) { create_name(outFile, outBase, "_look.plot"); calculate_plot("Look angle", outLook, dataFile, maskFile, outFile, meta, firstLook); } if (flags[f_INCIDENCE] != FLAG_NOT_SET) { create_name(outFile, outBase, "_incid.plot"); calculate_plot("Incidence angle", outIncid, dataFile, maskFile, outFile, meta, firstIncid); } if (flags[f_RANGE] != FLAG_NOT_SET) { create_name(outFile, outBase, "_range.plot"); calculate_plot("Range", outRange, dataFile, maskFile, outFile, meta, firstRange); } if (flags[f_LINE] != FLAG_NOT_SET) { create_name(outFile, outBase, "_line.plot"); calculate_plot("Line", NULL, dataFile, maskFile, outFile, meta, 0.0); } if (flags[f_SAMPLE] != FLAG_NOT_SET) { create_name(outFile, outBase, "_sample.plot"); calculate_plot("Sample", NULL, dataFile, maskFile, outFile, meta, 0.0); } /* Clean up */ sprintf(cmd, "rm -rf tmp*"); system(cmd); exit(0); }
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[]) { int currArg = 1; int NUM_ARGS = 2; handle_license_and_version_args(argc, argv, ASF_NAME_STRING); asfSplashScreen(argc, argv); if (argc<2) usage(ASF_NAME_STRING); else if (strmatches(argv[1],"-help","--help",NULL)) print_help(); while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key,"-help","--help",NULL)) { print_help(); // doesn't return } else if (strmatches(key,"-log","--log",NULL)) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag = TRUE; } else if (strmatches(key,"-quiet","--quiet","-q",NULL)) { quietflag = TRUE; } else { --currArg; break; } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments. Expected %d, got %d.\n", NUM_ARGS, argc-currArg); usage(argv[0]); } else if ((argc-currArg) > NUM_ARGS) { printf("Unknown argument: %s\n", argv[currArg]); usage(argv[0]); } char *in_file = argv[currArg]; char *out_file = argv[currArg+1]; char *in_img = appendExt(in_file, ".img"); char *out_img = appendExt(out_file, ".img"); char *in_meta = appendExt(in_file, ".meta"); char *out_meta = appendExt(out_file, ".meta"); meta_parameters *meta = meta_read(in_meta); if (!meta) asfPrintError("Failed to read metadata for: %s\n", in_file); FILE *ifp = FOPEN(in_img, "r"); FILE *ofp = FOPEN(out_img, "w"); float *buf = MALLOC(sizeof(float)*meta->general->sample_count); int ii,jj; for (ii=0; ii<meta->general->line_count; ++ii) { get_float_line(ifp, meta, ii, buf); for (jj=0; jj<meta->general->sample_count; ++jj) { if (buf[jj] < 0) { buf[jj] = 0; } else { buf[jj] = sqrt(buf[jj]); } } put_float_line(ofp, meta, ii, buf); asfLineMeter(ii,meta->general->line_count); } FCLOSE(ifp); FCLOSE(ofp); FREE(buf); if (meta->stats) { FREE(meta->stats); meta->stats = NULL; } meta_write(meta, out_meta); meta_free(meta); FREE(in_img); FREE(out_img); FREE(in_meta); FREE(out_meta); asfPrintStatus("Done.\n"); return EXIT_SUCCESS; }
static void get_inner_extents(char *file, double *x0, double *y0, double *xL, double *yL) { int ii, kk; FILE *fp = FOPEN(file, "rb"); meta_parameters *meta = meta_read(file); int line_count = meta->general->line_count; int sample_count = meta->general->sample_count; int startX = sample_count - 1; int endX = 0; int startY = -99; int endY = -99; int startLine = -99; int startSample = -99; int endLine = 0; int endSample = 0; float *buf = (float *) MALLOC(sizeof(float)*sample_count); for (ii=0; ii<line_count; ii++) { get_float_line(fp, meta, ii, buf); int left = 0; int right = sample_count - 1; while (FLOAT_EQUIVALENT(buf[left], 0.0) && left < sample_count - 1) left++; while (FLOAT_EQUIVALENT(buf[right], 0.0) && right > 0) right--; if (left < startX) { startX = left; startLine = ii; } if (right > endX) { endX = right; endLine = ii; } int all_zero = TRUE; for (kk=0; kk<sample_count; kk++) { if (!FLOAT_EQUIVALENT(buf[kk], 0.0)) { all_zero = FALSE; break; } } if (!all_zero) { if (startY < 0) { startY = ii; endSample = kk; } startSample = kk; endY = ii; } } FCLOSE(fp); FREE(buf); *x0 = meta->projection->startX + startSample*meta->projection->perX; *y0 = meta->projection->startY + startLine*meta->projection->perY; *xL = meta->projection->startX + endSample*meta->projection->perX; *yL = meta->projection->startY + endLine*meta->projection->perY; meta_free(meta); }
static void ingest_insar_data(char *inFile, char *inBaseName, char *band, int size, int line_count, char *outFile, int create) { airsar_header *header; meta_parameters *metaIn = NULL, *metaOut = NULL; FILE *fpIn, *fpOut; int ii, kk, line_offset; float *floatBuf; char tmp[10]; fpIn = FOPEN(inFile, "rb"); append_ext_if_needed(outFile, ".img", NULL); if (create) fpOut = FOPEN(outFile, "wb"); else fpOut = FOPEN(outFile, "ab"); if (create) { metaOut = import_airsar_meta(inFile, inBaseName, TRUE); metaOut->general->data_type = REAL32; metaOut->general->band_count = 1; sprintf(metaOut->general->bands, "%s", band); metaOut->general->image_data_type = IMAGE_LAYER_STACK; } else { metaOut = meta_read(outFile); metaOut->general->band_count += 1; sprintf(tmp, ",%s", band); strcat(metaOut->general->bands, tmp); } header = read_airsar_header(inFile); metaIn = import_airsar_meta(inFile, inBaseName, TRUE); line_offset = header->first_data_offset/metaIn->general->sample_count/size; metaIn->general->line_count = line_count + line_offset; if (size == 2) metaIn->general->data_type = INTEGER16; else if (size == 1) metaIn->general->data_type = ASF_BYTE; floatBuf = (float *) MALLOC(sizeof(float)*metaIn->general->sample_count); for (ii=0; ii<line_count; ii++) { get_float_line(fpIn, metaIn, ii+line_offset, floatBuf); if (strcmp_case(band, "DEM") == 0) { for (kk=0; kk<metaIn->general->sample_count; kk++) floatBuf[kk] = floatBuf[kk]*metaIn->airsar->elevation_increment + metaIn->airsar->elevation_offset; } put_float_line(fpOut, metaOut, ii, floatBuf); asfLineMeter(ii, line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outFile); if (floatBuf) FREE(floatBuf); if (metaIn) meta_free(metaIn); if (metaOut) meta_free(metaOut); }
int dem2phase(char *demFile, char *baseFile, char *phaseFile) { int x, y, start_sample, start_line, line_count, sample_count; double k, *phase2elevBase, *sinFlat, *cosFlat, xScale, yScale; baseline base; meta_parameters *meta; FILE *fpDem, *fpPhase; float *phase,*dem; meta = meta_read(demFile); start_sample = meta->general->start_sample; start_line = meta->general->start_line; xScale = meta->sar->sample_increment; yScale = meta->sar->line_increment; line_count = meta->general->line_count; sample_count = meta->general->sample_count; meta_write(meta, phaseFile); // Allocate some memory phase = (float *)MALLOC(sizeof(float)*sample_count); dem =(float *)MALLOC(sizeof(float)*sample_count); // Get wavenumber k = meta_get_k(meta); // Read in baseline values base = read_baseline(baseFile); // Open files fpDem = fopenImage(demFile, "rb"); fpPhase = fopenImage(phaseFile,"wb"); /* calculate the sine of the incidence angle across cols*/ sinFlat = (double *)MALLOC(sizeof(double)*sample_count); cosFlat = (double *)MALLOC(sizeof(double)*sample_count); phase2elevBase = (double *)MALLOC(sizeof(double)*sample_count); for (x=0; x<sample_count; x++) { int img_x = x*xScale + start_sample; double incid = meta_incid(meta, 0.0, (float)img_x); double flat = meta_flat(meta, 0.0, (float)img_x); sinFlat[x] = sin(flat); cosFlat[x] = cos(flat); phase2elevBase[x] = meta_get_slant(meta, 0.0, (float)img_x) * sin(incid)/(2.0*k); } // Loop through each row and calculate height for (y=0;y<line_count;y++) { double Bn_y, Bp_y; // Read in data get_float_line(fpDem, meta, y, dem); // Calculate baseline for this row meta_interp_baseline(meta, base, y*(int)yScale+start_line, &Bn_y, &Bp_y); // Step through each pixel in row for (x=0; x<sample_count; x++) phase[x] = dem[x]/phase2elevBase[x]*(-Bp_y*sinFlat[x]-Bn_y*cosFlat[x]); put_float_line(fpPhase, meta, y, phase); asfLineMeter(y, line_count); } asfPrintStatus("Wrote %d lines of simulated phase data.\n\n", line_count); // Clean up FREE(phase); FREE(dem); FCLOSE(fpPhase); FCLOSE(fpDem); return(0); }
void calc_stats_rmse_from_file(const char *inFile, char *band, double mask, double *min, double *max, double *mean, double *stdDev, double *rmse, gsl_histogram **histogram) { double se; int ii,jj; *min = 999999; *max = -999999; *mean = 0.0; meta_parameters *meta = meta_read(inFile); int band_number = (!band || strlen(band) == 0 || strcmp(band, "???") == 0) ? 0 : 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, rmse, and histogram...\n"); se = 0.0; 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]); se += (data[jj] - *mean) * (data[jj] - *mean); } } } asfPercentMeter(1.0); FCLOSE(fp); *stdDev = sqrt(*stdDev/(pixel_count - 1)); *rmse = sqrt(se/(pixel_count - 1)); FREE(data); *histogram = hist; }
void calc_minmax_median(const char *inFile, char *band, double mask, double *min, double *max) { long long ii, jj; float logeps = 10.0 * log10(EPSILON); float median, median0; meta_parameters *meta = meta_read(inFile); int band_number = (!band || strlen(band) == 0 || strcmp(band, "???") == 0) ? 0 : get_band_number(meta->general->bands, meta->general->band_count, band); long sample_count = meta->general->sample_count; long line_count = meta->general->line_count; long pixel_count = sample_count*line_count; long offset = line_count * band_number; float *data_line = MALLOC(sizeof(float) * sample_count); float *data = MALLOC(sizeof(float) * pixel_count); float *data2 = MALLOC(sizeof(float) * pixel_count); // Culling invalid pixels FILE *fp = FOPEN(inFile, "rb"); long valid_pixel_count = 0; asfPrintStatus("\nCalculating min and max using median...\n"); for (ii=0; ii<line_count; ++ii) { get_float_line(fp, meta, ii + offset, data_line); asfPercentMeter(((double)ii/(double)line_count)); for (jj=0; jj<sample_count; ++jj) { if (!FLOAT_EQUIVALENT(data_line[jj], -9999.99) || !FLOAT_EQUIVALENT(data_line[jj], logeps) || ISNAN(mask)) { data[valid_pixel_count] = data_line[jj]; valid_pixel_count++; } } } asfPercentMeter(1.0); FCLOSE(fp); FREE(data_line); // Determine initial min and max *min = INIT_MINMAX; *max = -INIT_MINMAX; float minmin = INIT_MINMAX; float maxmax = -INIT_MINMAX; for (ii=0; ii<valid_pixel_count; ++ii) { data2[ii] = data[ii]; if (data[ii] < minmin) minmin = data[ii]; if (data[ii] > maxmax) maxmax = data[ii]; } median0 = median_value(data, valid_pixel_count); // Determine minimum median = median0; *min = median0; for (ii=0; ii<3; ii++) { pixel_count = -1; for (jj=0; jj<valid_pixel_count; ++jj) if (median0 == minmin) { if (data[jj] <= median) { pixel_count++; data2[pixel_count] = data[jj]; } } else { if (data[jj] < median) { pixel_count++; data2[pixel_count] = data[jj]; } } median = median_value(data2, pixel_count); if (median == minmin) median = *min; *min = median; } // Determine maximum median = median0; *max = median0; for (ii=0; ii<3; ii++) { pixel_count = -1; for (jj=0; jj<valid_pixel_count; ++jj) if (median0 == maxmax) { if (data[jj] >= median) { pixel_count++; data2[pixel_count] = data[jj]; } } else { if (data[jj] > median) { pixel_count++; data2[pixel_count] = data[jj]; } } median = median_value(data2, pixel_count); if (median == maxmax) median = *max; *max = median; } FREE(data); FREE(data2); }
static void get_uavsar_lines(ReadUavsarClientInfo *info, meta_parameters *meta, int row, int n, float *buf) { // wrapper for get_float_line() that multilooks if needed int j,ns=meta->general->sample_count; if (info->ml) { assert(meta->sar); int i,k; int nlooks = meta->sar->azimuth_look_count; row *= nlooks; // we fudged the line count in the metadata for the // viewer (which is displaying a multilooked image), we must // put the correct value back for the reader int lc = meta->general->line_count; meta->general->line_count = g_saved_line_count; float *tmp = MALLOC(sizeof(float)*ns); for (i=0; i<n; ++i) { float *this_row = buf + i*ns; get_float_line(info->fp, meta, row+i*nlooks, this_row); for (j=0; j<ns; ++j) ieee_big32(this_row[j]); int n_read = nlooks; for (k=1; k<nlooks; ++k) { if (row+n*nlooks+k >= meta->general->line_count) { --n_read; } else { get_float_line(info->fp, meta, row+i*nlooks+k, tmp); for (j=0; j<ns; ++j) ieee_big32(tmp[j]); for (j=0; j<ns; ++j) this_row[j] += tmp[j]; } } for (j=0; j<meta->general->sample_count; ++j) this_row[j] /= n_read; } free(tmp); // restore the fudged value meta->general->line_count = lc; } else { // no multilooking case if (info->is_complex) { complexFloat *cf_buf = MALLOC(sizeof(complexFloat)*ns*n); get_complexFloat_lines(info->fp, meta, row, n, cf_buf); for (j=0; j<n*ns; ++j) { ieee_big32(cf_buf[j].real); ieee_big32(cf_buf[j].imag); buf[j] = hypot(cf_buf[j].real, cf_buf[j].imag); //buf[j] = atan2_check(cf_buf[j].imag, cf_buf[j].real); } FREE(cf_buf); } else { get_float_lines(info->fp, meta, row, n, buf); for (j=0; j<n*ns; ++j) ieee_big32(buf[j]); } } }
int main(int argc, char **argv) { int x, y; int maskflag=0; unsigned char *mask; double k; double *phase2elevBase,*sinFlat,*cosFlat; char datafile[256], basefile[256], outfile[256]; char maskfile[256]; int nrows,ncols; float *f_coh; float *f_eleverr; float percent=0.0; double init_err=DEFAULT_ERROR; FILE *fdata, *fmask, *fout; meta_parameters *meta; baseline base; /* Parse command line arguments */ logflag=FALSE; while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatch(key,"-log")) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag=TRUE; } else if (strmatch(key, "-mask")) { CHECK_ARG(1); strcpy(maskfile, GET_ARG(1)); maskflag = TRUE; } else if (strmatch(key,"-i")) { CHECK_ARG(1); init_err = atof(GET_ARG(1)); init_err *= init_err; } else { printf("\n**Invalid option: %s\n",argv[currArg-1]); usage(argv[0]); } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments.\n"); usage(argv[0]); } create_name(datafile, argv[currArg], ".img"); strcpy(basefile, argv[currArg+1]); strcpy(outfile, argv[currArg+2]); asfSplashScreen(argc, argv); /* Get appropriate metadata */ meta = meta_read(datafile); nrows = meta->general->line_count; ncols = meta->general->sample_count; meta->general->data_type = REAL32; meta_write(meta, outfile); k = meta_get_k(meta); /* wave number*/ /* Allocate space for vectors, matricies, and stuff*/ mask = (unsigned char *)MALLOC(sizeof(unsigned char)*ncols); f_coh = (float *)MALLOC(sizeof(float)*ncols); f_eleverr = (float *)MALLOC(sizeof(float)*ncols); sinFlat = (double *)MALLOC(sizeof(double)*ncols); cosFlat = (double *)MALLOC(sizeof(double)*ncols); phase2elevBase = (double *)MALLOC(sizeof(double)*ncols); /* Open data file & get seed phase*/ fdata = fopenImage(datafile, "rb"); fout = fopenImage(outfile,"wb"); if (maskflag) fmask = fopenImage(maskfile,"rb"); /* Read in baseline values*/ base = read_baseline(basefile); /* Obtain information from metadata*/ for (x=0;x<ncols;x++) { int img_x = x * meta->sar->sample_increment + meta->general->start_sample; double incid=meta_incid(meta,0,img_x); double flat=meta_flat(meta,0,img_x); sinFlat[x]=sin(flat); cosFlat[x]=cos(flat); phase2elevBase[x]=meta_get_slant(meta,0,img_x)*sin(incid)/(2.0*k); } /* Loop through each row & calculate height*/ for (y=0;y<nrows;y++) { double Bn_y,Bp_y; /* Report progress */ if ((y*100/nrows)>percent) { printf("\r Completed %3.0f percent", percent); fflush(NULL); percent+=5.0; } /* read in data */ if (maskflag) ASF_FREAD(mask,sizeof(unsigned char),ncols,fmask); get_float_line(fdata, meta, y, f_coh); /* calculate baseline for this row*/ meta_interp_baseline(meta, base, y*meta->sar->line_increment+meta->general->start_line+1, &Bn_y, &Bp_y); /* step through each pixel in row*/ for (x=0;x<ncols;x++) { if ((mask[x] == 0x10 && maskflag) || (!maskflag)) { double tmp,tmp1,sigma_height; tmp = phase2elevBase[x]/(-Bp_y*sinFlat[x]-Bn_y*cosFlat[x]); tmp1 = (FLOAT_EQUALS_ZERO(f_coh[x])) ? 0.0 : sqrt((1-f_coh[x])/f_coh[x]); sigma_height = tmp*tmp1; f_eleverr[x] = (float)sqrt( init_err + sigma_height*sigma_height ); } else f_eleverr[x] = -1.0; } put_float_line(fout, meta, y, f_eleverr); } printf("\r Completed 100 percent\n\n"); sprintf(logbuf, " Wrote %lld bytes of data\n\n", (long long)(nrows*ncols*4)); printf("%s", logbuf); if (logflag) { printLog(logbuf); } /* free memory & scram*/ meta_free(meta); FREE(mask); FREE(f_coh); FREE(f_eleverr); FREE(sinFlat); FREE(cosFlat); FREE(phase2elevBase); FCLOSE(fdata); FCLOSE(fout); if (maskflag) FCLOSE(fmask); exit(EXIT_SUCCESS); }
int asf_windspeed(platform_type_t platform_type, char *band_id, double wind_dir, int cmod4, double landmaskHeight, char *landmaskFile, char *demFile, char *inBaseName, char *colormapName, char *outBaseName) { char *inDataName, outDataName[1024], outMetaName[1024]; FILE *in = NULL, *out = NULL; asfPrintStatus("\n Determining windspeeds in: %s\n", inBaseName); strcpy(outDataName, outBaseName); strcpy(outMetaName, outBaseName); inDataName = (char *)MALLOC(sizeof(char) * (strlen(inBaseName) + 10)); strcpy(inDataName, inBaseName); append_ext_if_needed(inDataName, ".img", NULL); append_ext_if_needed(outDataName, ".img", NULL); append_ext_if_needed(outMetaName, ".meta", NULL); // New images for processing in to out meta_parameters *imd = meta_read(inBaseName); meta_general *img = imd->general; // convenience ptr meta_parameters *omd = meta_read(inBaseName); meta_general *omg = omd->general; // convenience ptr meta_sar *oms = omd->sar; // convenience ptr omg->band_count = 0; strcpy(omg->bands, ""); strcpy(oms->polarization, ""); if (strstr(img->bands, "VV") == NULL && strstr(img->bands, "HH") == NULL) { asfPrintError("Cannot find any VV or HH polarized bands in this data. Available\n" "bands are %s). Wind speeds can only be determined on Sigma0-\n" "calibrated SAR data in HH or VV polarizations.\n", img->bands); } in = (FILE *)FOPEN(inDataName, "rb"); out = (FILE *)FOPEN(outDataName, "wb"); FREE(inDataName); // For each band double alpha = 1.0; // Default for VV polarization; int band_num; float *data = (float *)MALLOC(sizeof(float) * img->sample_count); for (band_num = 0; band_num < img->band_count; band_num++) { // Get band name, check for proper polarization, and create new output bandname, set alpha char *band_name = get_band_name(img->bands, img->band_count, band_num); long offset = img->line_count * band_num; char polarization[2]=""; if (strncmp_case(band_name, "SIGMA-VV", 8) == 0 || strncmp_case(band_name, "SIGMA-HH", 8) == 0) { asfPrintStatus("\nProcessing wind speed calculations on band %s...\n\n", band_name); (omg->band_count)++; strcpy(polarization, (strstr(band_name, "VV") != NULL) ? "VV" : "HH"); strcpy(oms->polarization, polarization); sprintf(&omg->bands[strlen(omg->bands)], "%s%s%s", WINDSPEED_BAND_BASENAME, polarization, (band_num < img->band_count - 1 && img->band_count > 0) ? ", " : ""); alpha = (strcmp(polarization, "VV") == 0) ? 1.0 : DEFAULT_HH_POL_ALPHA; // For CMODx } else { asfPrintStatus("\nFound band: %s (Cannot calculate wind speed on this type of band)\n\n", band_name); continue; // Skip this band } // Calculate average r_look for entire image (r_look is the angle between the NADIR line // and a line point directly north, the 'look angle' of the platform.) double r_look = asf_r_look(imd); double phi_diff = wind_dir - r_look; // Pre-populate incidence angles (as a function of sample) and get min/max incidence angle // as well int line, sample; double *incids = (double *)MALLOC(img->sample_count * sizeof(double)); double min_incid = DBL_MAX; double max_incid = DBL_MIN; for (sample = 0; sample < img->sample_count; sample++) { incids[sample] = R2D * meta_incid(imd, img->line_count / 2, sample); min_incid = (incids[sample] < min_incid) ? incids[sample] : min_incid; max_incid = (incids[sample] > max_incid) ? incids[sample] : max_incid; } // Get min/max radar cross-sections asfPrintStatus("\nFinding min/max radar cross-sections...\n\n"); double rcs_min = DBL_MAX; double rcs_max = DBL_MIN; for (line = 0; line < img->line_count; line++) { // Get a line get_float_line(in, imd, line+offset, data); for (sample = 0; sample < img->sample_count; sample++) { if (meta_is_valid_double(data[sample]) && data[sample] >= 0.0) { rcs_min = (data[sample] < rcs_min) ? data[sample] : rcs_min; rcs_max = (data[sample] > rcs_max) ? data[sample] : rcs_max; } } asfLineMeter(line, img->line_count); } // FIXME: Generate 2D array of windspeeds here. One dimension is incidence angle and // the other is radar cross-section. The values in the table are wind speed as a function // of incidence angle and radar cross-section (given the provided wind direction.) The idea // is to more-quickly populate a grid of results and then to interpolate results for each // pixel of the image rather then perform the full calculation (very sloooow) double windspeed1 = 0.0, windspeed2 = 0.0; for (line = 0; line < img->line_count; line++) { // Get a line get_float_line(in, imd, line+offset, data); for (sample = 0; sample < img->sample_count; sample++) { // FIXME: Here is where we should apply a land mask ...in this if-statement expression if (meta_is_valid_double(data[sample]) && data[sample] >= 0.0) { // Calculate windspeed // FIXME: This returns the angle, at the target pixel location, between straight up // and the line to the satellite. Make sure Frank's code doesn't assume the angle // between the line to the satellite and a horizontal line, i.e. 90 degrees minus // this angle. double incidence_angle = incids[sample]; switch (platform_type) { case p_RSAT1: if (!cmod4) { // Use CMOD5 to calculate windspeeds double hh = alpha; ws_inv_cmod5((double)data[sample], phi_diff, incidence_angle, &windspeed1, &windspeed2, (double)MIN_CMOD5_WINDSPEED, (double)MAX_CMOD5_WINDSPEED, 25, hh); data[sample] = windspeed1; // When 2 answers exist, take the lower (per Frank Monaldo) } else { // Use CMOD4 to calculate windspeeds asfPrintError("The CMOD4 algorithm is not yet supported. Avoid the -cmod4\n" "option for now and let %s default to using the CMOD5 algorithm\n" "instead.\n"); } break; case p_PALSAR: case p_TERRASARX: case p_ERS1: case p_ERS2: default: asfPrintError("Found a platform type (%s) that is not yet supported.\n", (platform_type == p_PALSAR) ? "PALSAR" : (platform_type == p_TERRASARX) ? "TerraSAR-X" : (platform_type == p_ERS1) ? "ERS-1" : (platform_type == p_ERS2) ? "ERS-2" : "UNKNOWN PLATFORM"); } } } put_float_line(out, omd, line+offset, data); asfLineMeter(line, img->line_count); } } // end for (each band) FREE(data); // Insert colormap into metadata meta_write(omd, outMetaName); meta_free(imd); meta_free(omd); asfPrintStatus("Windspeed calculation complete.\n\n"); return EXIT_SUCCESS; }
// if png_flag is true, outputs a PNG. if false, outputs a jpeg static void patchToRGBImage(char *outname, int png_flag) { update_status("Generating %s", outname); if (!quietflag) printf(" Outputting Debugging image '%s'...\n",outname); // input name is just the output name with ".img" char *polar_name = MALLOC((strlen(outname)+20)*sizeof(char)); sprintf(polar_name, "%s_polar.img", outname); // will multilook, as well as conver to polar, generates a 2-band // file (amplitude is band 1, phase is band 2) c2p(outname,polar_name,FALSE,TRUE); // prepare for RGB conversion int i,j; meta_parameters *meta = meta_read(polar_name); int nl = meta->general->line_count; int ns = meta->general->sample_count; float *amp = MALLOC(sizeof(float)*ns); float *phase = MALLOC(sizeof(float)*ns); unsigned char *red = MALLOC(sizeof(unsigned char)*ns); unsigned char *grn = MALLOC(sizeof(unsigned char)*ns); unsigned char *blu = MALLOC(sizeof(unsigned char)*ns); FILE *fp = fopenImage(polar_name, "rb"); const double TWOPI=2.*PI; const double PIOVER3=PI/3.; int n=0; // first/second passes are stats gathering asfPrintStatus("Gathering stats...\n"); double avg=0, stddev=0; for (i=0; i<nl; i+=3) { get_float_line(fp,meta,i,amp); for (j=0; j<ns; j+=3) { avg += amp[j]; ++n; } asfPercentMeter((float)i/((float)nl*2.)); } avg /= (double)n; for (i=0; i<nl; i+=3) { get_float_line(fp,meta,i,amp); for (j=0; j<ns; j+=3) { stddev += (amp[j]-avg)*(amp[j]-avg); } asfPercentMeter((float)(i+nl)/((float)nl*2.)); } asfPercentMeter(1); stddev = sqrt(stddev/(double)n); double min = avg - 2*stddev; double max = avg + 2*stddev; // open up PNG/JPEG output file FILE *ofp=NULL; struct jpeg_compress_struct cinfo; png_structp png_ptr; png_infop png_info_ptr; char *jpgname = NULL; char *pngname = NULL; if (png_flag) { asfPrintStatus("Generating debug image (PNG)...\n"); pngname = appendExt(outname, ".png"); initialize_png_file(pngname,meta,&ofp,&png_ptr,&png_info_ptr,TRUE); } else { asfPrintStatus("Generating debug image (JPEG)...\n"); jpgname = appendExt(outname, ".jpg"); initialize_jpeg_file(jpgname,meta,&ofp,&cinfo,TRUE); } // now read in the polar image, calculate RGB values, write to jpeg/png for (i=0; i<nl; ++i) { get_band_float_line(fp,meta,0,i,amp); get_band_float_line(fp,meta,1,i,phase); for (j=0; j<ns; ++j) { // scale to 2-sigma, to get brightness of the pixel unsigned char intensity; //=(unsigned char)(amp[j] * 128./(float)avg * 41./255.); if (amp[j]<=min) intensity=0; else if (amp[j]>=max) intensity=255; else intensity=(unsigned char)((amp[j]-min)/(max-min)*255.); // color of the pixel is determined by the phase unsigned char r=0,g=0,b=0; if (phase[j]<-PI) phase[j]+=TWOPI; // ensure [-PI, PI) if (phase[j]>=PI) phase[j]-=TWOPI; int range = (int)((phase[j]+PI)/PIOVER3); // will be 0-6 (and rarely 6) switch (range) { case 0: r=1; break; case 1: r=1; g=1; break; case 2: g=1; break; case 3: g=1; b=1; break; case 4: b=1; break; case 5: r=1; b=1; break; case 6: break; // left black default: printf("phase: %f, range: %d\n", phase[j], range); assert(FALSE); break; } red[j] = r*intensity; grn[j] = g*intensity; blu[j] = b*intensity; } // write the line if (png_flag) write_rgb_png_byte2byte(ofp,red,grn,blu,png_ptr,png_info_ptr,ns); else write_rgb_jpeg_byte2byte(ofp,red,grn,blu,&cinfo,ns); // keep the user interested! asfPercentMeter((float)i/((float)nl)); } asfPercentMeter(1.0); // clean up FCLOSE(fp); FREE(amp); FREE(phase); FREE(red); FREE(grn); FREE(blu); meta_free(meta); if (png_flag) finalize_png_file(ofp,png_ptr,png_info_ptr); else finalize_jpeg_file(ofp,&cinfo); FREE(jpgname); FREE(pngname); clean(polar_name); FREE(polar_name); }
int main(int argc, char *argv[]) { char *baseFile; meta_parameters *meta; baseline base; int wid, len, /* Width and Length of input scene */ ss, sl; /* Offsets of input scene in original */ int x,y; double xScale,yScale; float percent=5.0; FILE *fin, *fout; char szInPhase[255], szInAmp[255], szOutPhase[255], szOutAmp[255]; float *data; double *sflat,*cflat; double derampDirection=1.0;/*1.0=forward deramping. -1.0=backward deramping.*/ logflag=0; /* process command line args */ currArg=1; /* from cla.h in asf.h */ /* optional args */ while (currArg < (argc-3)) { char *key = argv[currArg++]; if (strmatch(key,"-log")) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag=1; } else if (strmatch(key,"-backward")) { derampDirection = -1.0; } else {printf("**Invalid option: %s\n",argv[currArg-1]); usage(argv[0]);} } if ((argc-currArg) < 3) {printf("Insufficient arguments.\n"); usage(argv[0]);} /* required args */ create_name(szInAmp, argv[currArg], "_amp.img"); create_name(szInPhase, argv[currArg], "_phase.img"); baseFile = argv[currArg+1]; asfSplashScreen(argc, argv); /* Get input scene size and windowing info, check validity */ meta = meta_read(szInPhase); wid = meta->general->sample_count; len = meta->general->line_count; ss = meta->general->start_sample - 1; sl = meta->general->start_line - 1; xScale = meta->sar->sample_increment; yScale = meta->sar->line_increment; create_name(szOutAmp,argv[currArg+2],"_amp.img"); meta_write(meta, szOutAmp); create_name(szOutPhase,argv[currArg+2],"_phase.img"); meta_write(meta, szOutPhase); /*Link over ".amp" file, if it exists.*/ if (fileExists(szInAmp)&&!fileExists(szOutAmp)) { char command[1024]; sprintf(command,"ln -s %s %s\n", szInAmp, szOutAmp); system(command); } /* buffer mallocs, read data file */ data = (float *)MALLOC(sizeof(float)*wid); sflat = (double *)MALLOC(sizeof(double)*wid); cflat = (double *)MALLOC(sizeof(double)*wid); fin = fopenImage(szInPhase,"rb"); fout = fopenImage(szOutPhase,"wb"); /* read in CEOS parameters & convert to meters */ base=read_baseline(baseFile); /* calculate slant ranges and look angles - Ian's thesis eqn 3.10 */ for (x = 0; x < wid; x++) { double flat=meta_flat(meta,0.0,x*xScale+ss); sflat[x]=sin(flat); cflat[x]=cos(flat); } /* Deramp 'data' array */ /* printf("\n starting in-place deramp of input data \n\n");*/ for (y = 0; y < len; y++) { double Bn_y,Bp_y; double twok=derampDirection*2.0*meta_get_k(meta); meta_interp_baseline(meta,base,y*(int)yScale+sl,&Bn_y,&Bp_y); /* read in the next row of data */ get_float_line(fin, meta, y, data); /* calculate flat-earth range phase term & remove it */ for (x = 0; x < wid; x++) { double d=data[x]; if (d!=0.0) /*Ignore points which didn't phase unwrap.*/ d -= twok*(Bp_y*cflat[x]-Bn_y*sflat[x]); /*Was: d-=ceos_flat_phase(ceos,base,x,y);*/ data[x]=d; } /* write out this row of data */ put_float_line(fout, meta, y, data); if (y*100/len==percent) { printf(" Completed %3.0f percent\n", percent); percent+=5.0; } } /* printf("\nDone with deramp\n\n");*/ /* save and scram */ FCLOSE(fin); FCLOSE(fout); FREE(data); FREE(sflat);FREE(cflat); printf(" Completed 100 percent\n\n"); if (logflag) { sprintf(logbuf, " Wrote %lld bytes of data\n\n", (long long)(len*wid*4)); printLog(logbuf); } return 0; }
int main(int argc, char *argv[]) { if (argc != 8) usage(); int type = 0; // 0=?, 1=sinc, 2=pole, 3=pyr char *in = argv[6]; char *out = argv[7]; int line = atoi(argv[2]); int samp = atoi(argv[3]); int radius = atoi(argv[4]); float height = atof(argv[5]); if (strcmp(argv[1], "-sinc")==0) type=1; if (strcmp(argv[1], "-pole")==0) type=2; if (strcmp(argv[1], "-pyr")==0) type=3; if (type==0) { printf("Unknown pole type.\n"); usage(); } printf("Adding a pole:\n"); printf(" Center point: (%d,%d)\n", line, samp); printf(" Radius: %d\n", radius); printf(" Height: %f\n", height); if (type!=2) printf(" Note that the height value is **added** to the existing " "terrain height.\n\n"); printf(" Input file: %s\n", in); printf(" Output file: %s\n", out); printf(" Pole type: %s\n", argv[1]+1); meta_parameters *meta = meta_read(in); int ns = meta->general->sample_count; int nl = meta->general->line_count; FILE *inDEM = fopenImage(in, "rb"); FILE *outDEM = fopenImage (out, "wb"); float *demLine = (float*)MALLOC(sizeof(float)*ns); int i,l; for (l = 0; l < nl; ++l) { get_float_line(inDEM, meta, l, demLine); for (i = 0; i < ns; ++i) { double x; // sinc and pole use circular posts, real distance // pyr uses distance measured along the gridlines if (type==1 || type==2) x = hypot(i-samp, l-line); else if (type == 3) x = dmax(fabs(i-samp),fabs(l-line)); if (x < (double)radius) { if (type==1) { // sinc if (i==samp && l==line) demLine[i] = height; else { x *= M_PI/radius; demLine[i] += height * sin(x)/x; } } else if (type==2) { // pole demLine[i] = height; } else if (type==3) { // pyr demLine[i] += height * (radius-x)/radius; } else { printf("Impossible: type=%d\n", type); exit(1); } } } put_float_line(outDEM, meta, l, demLine); asfLineMeter(l,nl); } meta_write(meta, out); fclose(inDEM); fclose(outDEM); return 0; }