int closefiles(char *h_name, char *i_name, char *s_name, int fd_output[3], CELL * rowbuf[3]) { int i; struct Colors colors; struct Range range; struct History history; CELL min, max; const char *mapset; for (i = 0; i < 3; i++) { Rast_close(fd_output[i]); G_free(rowbuf[i]); } mapset = G_mapset(); /* write colors */ /* set to 0,max_level instead of min,max ?? */ Rast_read_range(h_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(h_name, mapset, &colors); Rast_read_range(i_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(i_name, mapset, &colors); Rast_read_range(s_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(s_name, mapset, &colors); /* write metadata */ Rast_short_history(h_name, "raster", &history); Rast_command_history(&history); Rast_write_history(h_name, &history); Rast_put_cell_title(h_name, "Image hue"); Rast_short_history(i_name, "raster", &history); Rast_command_history(&history); Rast_write_history(i_name, &history); Rast_put_cell_title(i_name, "Image intensity"); Rast_short_history(s_name, "raster", &history); Rast_command_history(&history); Rast_write_history(s_name, &history); Rast_put_cell_title(s_name, "Image saturation"); return 0; }
int write_contrast_colors (char* raster) { struct Colors colors; struct Categories cats; FCOLORS fcolors[9]={ /* colors for positive openness */ {-2500, 0, 0, 50, NULL}, {-100, 0, 0, 56, NULL}, {-15, 0, 56, 128, NULL}, {-3, 0, 128, 255, NULL}, {0, 255, 255, 255, NULL}, {3, 255, 128, 0, NULL}, {15, 128, 56, 0, NULL}, {100, 56, 0, 0, NULL}, {2500, 50, 0, 0, NULL}}; int i; Rast_init_colors(&colors); for(i=0;i<8;++i) Rast_add_d_color_rule( &fcolors[i].cat, fcolors[i].r, fcolors[i].g, fcolors[i].b, &fcolors[i+1].cat, fcolors[i+1].r, fcolors[i+1].g, fcolors[i+1].b, &colors); Rast_write_colors(raster, G_mapset(), &colors); Rast_free_colors(&colors); /* Rast_init_cats("Forms", &cats); for(i=0;i<8;++i) Rast_set_cat(&ccolors[i].cat, &ccolors[i].cat, ccolors[i].label, &cats, CELL_TYPE); Rast_write_cats(raster, &cats); Rast_free_cats(&cats); */ return 0; }
/* ---------------------------------------------------------------------- */ void setFlowAccuColorTable(char* cellname) { struct Colors colors; const char *mapset; struct Range r; mapset = G_find_raster(cellname, ""); if (mapset == NULL) { G_fatal_error (_("Raster map <%s> not found"), cellname); } if (Rast_read_range(cellname, mapset, &r) == -1) { G_fatal_error(_("cannot read range")); } /*fprintf(stderr, "%s range is: min=%d, max=%d\n", cellname, r.min, r.max);*/ int v[6]; v[0] = r.min; v[1] = 5; v[2] = 30; v[3] = 100; v[4] = 1000; v[5] = r.max; Rast_init_colors(&colors); Rast_add_c_color_rule(&v[0], 255,255,255, &v[1], 255,255,0, &colors); Rast_add_c_color_rule(&v[1], 255,255,0, &v[2], 0,255,255, &colors); Rast_add_c_color_rule(&v[2], 0,255,255, &v[3], 0,127,255, &colors); Rast_add_c_color_rule(&v[3], 0,127,255, &v[4], 0,0,255, &colors); Rast_add_c_color_rule(&v[4], 0,0,255, &v[5], 0,0,0, &colors); Rast_write_colors(cellname, mapset, &colors); Rast_free_colors(&colors); }
/* Copy the colors from map named iname to the map named oname */ static void copy_colors(const char *iname, char *oname) { struct Colors colors; Rast_read_colors(iname, "", &colors); Rast_write_colors(oname, G_mapset(), &colors); }
static void fft_colors(const char *name) { struct Colors colors; struct FPRange range; DCELL min, max; /* make a real component color table */ Rast_read_fp_range(name, G_mapset(), &range); Rast_get_fp_range_min_max(&range, &min, &max); Rast_make_grey_scale_fp_colors(&colors, min, max); Rast_write_colors(name, G_mapset(), &colors); }
static void write_colors_float(int c) { channel *ch = &channels[c]; FCELL i0 = 0.0; FCELL i1 = 1.0; struct Colors colors; Rast_init_colors(&colors); Rast_add_f_color_rule(&i0, 0, 0, 0, &i1, 255, 255, 255, &colors); Rast_write_colors(ch->name, G_mapset(), &colors); }
static void do_output(int base_fd, char **outputs, const char *covermap) { int *out_fd = G_malloc(num_quants * sizeof(int)); CELL *base_buf = Rast_allocate_c_buf(); DCELL *out_buf = Rast_allocate_d_buf(); const char *mapset = G_mapset(); struct Colors colors; int have_colors; int quant; int row, col; G_message(_("Writing output maps")); for (quant = 0; quant < num_quants; quant++) { const char *output = outputs[quant]; out_fd[quant] = Rast_open_fp_new(output); } have_colors = Rast_read_colors(covermap, "", &colors) > 0; for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); for (quant = 0; quant < num_quants; quant++) { for (col = 0; col < cols; col++) if (Rast_is_c_null_value(&base_buf[col])) Rast_set_d_null_value(&out_buf[col], 1); else out_buf[col] = basecats[base_buf[col] - min].quants[quant]; Rast_put_d_row(out_fd[quant], out_buf); } G_percent(row, rows, 2); } G_percent(row, rows, 2); for (quant = 0; quant < num_quants; quant++) { Rast_close(out_fd[quant]); if (have_colors) Rast_write_colors(outputs[quant], mapset, &colors); } }
static void write_support_files(int xtile, int ytile, int overlap) { char name[GNAME_MAX]; struct Cell_head cellhd; char title[64]; struct History history; struct Colors colors; struct Categories cats; sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile); Rast_get_cellhd(name, G_mapset(), &cellhd); cellhd.north = src_w.north - ytile * dst_w.rows * src_w.ns_res; cellhd.south = cellhd.north - (dst_w.rows + 2 * overlap) * src_w.ns_res; cellhd.west = src_w.west + xtile * dst_w.cols * src_w.ew_res; cellhd.east = cellhd.west + (dst_w.cols + 2 * overlap) * src_w.ew_res; Rast_put_cellhd(name, &cellhd); /* copy cats from source map */ if (Rast_read_cats(parm.rastin->answer, "", &cats) < 0) G_fatal_error(_("Unable to read cats for %s"), parm.rastin->answer); Rast_write_cats(name, &cats); /* record map metadata/history info */ G_debug(1, "Tile %d,%d of %s: writing %s", xtile, ytile, parm.rastin->answer, name); sprintf(title, "Tile %d,%d of %s", xtile, ytile, parm.rastin->answer); Rast_put_cell_title(name, title); Rast_short_history(name, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); Rast_command_history(&history); Rast_write_history(name, &history); /* copy color table from source map */ if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); if (map_type != CELL_TYPE) Rast_mark_colors_as_fp(&colors); Rast_write_colors(name, G_mapset(), &colors); }
/* ---------------------------------------------------------------------- */ void setSinkWatershedColorTable(char* cellname) { struct Colors colors; const char *mapset; struct Range r; mapset = G_find_raster(cellname, ""); if (mapset == NULL) { G_fatal_error (_("Raster map <%s> not found"), cellname); } if (Rast_read_range(cellname, mapset, &r) == -1) { G_fatal_error(_("cannot read range")); } Rast_init_colors(&colors); Rast_make_random_colors(&colors, 1, r.max); Rast_write_colors(cellname, mapset, &colors); Rast_free_colors(&colors); }
int write_form_cat_colors (char* raster, CATCOLORS* ccolors) { struct Colors colors; struct Categories cats; int i; Rast_init_colors(&colors); for(i=1;i<CNT;++i) Rast_add_color_rule( &ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b, &ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b, &colors, CELL_TYPE); Rast_write_colors(raster, G_mapset(), &colors); Rast_free_colors(&colors); Rast_init_cats("Forms", &cats); for(i=1;i<CNT;++i) Rast_set_cat(&ccolors[i].cat, &ccolors[i].cat, ccolors[i].label, &cats, CELL_TYPE); Rast_write_cats(raster, &cats); Rast_free_cats(&cats); return 0; }
static void write_colors_int(int c) { channel *ch = &channels[c]; CELL i0 = 0; CELL i1 = ch->maxval; struct Colors colors; int i; Rast_init_colors(&colors); if (color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; int num_palette; png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette); for (i = 0; i < num_palette; i++) { png_colorp col = &palette[i]; Rast_set_c_color((CELL) i, col->red, col->green, col->blue, &colors); } } else if (c == C_A || t_gamma == 1.0) Rast_add_c_color_rule(&i0, 0, 0, 0, &i1, 255, 255, 255, &colors); else for (i = 0; i <= i1; i++) { int v = intensity((double) i / i1); Rast_set_c_color((CELL) i, v, v, v, &colors); } Rast_write_colors(ch->name, G_mapset(), &colors); }
void write_cols(void) { struct Colors colours; CELL val1, val2; Rast_init_colors(&colours); val1 = FLAT; val2 = PIT; Rast_add_c_color_rule(&val1, 180, 180, 180, /* White */ &val2, 0, 0, 0, &colours); /* Black */ val1 = CHANNEL; val2 = PASS; Rast_add_c_color_rule(&val1, 0, 0, 255, /* Blue */ &val2, 0, 255, 0, &colours); /* Green */ val1 = RIDGE; val2 = PEAK; Rast_add_c_color_rule(&val1, 255, 255, 0, /* Yellow */ &val2, 255, 0, 0, &colours); /* Red */ Rast_write_colors(rast_out_name, G_mapset(), &colours); Rast_free_colors(&colours); }
int main(int argc, char *argv[]) { int fd[NFILES]; int outfd; int i; const char *name; const char *output; const char *mapset; int non_zero; struct Range range; CELL ncats, max_cats; int primary; struct Categories pcats; struct Colors pcolr; char buf[1024]; CELL result; struct GModule *module; struct { struct Option *input, *output; } parm; struct { struct Flag *z; } flag; G_gisinit(argv[0]); /* Define the different options */ module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Creates a cross product of the category values from " "multiple raster map layers."); parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->multiple = YES; parm.input->gisprompt = "old,cell,raster"; sprintf(buf, _("Names of 2-%d input raster maps"), NFILES); parm.input->description = G_store(buf); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); /* Define the different flags */ flag.z = G_define_flag(); flag.z->key = 'z'; flag.z->description = _("Non-zero data only"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); nfiles = 0; non_zero = flag.z->answer; for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) { if (nfiles >= NFILES) G_fatal_error(_("More than %d files not allowed"), NFILES); mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); names[nfiles] = name; fd[nfiles] = Rast_open_old(name, mapset); Rast_read_range(name, mapset, &range); ncats = range.max - range.min; if (nfiles == 0 || ncats > max_cats) { primary = nfiles; max_cats = ncats; } } if (nfiles <= 1) G_fatal_error(_("Must specify 2 or more input maps")); output = parm.output->answer; outfd = Rast_open_c_new(output); sprintf(buf, "Cross of %s", names[0]); for (i = 1; i < nfiles - 1; i++) { strcat(buf, ", "); strcat(buf, names[i]); } strcat(buf, " and "); strcat(buf, names[i]); Rast_init_cats(buf, &pcats); /* first step is cross product, but un-ordered */ result = cross(fd, non_zero, primary, outfd); /* print message STEP mesage */ G_message(_("%s: STEP 2 ..."), G_program_name()); /* now close all files */ for (i = 0; i < nfiles; i++) Rast_close(fd[i]); Rast_close(outfd); if (result <= 0) exit(0); /* build the renumbering/reclass and the new cats file */ qsort(reclass, result + 1, sizeof(RECLASS), cmp); table = (CELL *) G_calloc(result + 1, sizeof(CELL)); for (i = 0; i < nfiles; i++) { mapset = G_find_raster2(names[i], ""); Rast_read_cats(names[i], mapset, &labels[i]); } for (ncats = 0; ncats <= result; ncats++) { table[reclass[ncats].result] = ncats; set_cat(ncats, reclass[ncats].cat, &pcats); } for (i = 0; i < nfiles; i++) Rast_free_cats(&labels[i]); /* reopen the output cell for reading and for writing */ fd[0] = Rast_open_old(output, G_mapset()); outfd = Rast_open_c_new(output); renumber(fd[0], outfd); G_message(_("Creating support files for <%s>..."), output); Rast_close(fd[0]); Rast_close(outfd); Rast_write_cats(output, &pcats); Rast_free_cats(&pcats); if (result > 0) { Rast_make_random_colors(&pcolr, (CELL) 1, result); Rast_write_colors(output, G_mapset(), &pcolr); } G_message(_("%ld categories"), (long)result); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *rastin, *rastout, *method, *quantile; } parm; struct { struct Flag *nulls, *weight; } flag; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int row; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a coarser grid using aggregation."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->description = _("Aggregation method"); parm.method->options = build_method_list(); parm.method->answer = "average"; parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.nulls = G_define_flag(); flag.nulls->key = 'n'; flag.nulls->description = _("Propagate NULLs"); flag.weight = G_define_flag(); flag.weight->key = 'w'; flag.weight->description = _("Weight according to area (slower)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nulls = flag.nulls->answer; method = find_method(parm.method->answer); if (method < 0) G_fatal_error(_("Unknown method <%s>"), parm.method->answer); if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); /* enlarge source window */ { int r0 = (int)floor(Rast_northing_to_row(dst_w.north, &src_w)); int r1 = (int)ceil(Rast_northing_to_row(dst_w.south, &src_w)); int c0 = (int)floor(Rast_easting_to_col(dst_w.west, &src_w)); int c1 = (int)ceil(Rast_easting_to_col(dst_w.east, &src_w)); src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); Rast_set_output_window(&dst_w); row_scale = 2 + ceil(dst_w.ns_res / src_w.ns_res); col_scale = 2 + ceil(dst_w.ew_res / src_w.ew_res); /* allocate buffers for input rows */ bufs = G_malloc(row_scale * sizeof(DCELL *)); for (row = 0; row < row_scale; row++) bufs[row] = Rast_allocate_d_input_buf(); /* open old map */ infile = Rast_open_old(parm.rastin->answer, ""); /* allocate output buffer */ outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(parm.rastout->answer, DCELL_TYPE); if (flag.weight->answer && menu[method].method_w) resamp_weighted(); else resamp_unweighted(); G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Aggregate resample by %s", parm.method->answer); Rast_put_cell_title(parm.rastout->answer, title); Rast_short_history(parm.rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(parm.rastout->answer, &history); /* copy color table from source map */ if (strcmp(parm.method->answer, "sum") != 0) { if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(parm.rastout->answer, G_mapset(), &colors); } return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKA, *PATM, *G0; char *ETa; /* input-output cell values */ DCELL d_tempka, d_pt_patm, d_rnet, d_g0; DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0, *input_PT; struct Option *output; struct Flag *zero; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "Priestley and Taylor formulation, 1972."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "net_radiation"; input_RNET->description = _("Name of input net radiation raster map [W/m2]"); input_G0 = G_define_standard_option(G_OPT_R_INPUT); input_G0->key = "soil_heatflux"; input_G0->description = _("Name of input soil heat flux raster map [W/m2]"); input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKA->key = "air_temperature"; input_TEMPKA->description = _("Name of input air temperature raster map [K]"); input_PATM = G_define_standard_option(G_OPT_R_INPUT); input_PATM->key = "atmospheric_pressure"; input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]"); input_PT = G_define_option(); input_PT->key = "priestley_taylor_coeff"; input_PT->type = TYPE_DOUBLE; input_PT->required = YES; input_PT->description = _("Priestley-Taylor coefficient"); input_PT->answer = "1.26"; output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name of output evapotranspiration raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKA = input_TEMPKA->answer; PATM = input_PATM->answer; G0 = input_G0->answer; d_pt_alpha = atof(input_PT->answer); ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKA = Rast_open_old(TEMPKA, ""); infd_PATM = Rast_open_old(PATM, ""); infd_G0 = Rast_open_old(G0, ""); /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKA, "", &cellhd); Rast_get_cellhd(PATM, "", &cellhd); Rast_get_cellhd(G0, "", &cellhd); /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKA = Rast_allocate_d_buf(); inrast_PATM = Rast_allocate_d_buf(); inrast_G0 = Rast_allocate_d_buf(); /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row); Rast_get_d_row(infd_PATM, inrast_PATM, row); Rast_get_d_row(infd_G0, inrast_G0, row); for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempka = ((DCELL *) inrast_TEMPKA)[col]; d_pt_patm = ((DCELL *) inrast_PATM)[col]; d_g0 = ((DCELL *) inrast_G0)[col]; /*Delta_pt and Ghamma_pt */ d_pt_delta = pt_delta(d_tempka); d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm); /*Calculate ET */ d_daily_et = pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0, d_tempka); if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKA); G_free(inrast_PATM); G_free(inrast_G0); Rast_close(infd_RNET); Rast_close(infd_TEMPKA); Rast_close(infd_PATM); Rast_close(infd_G0); /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct Option *rastin, *rastout, *method; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int infile, outfile; DCELL *outbuf; int row, col; struct Cell_head dst_w, src_w; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a finer grid using interpolation."); rastin = G_define_standard_option(G_OPT_R_INPUT); rastout = G_define_standard_option(G_OPT_R_OUTPUT); method = G_define_option(); method->key = "method"; method->type = TYPE_STRING; method->required = NO; method->description = _("Interpolation method"); method->options = "nearest,bilinear,bicubic,lanczos"; method->answer = "bilinear"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (G_strcasecmp(method->answer, "nearest") == 0) neighbors = 1; else if (G_strcasecmp(method->answer, "bilinear") == 0) neighbors = 2; else if (G_strcasecmp(method->answer, "bicubic") == 0) neighbors = 4; else if (G_strcasecmp(method->answer, "lanczos") == 0) neighbors = 5; else G_fatal_error(_("Invalid method: %s"), method->answer); G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(rastin->answer, "", &src_w); /* enlarge source window */ { double north = Rast_row_to_northing(0.5, &dst_w); double south = Rast_row_to_northing(dst_w.rows - 0.5, &dst_w); int r0 = (int)floor(Rast_northing_to_row(north, &src_w) - 0.5) - 2; int r1 = (int)floor(Rast_northing_to_row(south, &src_w) - 0.5) + 3; double west = Rast_col_to_easting(0.5, &dst_w); double east = Rast_col_to_easting(dst_w.cols - 0.5, &dst_w); int c0 = (int)floor(Rast_easting_to_col(west, &src_w) - 0.5) - 2; int c1 = (int)floor(Rast_easting_to_col(east, &src_w) - 0.5) + 3; src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); /* allocate buffers for input rows */ for (row = 0; row < neighbors; row++) bufs[row] = Rast_allocate_d_input_buf(); cur_row = -100; /* open old map */ infile = Rast_open_old(rastin->answer, ""); /* reset window to current region */ Rast_set_output_window(&dst_w); outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(rastout->answer, DCELL_TYPE); switch (neighbors) { case 1: /* nearest */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f + 0.5); G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f + 0.5); double c = bufs[0][mapcol0]; if (Rast_is_d_null_value(&c)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = c; } } Rast_put_d_row(outfile, outbuf); } break; case 2: /* bilinear */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f); double v = maprow_f - maprow0; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f); int mapcol1 = mapcol0 + 1; double u = mapcol_f - mapcol0; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bilinear(u, v, c00, c01, c10, c11); } } Rast_put_d_row(outfile, outbuf); } break; case 4: /* bicubic */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f); int maprow0 = maprow1 - 1; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol1 = (int)floor(mapcol_f); int mapcol0 = mapcol1 - 1; int mapcol2 = mapcol1 + 1; int mapcol3 = mapcol1 + 2; double u = mapcol_f - mapcol1; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c02 = bufs[0][mapcol2]; double c03 = bufs[0][mapcol3]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; double c12 = bufs[1][mapcol2]; double c13 = bufs[1][mapcol3]; double c20 = bufs[2][mapcol0]; double c21 = bufs[2][mapcol1]; double c22 = bufs[2][mapcol2]; double c23 = bufs[2][mapcol3]; double c30 = bufs[3][mapcol0]; double c31 = bufs[3][mapcol1]; double c32 = bufs[3][mapcol2]; double c33 = bufs[3][mapcol3]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c02) || Rast_is_d_null_value(&c03) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11) || Rast_is_d_null_value(&c12) || Rast_is_d_null_value(&c13) || Rast_is_d_null_value(&c20) || Rast_is_d_null_value(&c21) || Rast_is_d_null_value(&c22) || Rast_is_d_null_value(&c23) || Rast_is_d_null_value(&c30) || Rast_is_d_null_value(&c31) || Rast_is_d_null_value(&c32) || Rast_is_d_null_value(&c33)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bicubic(u, v, c00, c01, c02, c03, c10, c11, c12, c13, c20, c21, c22, c23, c30, c31, c32, c33); } } Rast_put_d_row(outfile, outbuf); } break; case 5: /* lanczos */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f + 0.5); int maprow0 = maprow1 - 2; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol2 = (int)floor(mapcol_f + 0.5); int mapcol0 = mapcol2 - 2; int mapcol4 = mapcol2 + 2; double u = mapcol_f - mapcol2; double c[25]; int ci = 0, i, j, do_lanczos = 1; for (i = 0; i < 5; i++) { for (j = mapcol0; j <= mapcol4; j++) { c[ci] = bufs[i][j]; if (Rast_is_d_null_value(&(c[ci]))) { Rast_set_d_null_value(&outbuf[col], 1); do_lanczos = 0; break; } ci++; } if (!do_lanczos) break; } if (do_lanczos) { outbuf[col] = Rast_interp_lanczos(u, v, c); } } Rast_put_d_row(outfile, outbuf); } break; } G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Resample by %s interpolation", method->answer); Rast_put_cell_title(rastout->answer, title); Rast_short_history(rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(rastout->answer, &history); /* copy color table from source map */ if (Rast_read_colors(rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(rastout->answer, G_mapset(), &colors); return (EXIT_SUCCESS); }
int main(int argc, char **argv) { static DCELL *count, *sum, *mean, *sumu, *sum2, *sum3, *sum4, *min, *max; DCELL *result; struct GModule *module; struct { struct Option *method, *basemap, *covermap, *output; } opt; struct { struct Flag *c, *r; } flag; char methods[2048]; const char *basemap, *covermap, *output; int usecats; int reclass; int base_fd, cover_fd; struct Categories cats; CELL *base_buf; DCELL *cover_buf; struct Range range; CELL mincat, ncats; int method; int rows, cols; int row, col, i; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Calculates category or object oriented statistics (accumulator-based statistics)."); opt.basemap = G_define_standard_option(G_OPT_R_BASE); opt.covermap = G_define_standard_option(G_OPT_R_COVER); opt.method = G_define_option(); opt.method->key = "method"; opt.method->type = TYPE_STRING; opt.method->required = YES; opt.method->description = _("Method of object-based statistic"); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ","); else *(methods) = 0; strcat(methods, menu[i].name); } opt.method->options = G_store(methods); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ";"); else *(methods) = 0; strcat(methods, menu[i].name); strcat(methods, ";"); strcat(methods, menu[i].text); } opt.method->descriptions = G_store(methods); opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.output->description = _("Resultant raster map"); opt.output->required = YES; flag.c = G_define_flag(); flag.c->key = 'c'; flag.c->description = _("Cover values extracted from the category labels of the cover map"); flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Create reclass map with statistics as category labels"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); basemap = opt.basemap->answer; covermap = opt.covermap->answer; output = opt.output->answer; usecats = flag.c->answer; reclass = flag.r->answer; for (i = 0; menu[i].name; i++) if (strcmp(menu[i].name, opt.method->answer) == 0) break; if (!menu[i].name) { G_warning(_("<%s=%s> unknown %s"), opt.method->key, opt.method->answer, opt.method->key); G_usage(); exit(EXIT_FAILURE); } method = menu[i].val; base_fd = Rast_open_old(basemap, ""); cover_fd = Rast_open_old(covermap, ""); if (usecats && Rast_read_cats(covermap, "", &cats) < 0) G_fatal_error(_("Unable to read category file of cover map <%s>"), covermap); if (Rast_map_is_fp(basemap, "") != 0) G_fatal_error(_("The base map must be an integer (CELL) map")); if (Rast_read_range(basemap, "", &range) < 0) G_fatal_error(_("Unable to read range of base map <%s>"), basemap); mincat = range.min; ncats = range.max - range.min + 1; rows = Rast_window_rows(); cols = Rast_window_cols(); switch (method) { case COUNT: count = G_calloc(ncats, sizeof(DCELL)); break; case SUM: sum = G_calloc(ncats, sizeof(DCELL)); break; case MIN: min = G_malloc(ncats * sizeof(DCELL)); break; case MAX: max = G_malloc(ncats * sizeof(DCELL)); break; case RANGE: min = G_malloc(ncats * sizeof(DCELL)); max = G_malloc(ncats * sizeof(DCELL)); break; case AVERAGE: case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE1: case STDDEV1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (min) for (i = 0; i < ncats; i++) min[i] = 1e300; if (max) for (i = 0; i < ncats; i++) max[i] = -1e300; base_buf = Rast_allocate_c_buf(); cover_buf = Rast_allocate_d_buf(); G_message(_("First pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); if (count) count[n]++; if (sum) sum[n] += v; if (sum2) sum2[n] += v * v; if (sum3) sum3[n] += v * v * v; if (sum4) sum4[n] += v * v * v * v; if (min && min[n] > v) min[n] = v; if (max && max[n] < v) max[n] = v; } G_percent(row, rows, 2); } G_percent(row, rows, 2); result = G_calloc(ncats, sizeof(DCELL)); switch (method) { case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: mean = G_calloc(ncats, sizeof(DCELL)); for (i = 0; i < ncats; i++) mean[i] = sum[i] / count[i]; G_free(sum); break; } switch (method) { case ADEV: sumu = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE2: case STDDEV2: sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (mean) { G_message(_("Second pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v, d; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); d = v - mean[n]; if (sumu) sumu[n] += fabs(d); if (sum2) sum2[n] += d * d; if (sum3) sum3[n] += d * d * d; if (sum4) sum4[n] += d * d * d * d; } G_percent(row, rows, 2); } G_percent(row, rows, 2); G_free(mean); G_free(cover_buf); } switch (method) { case COUNT: for (i = 0; i < ncats; i++) result[i] = count[i]; break; case SUM: for (i = 0; i < ncats; i++) result[i] = sum[i]; break; case AVERAGE: for (i = 0; i < ncats; i++) result[i] = sum[i] / count[i]; break; case MIN: for (i = 0; i < ncats; i++) result[i] = min[i]; break; case MAX: for (i = 0; i < ncats; i++) result[i] = max[i]; break; case RANGE: for (i = 0; i < ncats; i++) result[i] = max[i] - min[i]; break; case VARIANCE1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = var; } break; case STDDEV1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = sqrt(var); } break; case SKEWNESS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double skew = (sum3[i] / n - 3 * sum[i] * sum2[i] / (n * n) + 2 * sum[i] * sum[i] * sum[i] / (n * n * n)) / (pow(var, 1.5)); result[i] = skew; } break; case KURTOSIS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double kurt = (sum4[i] / n - 4 * sum[i] * sum3[i] / (n * n) + 6 * sum[i] * sum[i] * sum2[i] / (n * n * n) - 3 * sum[i] * sum[i] * sum[i] * sum[i] / (n * n * n * n)) / (var * var) - 3; result[i] = kurt; } break; case ADEV: for (i = 0; i < ncats; i++) result[i] = sumu[i] / count[i]; break; case VARIANCE2: for (i = 0; i < ncats; i++) result[i] = sum2[i] / (count[i] - 1); break; case STDDEV2: for (i = 0; i < ncats; i++) result[i] = sqrt(sum2[i] / (count[i] - 1)); break; case SKEWNESS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); double sdev = sqrt(var); result[i] = sum3[i] / (sdev * sdev * sdev) / n; } G_free(count); G_free(sum2); G_free(sum3); break; case KURTOSIS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); result[i] = sum4[i] / (var * var) / n - 3; } G_free(count); G_free(sum2); G_free(sum4); break; } if (reclass) { const char *tempfile = G_tempfile(); char *input_arg = G_malloc(strlen(basemap) + 7); char *output_arg = G_malloc(strlen(output) + 8); char *rules_arg = G_malloc(strlen(tempfile) + 7); FILE *fp; G_message(_("Generating reclass map")); sprintf(input_arg, "input=%s", basemap); sprintf(output_arg, "output=%s", output); sprintf(rules_arg, "rules=%s", tempfile); fp = fopen(tempfile, "w"); if (!fp) G_fatal_error(_("Unable to open temporary file")); for (i = 0; i < ncats; i++) fprintf(fp, "%d = %d %f\n", mincat + i, mincat + i, result[i]); fclose(fp); G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL); } else { int out_fd; DCELL *out_buf; struct Colors colors; G_message(_("Writing output map")); out_fd = Rast_open_fp_new(output); out_buf = Rast_allocate_d_buf(); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); for (col = 0; col < cols; col++) if (Rast_is_c_null_value(&base_buf[col])) Rast_set_d_null_value(&out_buf[col], 1); else out_buf[col] = result[base_buf[col] - mincat]; Rast_put_d_row(out_fd, out_buf); G_percent(row, rows, 2); } G_percent(row, rows, 2); Rast_close(out_fd); if (Rast_read_colors(covermap, "", &colors) > 0) Rast_write_colors(output, G_mapset(), &colors); } return 0; }
int close_maps(char *stream_rast, char *stream_vect, char *dir_rast) { int stream_fd, dir_fd, r, c, i; CELL *cell_buf1, *cell_buf2; struct History history; CELL stream_id; ASP_FLAG af; /* cheating... */ stream_fd = dir_fd = -1; cell_buf1 = cell_buf2 = NULL; G_message(_("Writing output raster maps...")); /* write requested output rasters */ if (stream_rast) { stream_fd = Rast_open_new(stream_rast, CELL_TYPE); cell_buf1 = Rast_allocate_c_buf(); } if (dir_rast) { dir_fd = Rast_open_new(dir_rast, CELL_TYPE); cell_buf2 = Rast_allocate_c_buf(); } for (r = 0; r < nrows; r++) { G_percent(r, nrows, 2); if (stream_rast) Rast_set_c_null_value(cell_buf1, ncols); /* reset row to all NULL */ if (dir_rast) Rast_set_c_null_value(cell_buf2, ncols); /* reset row to all NULL */ for (c = 0; c < ncols; c++) { if (stream_rast) { cseg_get(&stream, &stream_id, r, c); if (stream_id) cell_buf1[c] = stream_id; } if (dir_rast) { seg_get(&aspflag, (char *)&af, r, c); if (!FLAG_GET(af.flag, NULLFLAG)) { cell_buf2[c] = af.asp; } } } if (stream_rast) Rast_put_row(stream_fd, cell_buf1, CELL_TYPE); if (dir_rast) Rast_put_row(dir_fd, cell_buf2, CELL_TYPE); } G_percent(nrows, nrows, 2); /* finish it */ if (stream_rast) { Rast_close(stream_fd); G_free(cell_buf1); Rast_short_history(stream_rast, "raster", &history); Rast_command_history(&history); Rast_write_history(stream_rast, &history); } if (dir_rast) { struct Colors colors; Rast_close(dir_fd); G_free(cell_buf2); Rast_short_history(dir_rast, "raster", &history); Rast_command_history(&history); Rast_write_history(dir_rast, &history); Rast_init_colors(&colors); Rast_make_aspect_colors(&colors, -8, 8); Rast_write_colors(dir_rast, G_mapset(), &colors); } /* close stream vector */ if (stream_vect) { if (close_streamvect(stream_vect) < 0) G_fatal_error(_("Unable to write vector map <%s>"), stream_vect); } /* rearranging desk chairs on the Titanic... */ G_free(outlets); /* free stream nodes */ for (i = 1; i <= n_stream_nodes; i++) { if (stream_node[i].n_alloc > 0) { G_free(stream_node[i].trib); } } G_free(stream_node); return 1; }
int main(int argc, char *argv[]) { char *p; int method; int in_fd; int selection_fd; int out_fd; DCELL *result; char *selection; RASTER_MAP_TYPE map_type; int row, col; int readrow; int nrows, ncols; int n; int copycolr; int half; stat_func *newvalue; stat_func_w *newvalue_w; ifunc cat_names; double quantile; const void *closure; struct Colors colr; struct Cell_head cellhd; struct Cell_head window; struct History history; struct GModule *module; struct { struct Option *input, *output, *selection; struct Option *method, *size; struct Option *title; struct Option *weight; struct Option *gauss; struct Option *quantile; } parm; struct { struct Flag *align, *circle; } flag; DCELL *values; /* list of neighborhood values */ DCELL(*values_w)[2]; /* list of neighborhood values and weights */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("algebra")); G_add_keyword(_("statistics")); module->description = _("Makes each cell category value a " "function of the category values assigned to the cells " "around it, and stores new cell values in an output raster " "map layer."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.selection = G_define_standard_option(G_OPT_R_INPUT); parm.selection->key = "selection"; parm.selection->required = NO; parm.selection->description = _("Name of an input raster map to select the cells which should be processed"); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->answer = "average"; p = G_malloc(1024); for (n = 0; menu[n].name; n++) { if (n) strcat(p, ","); else *p = 0; strcat(p, menu[n].name); } parm.method->options = p; parm.method->description = _("Neighborhood operation"); parm.method->guisection = _("Neighborhood"); parm.size = G_define_option(); parm.size->key = "size"; parm.size->type = TYPE_INTEGER; parm.size->required = NO; parm.size->description = _("Neighborhood size"); parm.size->answer = "3"; parm.size->guisection = _("Neighborhood"); parm.title = G_define_option(); parm.title->key = "title"; parm.title->key_desc = "phrase"; parm.title->type = TYPE_STRING; parm.title->required = NO; parm.title->description = _("Title of the output raster map"); parm.weight = G_define_standard_option(G_OPT_F_INPUT); parm.weight->key = "weight"; parm.weight->required = NO; parm.weight->description = _("Text file containing weights"); parm.gauss = G_define_option(); parm.gauss->key = "gauss"; parm.gauss->type = TYPE_DOUBLE; parm.gauss->required = NO; parm.gauss->description = _("Sigma (in cells) for Gaussian filter"); parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.align = G_define_flag(); flag.align->key = 'a'; flag.align->description = _("Do not align output with the input"); flag.circle = G_define_flag(); flag.circle->key = 'c'; flag.circle->description = _("Use circular neighborhood"); flag.circle->guisection = _("Neighborhood"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); sscanf(parm.size->answer, "%d", &ncb.nsize); if (ncb.nsize <= 0) G_fatal_error(_("Neighborhood size must be positive")); if (ncb.nsize % 2 == 0) G_fatal_error(_("Neighborhood size must be odd")); ncb.dist = ncb.nsize / 2; if (parm.weight->answer && flag.circle->answer) G_fatal_error(_("weight= and -c are mutually exclusive")); if (parm.weight->answer && parm.gauss->answer) G_fatal_error(_("weight= and gauss= are mutually exclusive")); ncb.oldcell = parm.input->answer; ncb.newcell = parm.output->answer; if (!flag.align->answer) { Rast_get_cellhd(ncb.oldcell, "", &cellhd); G_get_window(&window); Rast_align_window(&window, &cellhd); Rast_set_window(&window); } nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* open raster maps */ in_fd = Rast_open_old(ncb.oldcell, ""); map_type = Rast_get_map_type(in_fd); /* get the method */ for (method = 0; (p = menu[method].name); method++) if ((strcmp(p, parm.method->answer) == 0)) break; if (!p) { G_warning(_("<%s=%s> unknown %s"), parm.method->key, parm.method->answer, parm.method->key); G_usage(); exit(EXIT_FAILURE); } if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } half = (map_type == CELL_TYPE) ? menu[method].half : 0; /* establish the newvalue routine */ newvalue = menu[method].method; newvalue_w = menu[method].method_w; /* copy color table? */ copycolr = menu[method].copycolr; if (copycolr) { G_suppress_warnings(1); copycolr = (Rast_read_colors(ncb.oldcell, "", &colr) > 0); G_suppress_warnings(0); } /* read the weights */ if (parm.weight->answer) { read_weights(parm.weight->answer); if (!newvalue_w) weights_mask(); } else if (parm.gauss->answer) { if (!newvalue_w) G_fatal_error(_("Method %s not compatible with Gaussian filter"), parm.method->answer); gaussian_weights(atof(parm.gauss->answer)); } else newvalue_w = NULL; /* allocate the cell buffers */ allocate_bufs(); result = Rast_allocate_d_buf(); /* get title, initialize the category and stat info */ if (parm.title->answer) strcpy(ncb.title, parm.title->answer); else sprintf(ncb.title, "%dx%d neighborhood: %s of %s", ncb.nsize, ncb.nsize, menu[method].name, ncb.oldcell); /* initialize the cell bufs with 'dist' rows of the old cellfile */ readrow = 0; for (row = 0; row < ncb.dist; row++) readcell(in_fd, readrow++, nrows, ncols); /* open the selection raster map */ if (parm.selection->answer) { G_message(_("Opening selection map <%s>"), parm.selection->answer); selection_fd = Rast_open_old(parm.selection->answer, ""); selection = Rast_allocate_null_buf(); } else { selection_fd = -1; selection = NULL; } /*open the new raster map */ out_fd = Rast_open_new(ncb.newcell, map_type); if (flag.circle->answer) circle_mask(); if (newvalue_w) values_w = (DCELL(*)[2]) G_malloc(ncb.nsize * ncb.nsize * 2 * sizeof(DCELL)); else values = (DCELL *) G_malloc(ncb.nsize * ncb.nsize * sizeof(DCELL)); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); readcell(in_fd, readrow++, nrows, ncols); if (selection) Rast_get_null_value_row(selection_fd, selection, row); for (col = 0; col < ncols; col++) { DCELL *rp = &result[col]; if (selection && selection[col]) { *rp = ncb.buf[ncb.dist][col]; continue; } if (newvalue_w) n = gather_w(values_w, col); else n = gather(values, col); if (n < 0) Rast_set_d_null_value(rp, 1); else { if (newvalue_w) newvalue_w(rp, values_w, n, closure); else newvalue(rp, values, n, closure); if (half && !Rast_is_d_null_value(rp)) *rp += 0.5; } } Rast_put_d_row(out_fd, result); } G_percent(row, nrows, 2); Rast_close(out_fd); Rast_close(in_fd); if (selection) Rast_close(selection_fd); /* put out category info */ null_cats(); if ((cat_names = menu[method].cat_names)) cat_names(); Rast_write_cats(ncb.newcell, &ncb.cats); if (copycolr) Rast_write_colors(ncb.newcell, G_mapset(), &colr); Rast_short_history(ncb.newcell, "raster", &history); Rast_command_history(&history); Rast_write_history(ncb.newcell, &history); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { unsigned char *hue_n, *hue_r, *hue_g, *hue_b; unsigned char *int_n, *int_r; unsigned char *sat_n, *sat_r; unsigned char *dummy; CELL *r_array, *g_array, *b_array; char *name_h, *name_i, *name_s; int intensity; int saturation; int atrow, atcol; int hue_file; int int_file = 0; int int_used; int sat_file = 0; int sat_used; char *name_r, *name_g, *name_b; int r_file = 0; int r_used; int g_file = 0; int g_used; int b_file = 0; int b_used; struct Cell_head window; struct Colors hue_colors; struct Colors int_colors; struct Colors sat_colors; struct Colors gray_colors; struct History history; struct GModule *module; struct Option *opt_h, *opt_i, *opt_s; struct Option *opt_r, *opt_g, *opt_b; struct Flag *nulldraw; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("color transformation")); G_add_keyword(_("RGB")); G_add_keyword(_("HIS")); module->description = _("Generates red, green and blue raster map layers " "combining hue, intensity and saturation (HIS) " "values from user-specified input raster map layers."); opt_h = G_define_option(); opt_h->key = "h_map"; opt_h->type = TYPE_STRING; opt_h->required = YES; opt_h->gisprompt = "old,cell,raster"; opt_h->description = _("Name of layer to be used for HUE"); opt_i = G_define_option(); opt_i->key = "i_map"; opt_i->type = TYPE_STRING; opt_i->required = NO; opt_i->gisprompt = "old,cell,raster"; opt_i->description = _("Name of layer to be used for INTENSITY"); opt_s = G_define_option(); opt_s->key = "s_map"; opt_s->type = TYPE_STRING; opt_s->required = NO; opt_s->gisprompt = "old,cell,raster"; opt_s->description = _("Name of layer to be used for SATURATION"); opt_r = G_define_option(); opt_r->key = "r_map"; opt_r->type = TYPE_STRING; opt_r->required = YES; opt_r->gisprompt = "new,cell,raster"; opt_r->description = _("Name of output layer to be used for RED"); opt_g = G_define_option(); opt_g->key = "g_map"; opt_g->type = TYPE_STRING; opt_g->required = YES; opt_g->gisprompt = "new,cell,raster"; opt_g->description = _("Name of output layer to be used for GREEN"); opt_b = G_define_option(); opt_b->key = "b_map"; opt_b->type = TYPE_STRING; opt_b->required = YES; opt_b->gisprompt = "new,cell,raster"; opt_b->description = _("Name of output layer to be used for BLUE"); nulldraw = G_define_flag(); nulldraw->key = 'n'; nulldraw->description = _("Respect NULL values while drawing"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* read in current window */ G_get_window(&window); /* Get name of layer to be used for hue */ name_h = opt_h->answer; /* Make sure map is available */ hue_file = Rast_open_old(name_h, ""); hue_r = G_malloc(window.cols); hue_g = G_malloc(window.cols); hue_b = G_malloc(window.cols); hue_n = G_malloc(window.cols); dummy = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_h, "", &hue_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_h); int_used = 0; if (opt_i->answer != NULL) { /* Get name of layer to be used for intensity */ name_i = opt_i->answer; int_used = 1; /* Make sure map is available */ int_file = Rast_open_old(name_i, ""); int_r = G_malloc(window.cols); int_n = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_i, "", &int_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_i); } sat_used = 0; if (opt_s->answer != NULL) { /* Get name of layer to be used for saturation */ name_s = opt_s->answer; sat_used = 1; /* Make sure map is available */ sat_file = Rast_open_old(name_s, ""); sat_r = G_malloc(window.cols); sat_n = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_s, "", &sat_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_s); } r_used = 0; if (opt_r->answer != NULL) { name_r = opt_r->answer; r_file = Rast_open_c_new(name_r); r_used = 1; } g_used = 0; if (opt_g->answer != NULL) { name_g = opt_g->answer; g_file = Rast_open_c_new(name_g); g_used = 1; } b_used = 0; if (opt_b->answer != NULL) { name_b = opt_b->answer; b_file = Rast_open_c_new(name_b); b_used = 1; } r_array = Rast_allocate_c_buf(); g_array = Rast_allocate_c_buf(); b_array = Rast_allocate_c_buf(); /* Make color table */ make_gray_scale(&gray_colors); /* Now do the work */ intensity = 255; /* default is to not change intensity */ saturation = 255; /* default is to not change saturation */ for (atrow = 0; atrow < window.rows; atrow++) { G_percent(atrow, window.rows, 2); Rast_get_row_colors(hue_file, atrow, &hue_colors, hue_r, hue_g, hue_b, hue_n); if (int_used) Rast_get_row_colors(int_file, atrow, &int_colors, int_r, dummy, dummy, int_n); if (sat_used) Rast_get_row_colors(sat_file, atrow, &sat_colors, sat_r, dummy, dummy, sat_n); for (atcol = 0; atcol < window.cols; atcol++) { if (nulldraw->answer) { if (hue_n[atcol] || (int_used && int_n[atcol]) || (sat_used && sat_n[atcol])) { Rast_set_c_null_value(&r_array[atcol], 1); Rast_set_c_null_value(&g_array[atcol], 1); Rast_set_c_null_value(&b_array[atcol], 1); continue; } } if (int_used) intensity = int_r[atcol]; if (sat_used) saturation = sat_r[atcol]; HIS_to_RGB(hue_r[atcol], hue_g[atcol], hue_b[atcol], intensity, saturation, &r_array[atcol], &g_array[atcol], &b_array[atcol]); } if (r_used) Rast_put_row(r_file, r_array, CELL_TYPE); if (g_used) Rast_put_row(g_file, g_array, CELL_TYPE); if (b_used) Rast_put_row(b_file, b_array, CELL_TYPE); } G_percent(window.rows, window.rows, 5); /* Close the cell files */ Rast_close(hue_file); if (int_used) Rast_close(int_file); if (sat_used) Rast_close(sat_file); if (r_used) { Rast_close(r_file); Rast_write_colors(name_r, G_mapset(), &gray_colors); Rast_short_history(name_r, "raster", &history); Rast_command_history(&history); Rast_write_history(name_r, &history); Rast_put_cell_title(name_r, "Red extracted from HIS"); } if (g_used) { Rast_close(g_file); Rast_write_colors(name_g, G_mapset(), &gray_colors); Rast_short_history(name_g, "raster", &history); Rast_command_history(&history); Rast_write_history(name_g, &history); Rast_put_cell_title(name_g, "Green extracted from HIS"); } if (b_used) { Rast_close(b_file); Rast_write_colors(name_b, G_mapset(), &gray_colors); Rast_short_history(name_b, "raster", &history); Rast_command_history(&history); Rast_write_history(name_b, &history); Rast_put_cell_title(name_b, "Blue extracted from HIS"); } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int nrows, ncols; int row, col; char *viflag; /*Switch for particular index */ char *desc; struct GModule *module; struct { struct Option *viname, *red, *nir, *green, *blue, *chan5, *chan7, *sl_slope, *sl_int, *sl_red, *bits, *output; } opt; struct History history; /*metadata */ struct Colors colors; /*Color rules */ char *result; /*output raster name */ int infd_redchan, infd_nirchan, infd_greenchan; int infd_bluechan, infd_chan5chan, infd_chan7chan; int outfd; char *bluechan, *greenchan, *redchan, *nirchan, *chan5chan, *chan7chan; DCELL *inrast_redchan, *inrast_nirchan, *inrast_greenchan; DCELL *inrast_bluechan, *inrast_chan5chan, *inrast_chan7chan; DCELL *outrast; RASTER_MAP_TYPE data_type_redchan; RASTER_MAP_TYPE data_type_nirchan, data_type_greenchan; RASTER_MAP_TYPE data_type_bluechan; RASTER_MAP_TYPE data_type_chan5chan, data_type_chan7chan; DCELL msavip1, msavip2, msavip3, dnbits; CELL val1, val2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("vegetation index")); G_add_keyword(_("biophysical parameters")); module->label = _("Calculates different types of vegetation indices."); module->description = _("Uses red and nir bands mostly, " "and some indices require additional bands."); /* Define the different options */ opt.red = G_define_standard_option(G_OPT_R_INPUT); opt.red->key = "red"; opt.red->label = _("Name of input red channel surface reflectance map"); opt.red->description = _("Range: [0.0;1.0]"); opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.viname = G_define_option(); opt.viname->key = "viname"; opt.viname->type = TYPE_STRING; opt.viname->required = YES; opt.viname->description = _("Type of vegetation index"); desc = NULL; G_asprintf(&desc, "arvi;%s;dvi;%s;evi;%s;evi2;%s;gvi;%s;gari;%s;gemi;%s;ipvi;%s;msavi;%s;" "msavi2;%s;ndvi;%s;pvi;%s;savi;%s;sr;%s;vari;%s;wdvi;%s", _("Atmospherically Resistant Vegetation Index"), _("Difference Vegetation Index"), _("Enhanced Vegetation Index"), _("Enhanced Vegetation Index 2"), _("Green Vegetation Index"), _("Green Atmospherically Resistant Vegetation Index"), _("Global Environmental Monitoring Index"), _("Infrared Percentage Vegetation Index"), _("Modified Soil Adjusted Vegetation Index"), _("second Modified Soil Adjusted Vegetation Index"), _("Normalized Difference Vegetation Index"), _("Perpendicular Vegetation Index"), _("Soil Adjusted Vegetation Index"), _("Simple Ratio"), _("Visible Atmospherically Resistant Index"), _("Weighted Difference Vegetation Index")); opt.viname->descriptions = desc; opt.viname->options = "arvi,dvi,evi,evi2,gvi,gari,gemi,ipvi,msavi,msavi2,ndvi,pvi,savi,sr,vari,wdvi"; opt.viname->answer = "ndvi"; opt.viname->key_desc = _("type"); opt.nir = G_define_standard_option(G_OPT_R_INPUT); opt.nir->key = "nir"; opt.nir->required = NO; opt.nir->label = _("Name of input nir channel surface reflectance map"); opt.nir->description = _("Range: [0.0;1.0]"); opt.nir->guisection = _("Optional inputs"); opt.green = G_define_standard_option(G_OPT_R_INPUT); opt.green->key = "green"; opt.green->required = NO; opt.green->label = _("Name of input green channel surface reflectance map"); opt.green->description = _("Range: [0.0;1.0]"); opt.green->guisection = _("Optional inputs"); opt.blue = G_define_standard_option(G_OPT_R_INPUT); opt.blue->key = "blue"; opt.blue->required = NO; opt.blue->label = _("Name of input blue channel surface reflectance map"); opt.blue->description = _("Range: [0.0;1.0]"); opt.blue->guisection = _("Optional inputs"); opt.chan5 = G_define_standard_option(G_OPT_R_INPUT); opt.chan5->key = "band5"; opt.chan5->required = NO; opt.chan5->label = _("Name of input 5th channel surface reflectance map"); opt.chan5->description = _("Range: [0.0;1.0]"); opt.chan5->guisection = _("Optional inputs"); opt.chan7 = G_define_standard_option(G_OPT_R_INPUT); opt.chan7->key = "band7"; opt.chan7->required = NO; opt.chan7->label = _("Name of input 7th channel surface reflectance map"); opt.chan7->description = _("Range: [0.0;1.0]"); opt.chan7->guisection = _("Optional inputs"); opt.sl_slope = G_define_option(); opt.sl_slope->key = "soil_line_slope"; opt.sl_slope->type = TYPE_DOUBLE; opt.sl_slope->required = NO; opt.sl_slope->description = _("Value of the slope of the soil line (MSAVI only)"); opt.sl_slope->guisection = _("MSAVI settings"); opt.sl_int = G_define_option(); opt.sl_int->key = "soil_line_intercept"; opt.sl_int->type = TYPE_DOUBLE; opt.sl_int->required = NO; opt.sl_int->description = _("Value of the intercept of the soil line (MSAVI only)"); opt.sl_int->guisection = _("MSAVI settings"); opt.sl_red = G_define_option(); opt.sl_red->key = "soil_noise_reduction"; opt.sl_red->type = TYPE_DOUBLE; opt.sl_red->required = NO; opt.sl_red->description = _("Value of the factor of reduction of soil noise (MSAVI only)"); opt.sl_red->guisection = _("MSAVI settings"); opt.bits = G_define_option(); opt.bits->key = "storage_bit"; opt.bits->type = TYPE_INTEGER; opt.bits->required = NO; opt.bits->label = _("Maximum bits for digital numbers"); opt.bits->description = _("If data is in Digital Numbers (i.e. integer type), give the max bits (i.e. 8 for Landsat -> [0-255])"); opt.bits->options = "7,8,10,16"; opt.bits->answer = "8"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); viflag = opt.viname->answer; redchan = opt.red->answer; nirchan = opt.nir->answer; greenchan = opt.green->answer; bluechan = opt.blue->answer; chan5chan = opt.chan5->answer; chan7chan = opt.chan7->answer; if(opt.sl_slope->answer) msavip1 = atof(opt.sl_slope->answer); if(opt.sl_int->answer) msavip2 = atof(opt.sl_int->answer); if(opt.sl_red->answer) msavip3 = atof(opt.sl_red->answer); if(opt.bits->answer) dnbits = atof(opt.bits->answer); result = opt.output->answer; G_verbose_message(_("Calculating %s..."), viflag); if (!strcasecmp(viflag, "sr") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("sr index requires red and nir maps")); if (!strcasecmp(viflag, "ndvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("ndvi index requires red and nir maps")); if (!strcasecmp(viflag, "ipvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("ipvi index requires red and nir maps")); if (!strcasecmp(viflag, "dvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("dvi index requires red and nir maps")); if (!strcasecmp(viflag, "pvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("pvi index requires red and nir maps")); if (!strcasecmp(viflag, "wdvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("wdvi index requires red and nir maps")); if (!strcasecmp(viflag, "savi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("savi index requires red and nir maps")); if (!strcasecmp(viflag, "msavi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.sl_slope->answer) || !(opt.sl_int->answer) || !(opt.sl_red->answer)) ) G_fatal_error(_("msavi index requires red and nir maps, and 3 parameters related to soil line")); if (!strcasecmp(viflag, "msavi2") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("msavi2 index requires red and nir maps")); if (!strcasecmp(viflag, "gemi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("gemi index requires red and nir maps")); if (!strcasecmp(viflag, "arvi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.blue->answer)) ) G_fatal_error(_("arvi index requires blue, red and nir maps")); if (!strcasecmp(viflag, "evi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.blue->answer)) ) G_fatal_error(_("evi index requires blue, red and nir maps")); if (!strcasecmp(viflag, "evi2") && (!(opt.red->answer) || !(opt.nir->answer) ) ) G_fatal_error(_("evi2 index requires red and nir maps")); if (!strcasecmp(viflag, "vari") && (!(opt.red->answer) || !(opt.green->answer) || !(opt.blue->answer)) ) G_fatal_error(_("vari index requires blue, green and red maps")); if (!strcasecmp(viflag, "gari") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.green->answer) || !(opt.blue->answer)) ) G_fatal_error(_("gari index requires blue, green, red and nir maps")); if (!strcasecmp(viflag, "gvi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.green->answer) || !(opt.blue->answer) || !(opt.chan5->answer) || !(opt.chan7->answer)) ) G_fatal_error(_("gvi index requires blue, green, red, nir, chan5 and chan7 maps")); infd_redchan = Rast_open_old(redchan, ""); data_type_redchan = Rast_map_type(redchan, ""); inrast_redchan = Rast_allocate_buf(data_type_redchan); if (nirchan) { infd_nirchan = Rast_open_old(nirchan, ""); data_type_nirchan = Rast_map_type(nirchan, ""); inrast_nirchan = Rast_allocate_buf(data_type_nirchan); } if (greenchan) { infd_greenchan = Rast_open_old(greenchan, ""); data_type_greenchan = Rast_map_type(greenchan, ""); inrast_greenchan = Rast_allocate_buf(data_type_greenchan); } if (bluechan) { infd_bluechan = Rast_open_old(bluechan, ""); data_type_bluechan = Rast_map_type(bluechan, ""); inrast_bluechan = Rast_allocate_buf(data_type_bluechan); } if (chan5chan) { infd_chan5chan = Rast_open_old(chan5chan, ""); data_type_chan5chan = Rast_map_type(chan5chan, ""); inrast_chan5chan = Rast_allocate_buf(data_type_chan5chan); } if (chan7chan) { infd_chan7chan = Rast_open_old(chan7chan, ""); data_type_chan7chan = Rast_map_type(chan7chan, ""); inrast_chan7chan = Rast_allocate_buf(data_type_chan7chan); } nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* Create New raster files */ outfd = Rast_open_new(result, DCELL_TYPE); outrast = Rast_allocate_d_buf(); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d_bluechan; DCELL d_greenchan; DCELL d_redchan; DCELL d_nirchan; DCELL d_chan5chan; DCELL d_chan7chan; G_percent(row, nrows, 2); /* read input maps */ Rast_get_row(infd_redchan,inrast_redchan,row,data_type_redchan); if (nirchan) { Rast_get_row(infd_nirchan,inrast_nirchan,row,data_type_nirchan); } if (bluechan) { Rast_get_row(infd_bluechan,inrast_bluechan,row,data_type_bluechan); } if (greenchan) { Rast_get_row(infd_greenchan,inrast_greenchan,row,data_type_greenchan); } if (chan5chan) { Rast_get_row(infd_chan5chan,inrast_chan5chan,row,data_type_chan5chan); } if (chan7chan) { Rast_get_row(infd_chan7chan,inrast_chan7chan,row,data_type_chan7chan); } /* process the data */ for (col = 0; col < ncols; col++) { switch(data_type_redchan){ case CELL_TYPE: d_redchan = (double) ((CELL *) inrast_redchan)[col]; if(opt.bits->answer) d_redchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_redchan = (double) ((FCELL *) inrast_redchan)[col]; break; case DCELL_TYPE: d_redchan = ((DCELL *) inrast_redchan)[col]; break; } if (nirchan) { switch(data_type_nirchan){ case CELL_TYPE: d_nirchan = (double) ((CELL *) inrast_nirchan)[col]; if(opt.bits->answer) d_nirchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_nirchan = (double) ((FCELL *) inrast_nirchan)[col]; break; case DCELL_TYPE: d_nirchan = ((DCELL *) inrast_nirchan)[col]; break; } } if (greenchan) { switch(data_type_greenchan){ case CELL_TYPE: d_greenchan = (double) ((CELL *) inrast_greenchan)[col]; if(opt.bits->answer) d_greenchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_greenchan = (double) ((FCELL *) inrast_greenchan)[col]; break; case DCELL_TYPE: d_greenchan = ((DCELL *) inrast_greenchan)[col]; break; } } if (bluechan) { switch(data_type_bluechan){ case CELL_TYPE: d_bluechan = (double) ((CELL *) inrast_bluechan)[col]; if(opt.bits->answer) d_bluechan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_bluechan = (double) ((FCELL *) inrast_bluechan)[col]; break; case DCELL_TYPE: d_bluechan = ((DCELL *) inrast_bluechan)[col]; break; } } if (chan5chan) { switch(data_type_chan5chan){ case CELL_TYPE: d_chan5chan = (double) ((CELL *) inrast_chan5chan)[col]; if(opt.bits->answer) d_chan5chan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_chan5chan = (double) ((FCELL *) inrast_chan5chan)[col]; break; case DCELL_TYPE: d_chan5chan = ((DCELL *) inrast_chan5chan)[col]; break; } } if (chan7chan) { switch(data_type_chan7chan){ case CELL_TYPE: d_chan7chan = (double) ((CELL *) inrast_chan7chan)[col]; if(opt.bits->answer) d_chan7chan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_chan7chan = (double) ((FCELL *) inrast_chan7chan)[col]; break; case DCELL_TYPE: d_chan7chan = ((DCELL *) inrast_chan7chan)[col]; break; } } if (Rast_is_d_null_value(&d_redchan) || ((nirchan) && Rast_is_d_null_value(&d_nirchan)) || ((greenchan) && Rast_is_d_null_value(&d_greenchan)) || ((bluechan) && Rast_is_d_null_value(&d_bluechan)) || ((chan5chan) && Rast_is_d_null_value(&d_chan5chan)) || ((chan7chan) && Rast_is_d_null_value(&d_chan7chan))) { Rast_set_d_null_value(&outrast[col], 1); } else { /* calculate simple_ratio */ if (!strcasecmp(viflag, "sr")) outrast[col] = s_r(d_redchan, d_nirchan); /* calculate ndvi */ if (!strcasecmp(viflag, "ndvi")) { if (d_redchan + d_nirchan < 0.001) Rast_set_d_null_value(&outrast[col], 1); else outrast[col] = nd_vi(d_redchan, d_nirchan); } if (!strcasecmp(viflag, "ipvi")) outrast[col] = ip_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "dvi")) outrast[col] = d_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "evi")) outrast[col] = e_vi(d_bluechan, d_redchan, d_nirchan); if (!strcasecmp(viflag, "evi2")) outrast[col] = e_vi2(d_redchan, d_nirchan); if (!strcasecmp(viflag, "pvi")) outrast[col] = p_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "wdvi")) outrast[col] = wd_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "savi")) outrast[col] = sa_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "msavi")) outrast[col] = msa_vi(d_redchan, d_nirchan, msavip1, msavip2, msavip3); if (!strcasecmp(viflag, "msavi2")) outrast[col] = msa_vi2(d_redchan, d_nirchan); if (!strcasecmp(viflag, "gemi")) outrast[col] = ge_mi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "arvi")) outrast[col] = ar_vi(d_redchan, d_nirchan, d_bluechan); if (!strcasecmp(viflag, "gvi")) outrast[col] = g_vi(d_bluechan, d_greenchan, d_redchan, d_nirchan, d_chan5chan, d_chan7chan); if (!strcasecmp(viflag, "gari")) outrast[col] = ga_ri(d_redchan, d_nirchan, d_bluechan, d_greenchan); if (!strcasecmp(viflag, "vari")) outrast[col] = va_ri(d_redchan, d_greenchan, d_bluechan); } } Rast_put_d_row(outfd, outrast); } G_percent(1, 1, 1); G_free(inrast_redchan); Rast_close(infd_redchan); if (nirchan) { G_free(inrast_nirchan); Rast_close(infd_nirchan); } if (greenchan) { G_free(inrast_greenchan); Rast_close(infd_greenchan); } if (bluechan) { G_free(inrast_bluechan); Rast_close(infd_bluechan); } if (chan5chan) { G_free(inrast_chan5chan); Rast_close(infd_chan5chan); } if (chan7chan) { G_free(inrast_chan7chan); Rast_close(infd_chan7chan); } G_free(outrast); Rast_close(outfd); if (!strcasecmp(viflag, "ndvi")) { /* apply predefined NDVI color table */ const char *style = "ndvi"; if (G_find_color_rule("ndvi")) { Rast_make_fp_colors(&colors, style, -1.0, 1.0); } else G_fatal_error(_("Unknown color request '%s'"), style); } else { /* Color from -1.0 to +1.0 in grey */ Rast_init_colors(&colors); val1 = -1; val2 = 1; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); } Rast_write_colors(result, G_mapset(), &colors); Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { struct GModule *module; struct Option *opt_out; struct Option *opt_lev; struct Flag *flg_d; struct Flag *flg_c; int dither; char *out_name; int out_file; CELL *out_array; struct Colors out_colors; int levels; int atrow, atcol; struct Cell_head window; unsigned char *dummy, *nulls; int i, j; struct History history; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("composite")); G_add_keyword("RGB"); module->description = _("Combines red, green and blue raster maps into " "a single composite raster map."); for (i = 0; i < 3; i++) { struct Option *opt; char buff[80]; B[i].opt_name = opt = G_define_standard_option(G_OPT_R_INPUT); sprintf(buff, "%s", color_names[i]); opt->key = G_store(buff); opt->answer = NULL; sprintf(buff, _("Name of raster map to be used for <%s>"), color_names[i]); opt->description = G_store(buff); } opt_lev = G_define_option(); opt_lev->key = "levels"; opt_lev->type = TYPE_INTEGER; opt_lev->required = NO; opt_lev->options = "1-256"; opt_lev->answer = "32"; opt_lev->description = _("Number of levels to be used for each component"); opt_lev->guisection = _("Levels"); for (i = 0; i < 3; i++) { struct Option *opt; char buff[80]; B[i].opt_levels = opt = G_define_option(); sprintf(buff, "lev_%s", color_names[i]); opt->key = G_store(buff); opt->type = TYPE_INTEGER; opt->required = NO; opt->options = "1-256"; sprintf(buff, _("Number of levels to be used for <%s>"), color_names[i]); opt->description = G_store(buff); opt->guisection = _("Levels"); } opt_out = G_define_standard_option(G_OPT_R_OUTPUT); flg_d = G_define_flag(); flg_d->key = 'd'; flg_d->description = _("Dither"); flg_c = G_define_flag(); flg_c->key = 'c'; flg_c->description = _("Use closest color"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); levels = atoi(opt_lev->answer); dither = flg_d->answer; closest = flg_c->answer; /* read in current window */ G_get_window(&window); dummy = G_malloc(window.cols); nulls = G_malloc(window.cols); for (i = 0; i < 3; i++) { struct band *b = &B[i]; /* Get name of layer to be used */ b->name = b->opt_name->answer; /* Make sure map is available */ b->file = Rast_open_old(b->name, ""); b->type = Rast_get_map_type(b->file); b->size = Rast_cell_size(b->type); /* Reading color lookup table */ if (Rast_read_colors(b->name, "", &b->colors) == -1) G_fatal_error(_("Unable to read color file of raster map <%s>"), b->name); for (j = 0; j < 3; j++) b->array[j] = (i == j) ? G_malloc(window.cols) : dummy; b->levels = b->opt_levels->answer ? atoi(b->opt_levels->answer) : levels; b->maxlev = b->levels - 1; b->offset = 128 / b->maxlev; if (dither) for (j = 0; j < 2; j++) b->floyd[j] = G_calloc(window.cols + 2, sizeof(short)); } /* open output files */ out_name = opt_out->answer; out_file = Rast_open_c_new(out_name); out_array = Rast_allocate_c_buf(); /* Make color table */ make_color_cube(&out_colors); G_message(_("Writing raster map <%s>..."), out_name); for (atrow = 0; atrow < window.rows; atrow++) { G_percent(atrow, window.rows, 2); for (i = 0; i < 3; i++) { struct band *b = &B[i]; Rast_get_row_colors(b->file, atrow, &b->colors, b->array[0], b->array[1], b->array[2], nulls); if (dither) { short *tmp = b->floyd[0]; b->floyd[0] = b->floyd[1]; for (atcol = 0; atcol < window.cols + 2; atcol++) tmp[atcol] = 0; b->floyd[1] = tmp; } } for (atcol = 0; atcol < window.cols; atcol++) { int val[3]; if (nulls[atcol]) { Rast_set_c_null_value(&out_array[atcol], 1); continue; } for (i = 0; i < 3; i++) { struct band *b = &B[i]; int v = b->array[i][atcol]; if (dither) { int r, w, d; v += b->floyd[0][atcol + 1] / 16; v = (v < 0) ? 0 : (v > 255) ? 255 : v; r = quantize(i, v); w = r * 255 / b->maxlev; d = v - w; b->floyd[0][atcol + 2] += 7 * d; b->floyd[1][atcol + 0] += 3 * d; b->floyd[1][atcol + 1] += 5 * d; b->floyd[1][atcol + 2] += 1 * d; val[i] = r; } else val[i] = quantize(i, v); } out_array[atcol] = (CELL) (val[2] * B[1].levels + val[1]) * B[0].levels + val[0]; } Rast_put_row(out_file, out_array, CELL_TYPE); } G_percent(window.rows, window.rows, 1); /* Close the input files */ for (i = 0; i < 3; i++) Rast_close(B[i].file); /* Close the output file */ Rast_close(out_file); Rast_write_colors(out_name, G_mapset(), &out_colors); Rast_short_history(out_name, "raster", &history); Rast_command_history(&history); Rast_write_history(out_name, &history); G_done_msg(_("Raster map <%s> created."), out_name); exit(EXIT_SUCCESS); }
int exec_rectify(char *extension, char *interp_method, char *angle_map) { char *name; char *mapset; char *result; char *type = "raster"; int n; struct Colors colr; struct Categories cats; struct History hist; int colr_ok, cats_ok; long start_time, rectify_time; double aver_z; int elevfd; struct cache *ebuffer; G_debug(1, "Open elevation raster: "); /* open elevation raster */ select_target_env(); G_set_window(&target_window); G_debug(1, "target window: rs=%d cs=%d n=%f s=%f w=%f e=%f\n", target_window.rows, target_window.cols, target_window.north, target_window.south, target_window.west, target_window.east); elevfd = Rast_open_old(elev_name, elev_mapset); if (elevfd < 0) { G_fatal_error(_("Could not open elevation raster")); return 1; } ebuffer = readcell(elevfd, seg_mb_elev, 1); select_target_env(); Rast_close(elevfd); /* get an average elevation of the control points */ /* this is used only if target cells have no elevation */ get_aver_elev(&group.control_points, &aver_z); G_message("-----------------------------------------------"); /* rectify each file */ for (n = 0; n < group.group_ref.nfiles; n++) { if (!ref_list[n]) continue; name = group.group_ref.file[n].name; mapset = group.group_ref.file[n].mapset; result = G_malloc(strlen(group.group_ref.file[n].name) + strlen(extension) + 1); strcpy(result, group.group_ref.file[n].name); strcat(result, extension); G_debug(2, "ORTHO RECTIFYING:"); G_debug(2, "NAME %s", name); G_debug(2, "MAPSET %s", mapset); G_debug(2, "RESULT %s", result); G_debug(2, "select_current_env..."); select_current_env(); cats_ok = Rast_read_cats(name, mapset, &cats) >= 0; colr_ok = Rast_read_colors(name, mapset, &colr) > 0; /* Initialze History */ if (Rast_read_history(name, mapset, &hist) < 0) Rast_short_history(result, type, &hist); G_debug(2, "reading was fine..."); time(&start_time); G_debug(2, "Starting the rectification..."); if (rectify(name, mapset, ebuffer, aver_z, result, interp_method)) { G_debug(2, "Done. Writing results..."); select_target_env(); if (cats_ok) { Rast_write_cats(result, &cats); Rast_free_cats(&cats); } if (colr_ok) { Rast_write_colors(result, G_mapset(), &colr); Rast_free_colors(&colr); } /* Write out History */ Rast_command_history(&hist); Rast_write_history(result, &hist); select_current_env(); time(&rectify_time); report(rectify_time - start_time, 1); } else report((long)0, 0); G_free(result); } close(ebuffer->fd); release_cache(ebuffer); if (angle_map) { camera_angle(angle_map); } return 0; }
void set_map(char *name, char *name1, char *name2, struct Cell_head window, int top, int bot, int left, int right) { char cmd[30], cmd1[30], cmd2[30], **sel; int i, j, btn, d, class, top0, bot0, right0, left0, paint = 0, method; double msc[2], dtmp; /* VARIABLES IN: name = raster map name to be set up name1 = overlay vector map name name2 = overlay site map name */ colors_old = (struct Colors *)G_malloc(1 * sizeof(struct Colors)); Rast_init_colors(colors_old); Rast_read_colors(name, G_mapset(), colors_old); G_system("clear"); paint_map(name, name1, name2); paint = 1; /* setup the screen to raster map coordinate conversion system */ scr_cell(&window, top, bot, left, right, msc); top0 = top; bot0 = bot; left0 = left; right0 = right; /* display the menu and instructions */ again: if (!paint) { if (G_yes ("\n Refresh the screen before choosing more setup? ", 1)) paint_map(name, name1, name2); } else G_system("clear"); fprintf(stderr, "\n\n CHOOSE THE SETUP OPTION:\n\n"); fprintf(stderr, " Draw sampling regions 1\n"); fprintf(stderr, " Setup a sampling frame 2\n"); fprintf(stderr, " Setup sampling units 3\n"); fprintf(stderr, " Setup a moving window 4\n"); fprintf(stderr, " Setup group or class limits 5\n"); fprintf(stderr, " Change the raster map color table 6\n"); fprintf(stderr, " Exit and save setup 7\n"); do { fprintf(stderr, "\n Which Number? "); dtmp = 5.0; numtrap(1, &dtmp); if ((method = fabs(dtmp)) > 7 || method < 1) { fprintf(stderr, "\n Choice must between 1-7; try again"); } } while (method > 7 || method < 1); /* setup regions */ if (method == 1) set_rgn(msc, name, name1, name2); /* setup the sampling frame */ else if (method == 2) { top = top0; bot = bot0; right = right0; left = left0; set_frame(msc, &top, &bot, &left, &right); } /* setup sampling units */ else if (method == 3) { sample(top, bot, left, right, name, name1, name2, msc); } /* setup the moving window */ else if (method == 4) { mov_wind(top, bot, left, right, name, name1, name2, msc); } /* setup group/class limits */ else if (method == 5) { /* setup the buffer to store the user's input */ sel = (char **)G_malloc(10 * sizeof(char *)); for (i = 0; i < 9; i++) sel[i] = (char *)G_calloc(2, sizeof(char)); back: ask_group(sel); /* check for no input */ if (sel[0][0] != 'x' && sel[1][0] != 'x' && sel[2][0] != 'x' && sel[3][0] != 'x' && sel[4][0] != 'x' && sel[5][0] != 'x' && sel[6][0] != 'x' && sel[7][0] != 'x' && sel[8][0] != 'x') { G_system("clear"); fprintf(stderr, " Did you mean to not make any attribute group"); if (!G_yes("\n or index class setup choices? ", 1)) goto back; } /* if there is input, then invoke the group/class setup module and then free the memory allocated for selections */ else { get_group_drv(sel); for (i = 0; i < 9; i++) G_free(sel[i]); G_free(sel); } } /* change color tables */ else if (method == 6) change_color(name, name1, name2); /* reset the colortable and exit */ else if (method == 7) { Rast_write_colors(name, G_mapset(), colors_old); Rast_free_colors(colors_old); /* R_close_driver(); */ G_system("d.frame -e"); exit(0); } paint = 0; goto again; return; }
int close_array_seg(void) { struct Colors colors; int incr, max, red, green, blue, rd, gr, bl, flag; int c, r, map_fd; CELL *cellrow, value; CELL *theseg; RAMSEG thesegseg; cellrow = Rast_allocate_c_buf(); if (seg_flag || bas_flag || haf_flag) { if (seg_flag) { theseg = bas; thesegseg = bas_seg; } else if (bas_flag) { theseg = bas; thesegseg = bas_seg; } else { theseg = haf; thesegseg = haf_seg; } max = n_basins; G_debug(1, "%d basins created", max); Rast_init_colors(&colors); if (max > 0) Rast_make_random_colors(&colors, 1, max); else { G_warning(_("No basins were created. Verify threshold and region settings.")); Rast_make_random_colors(&colors, 1, 2); } if (max < 1000 && max > 0) { Rast_set_c_color((CELL) 0, 0, 0, 0, &colors); r = 1; incr = 0; while (incr >= 0) { G_percent(r, max, 2); for (gr = 130 + incr; gr <= 255; gr += 20) { for (rd = 90 + incr; rd <= 255; rd += 30) { for (bl = 90 + incr; bl <= 255; bl += 40) { flag = 1; while (flag) { Rast_get_c_color(&r, &red, &green, &blue, &colors); /* if existing rule is too dark then append a new rule to override it */ if ((blue * .11 + red * .30 + green * .59) < 100) { Rast_set_c_color(r, rd, gr, bl, &colors); flag = 0; } if (++r > max) { gr = rd = bl = 300; flag = 0; incr = -1; } } } } } if (incr >= 0) { incr += 15; if (incr > 120) incr = 7; } } G_percent(r - 1, max, 3); /* finish it */ } else G_debug(1, "Too many subbasins to reasonably check for color brightness"); /* using the existing stack of while/for/for/for/while loops ... */ } /* stream segments map */ if (seg_flag) { map_fd = Rast_open_c_new(seg_name); for (r = 0; r < nrows; r++) { Rast_set_c_null_value(cellrow, ncols); /* reset row to all NULL */ for (c = 0; c < ncols; c++) { value = FLAG_GET(swale, r, c); if (value) cellrow[c] = bas[SEG_INDEX(bas_seg, r, c)]; } Rast_put_row(map_fd, cellrow, CELL_TYPE); } Rast_close(map_fd); Rast_write_colors(seg_name, this_mapset, &colors); } /* basins map */ if (bas_flag) { map_fd = Rast_open_c_new(bas_name); for (r = 0; r < nrows; r++) { for (c = 0; c < ncols; c++) { cellrow[c] = bas[SEG_INDEX(bas_seg, r, c)]; if (cellrow[c] == 0) Rast_set_c_null_value(cellrow + c, 1); } Rast_put_row(map_fd, cellrow, CELL_TYPE); } Rast_close(map_fd); Rast_write_colors(bas_name, this_mapset, &colors); } /* half_basins map */ if (haf_flag) { map_fd = Rast_open_c_new(haf_name); for (r = 0; r < nrows; r++) { for (c = 0; c < ncols; c++) { cellrow[c] = haf[SEG_INDEX(haf_seg, r, c)]; if (cellrow[c] == 0) Rast_set_c_null_value(cellrow + c, 1); } Rast_put_row(map_fd, cellrow, CELL_TYPE); } Rast_close(map_fd); Rast_write_colors(haf_name, this_mapset, &colors); } if (seg_flag || bas_flag || haf_flag) Rast_free_colors(&colors); G_free(haf); G_free(bas); G_free(cellrow); if (arm_flag) fclose(fp); close_maps(); return 0; }
int make_support(struct rr_state *theState, int percent, double percentage) { char title[100]; struct History hist; struct Categories cats; struct Colors clr; char *inraster; struct RASTER_MAP_PTR nulls; /* write categories for output raster use values from input or cover map */ if (theState->docover == 1) { inraster = theState->inrcover; nulls = theState->cnulls; } else { inraster = theState->inraster; nulls = theState->nulls; } if (Rast_read_cats(inraster, "", &cats) >= 0) { sprintf(title, "Random points on <%s>", inraster); Rast_set_cats_title(title, &cats); if (theState->use_nulls) Rast_set_cat(nulls.data.v, nulls.data.v, "Points with NULL values in original", &cats, nulls.type); Rast_write_cats(theState->outraster, &cats); } /* write history for output raster */ if (Rast_read_history(theState->outraster, G_mapset(), &hist) >= 0) { Rast_short_history(theState->outraster, "raster", &hist); Rast_format_history(&hist, HIST_DATSRC_1, "Based on map <%s>", inraster); if (percent) Rast_format_history( &hist, HIST_DATSRC_2, "Random points over %.2f percent of the base map <%s>", percentage, inraster); else Rast_format_history( &hist, HIST_DATSRC_2, "%ld random points on the base map <%s>", theState->nRand, theState->inraster); Rast_command_history(&hist); Rast_write_history(theState->outraster, &hist); } /* write commandline to output vector */ if (theState->outvector) { struct Map_info map; Vect_open_old(&map, theState->outvector, G_mapset()); Vect_hist_command(&map); Vect_close(&map); } /* set colors for output raster */ if (Rast_read_colors(inraster, "", &clr) >= 0) { if (theState->use_nulls) { Rast_add_color_rule(nulls.data.v, 127, 127, 127, nulls.data.v, 127, 127, 127, &clr, nulls.type); } Rast_write_colors(theState->outraster, G_mapset(), &clr); } return 0; }
int camera_angle(char *name) { int row, col, nrows, ncols; double XC = group.XC; double YC = group.YC; double ZC = group.ZC; double c_angle, c_angle_min, c_alt, c_az, slope, aspect; double radians_to_degrees = 180.0 / M_PI; /* double degrees_to_radians = M_PI / 180.0; */ DCELL e1, e2, e3, e4, e5, e6, e7, e8, e9; double factor, V, H, dx, dy, dz, key; double north, south, east, west, ns_med; FCELL *fbuf0, *fbuf1, *fbuf2, *tmpbuf, *outbuf; int elevfd, outfd; struct Cell_head cellhd; struct Colors colr; FCELL clr_min, clr_max; struct History hist; char *type; G_message(_("Calculating camera angle to local surface...")); select_target_env(); /* align target window to elevation map, otherwise we get artefacts * like in r.slope.aspect -a */ Rast_get_cellhd(elev_name, elev_mapset, &cellhd); Rast_align_window(&target_window, &cellhd); Rast_set_window(&target_window); elevfd = Rast_open_old(elev_name, elev_mapset); if (elevfd < 0) { G_fatal_error(_("Could not open elevation raster")); return 1; } nrows = target_window.rows; ncols = target_window.cols; outfd = Rast_open_new(name, FCELL_TYPE); fbuf0 = Rast_allocate_buf(FCELL_TYPE); fbuf1 = Rast_allocate_buf(FCELL_TYPE); fbuf2 = Rast_allocate_buf(FCELL_TYPE); outbuf = Rast_allocate_buf(FCELL_TYPE); /* give warning if location units are different from meters and zfactor=1 */ factor = G_database_units_to_meters_factor(); if (factor != 1.0) G_warning(_("Converting units to meters, factor=%.6f"), factor); G_begin_distance_calculations(); north = Rast_row_to_northing(0.5, &target_window); ns_med = Rast_row_to_northing(1.5, &target_window); south = Rast_row_to_northing(2.5, &target_window); east = Rast_col_to_easting(2.5, &target_window); west = Rast_col_to_easting(0.5, &target_window); V = G_distance(east, north, east, south) * 4; H = G_distance(east, ns_med, west, ns_med) * 4; c_angle_min = 90; Rast_get_row(elevfd, fbuf1, 0, FCELL_TYPE); Rast_get_row(elevfd, fbuf2, 1, FCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_set_null_value(outbuf, ncols, FCELL_TYPE); /* first and last row */ if (row == 0 || row == nrows - 1) { Rast_put_row(outfd, outbuf, FCELL_TYPE); continue; } tmpbuf = fbuf0; fbuf0 = fbuf1; fbuf1 = fbuf2; fbuf2 = tmpbuf; Rast_get_row(elevfd, fbuf2, row + 1, FCELL_TYPE); north = Rast_row_to_northing(row + 0.5, &target_window); for (col = 1; col < ncols - 1; col++) { e1 = fbuf0[col - 1]; if (Rast_is_d_null_value(&e1)) continue; e2 = fbuf0[col]; if (Rast_is_d_null_value(&e2)) continue; e3 = fbuf0[col + 1]; if (Rast_is_d_null_value(&e3)) continue; e4 = fbuf1[col - 1]; if (Rast_is_d_null_value(&e4)) continue; e5 = fbuf1[col]; if (Rast_is_d_null_value(&e5)) continue; e6 = fbuf1[col + 1]; if (Rast_is_d_null_value(&e6)) continue; e7 = fbuf2[col - 1]; if (Rast_is_d_null_value(&e7)) continue; e8 = fbuf2[col]; if (Rast_is_d_null_value(&e8)) continue; e9 = fbuf2[col + 1]; if (Rast_is_d_null_value(&e9)) continue; dx = ((e1 + e4 + e4 + e7) - (e3 + e6 + e6 + e9)) / H; dy = ((e7 + e8 + e8 + e9) - (e1 + e2 + e2 + e3)) / V; /* compute topographic parameters */ key = dx * dx + dy * dy; /* slope in radians */ slope = atan(sqrt(key)); /* aspect in radians */ if (key == 0.) aspect = 0.; else if (dx == 0) { if (dy > 0) aspect = M_PI / 2; else aspect = 1.5 * M_PI; } else { aspect = atan2(dy, dx); if (aspect <= 0.) aspect = 2 * M_PI + aspect; } /* camera altitude angle in radians */ east = Rast_col_to_easting(col + 0.5, &target_window); dx = east - XC; dy = north - YC; dz = ZC - e5; c_alt = atan(sqrt(dx * dx + dy * dy) / dz); /* camera azimuth angle in radians */ c_az = atan(dy / dx); if (east < XC && north != YC) c_az += M_PI; else if (north < YC && east > XC) c_az += 2 * M_PI; /* camera angle to real ground */ /* orthogonal to ground: 90 degrees */ /* parallel to ground: 0 degrees */ c_angle = asin(cos(c_alt) * cos(slope) - sin(c_alt) * sin(slope) * cos(c_az - aspect)); outbuf[col] = c_angle * radians_to_degrees; if (c_angle_min > outbuf[col]) c_angle_min = outbuf[col]; } Rast_put_row(outfd, outbuf, FCELL_TYPE); } G_percent(row, nrows, 2); Rast_close(elevfd); Rast_close(outfd); G_free(fbuf0); G_free(fbuf1); G_free(fbuf2); G_free(outbuf); type = "raster"; Rast_short_history(name, type, &hist); Rast_command_history(&hist); Rast_write_history(name, &hist); Rast_init_colors(&colr); if (c_angle_min < 0) { clr_min = (FCELL)((int)(c_angle_min / 10 - 1)) * 10; clr_max = 0; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 0, 0, 0, &colr); } clr_min = 0; clr_max = 10; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 255, 0, 0, &colr); clr_min = 10; clr_max = 40; Rast_add_f_color_rule(&clr_min, 255, 0, 0, &clr_max, 255, 255, 0, &colr); clr_min = 40; clr_max = 90; Rast_add_f_color_rule(&clr_min, 255, 255, 0, &clr_max, 0, 255, 0, &colr); Rast_write_colors(name, G_mapset(), &colr); select_current_env(); return 1; }
int main(int argc, char *argv[]) { char *terrainmap, *seedmap, *lakemap; int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass; int lastcount, curcount, start_col = 0, start_row = 0; double east, north, area = 0, volume = 0; FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0; FCELL water_window[3][3]; struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt; struct Flag *negative_flag, *overwrite_flag; struct GModule *module; struct Colors colr; struct Cell_head window; struct History history; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("hydrology")); G_add_keyword(_("hazard")); G_add_keyword(_("flood")); module->description = _("Fills lake at given point to given level."); tmap_opt = G_define_standard_option(G_OPT_R_ELEV); wlvl_opt = G_define_option(); wlvl_opt->key = "water_level"; wlvl_opt->description = _("Water level"); wlvl_opt->type = TYPE_DOUBLE; wlvl_opt->required = YES; lake_opt = G_define_standard_option(G_OPT_R_OUTPUT); lake_opt->key = "lake"; lake_opt->required = NO; lake_opt->guisection = _("Output"); sdxy_opt = G_define_standard_option(G_OPT_M_COORDS); sdxy_opt->label = _("Seed point coordinates"); sdxy_opt->description = _("Either this coordinates pair or a seed" " map have to be specified"); sdxy_opt->required = NO; sdxy_opt->multiple = NO; sdxy_opt->guisection = _("Seed"); smap_opt = G_define_standard_option(G_OPT_R_MAP); smap_opt->key = "seed"; smap_opt->label = _("Input raster map with given starting point(s) (at least 1 cell > 0)"); smap_opt->description = _("Either this parameter or a coordinates pair have to be specified"); smap_opt->required = NO; smap_opt->guisection = _("Seed"); negative_flag = G_define_flag(); negative_flag->key = 'n'; negative_flag->description = _("Use negative depth values for lake raster map"); overwrite_flag = G_define_flag(); overwrite_flag->key = 'o'; overwrite_flag->description = _("Overwrite seed map with result (lake) map"); overwrite_flag->guisection = _("Output"); if (G_parser(argc, argv)) /* Returns 0 if successful, non-zero otherwise */ exit(EXIT_FAILURE); if (smap_opt->answer && sdxy_opt->answer) G_fatal_error(_("Both seed map and coordinates cannot be specified")); if (!smap_opt->answer && !sdxy_opt->answer) G_fatal_error(_("Seed map or seed coordinates must be set!")); if (sdxy_opt->answer && !lake_opt->answer) G_fatal_error(_("Seed coordinates and output map lake= must be set!")); if (lake_opt->answer && overwrite_flag->answer) G_fatal_error(_("Both lake and overwrite cannot be specified")); if (!lake_opt->answer && !overwrite_flag->answer) G_fatal_error(_("Output lake map or overwrite flag must be set!")); terrainmap = tmap_opt->answer; seedmap = smap_opt->answer; sscanf(wlvl_opt->answer, "%f", &water_level); lakemap = lake_opt->answer; /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */ if (lakemap) lake_fd = Rast_open_new(lakemap, 1); rows = Rast_window_rows(); cols = Rast_window_cols(); /* If we use x,y as seed... */ if (sdxy_opt->answer) { G_get_window(&window); east = window.east; north = window.north; G_scan_easting(sdxy_opt->answers[0], &east, G_projection()); G_scan_northing(sdxy_opt->answers[1], &north, G_projection()); start_col = (int)Rast_easting_to_col(east, &window); start_row = (int)Rast_northing_to_row(north, &window); if (start_row < 0 || start_row > rows || start_col < 0 || start_col > cols) G_fatal_error(_("Seed point outside the current region")); } /* Open terrain map */ in_terran_fd = Rast_open_old(terrainmap, ""); /* Open seed map */ if (smap_opt->answer) out_fd = Rast_open_old(seedmap, ""); /* Pointers to rows. Row = ptr to 'col' size array. */ in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *)); out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *)); if (in_terran == NULL || out_water == NULL) G_fatal_error(_("G_malloc: out of memory")); G_debug(1, "Loading maps..."); /* foo_rows[row] == array with data (2d array). */ for (row = 0; row < rows; row++) { in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL)); out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL)); /* In newly created space load data from file. */ Rast_get_f_row(in_terran_fd, in_terran[row], row); if (smap_opt->answer) Rast_get_f_row(out_fd, out_water[row], row); G_percent(row + 1, rows, 5); } /* Set seed point */ if (sdxy_opt->answer) /* Check is water level higher than seed point */ if (in_terran[start_row][start_col] >= water_level) G_fatal_error(_("Given water level at seed point is below earth surface. " "Increase water level or move seed point.")); out_water[start_row][start_col] = 1; /* Close seed map for reading. */ if (smap_opt->answer) Rast_close(out_fd); /* Open output map for writing. */ if (lakemap) out_fd = lake_fd; else out_fd = Rast_open_new(seedmap, 1); /* More pases are renudant. Real pases count is controlled by altered cell count. */ pases = (int)(rows * cols) / 2; G_debug(1, "Starting lake filling at level of %8.4f in %d passes. Percent done:", water_level, pases); lastcount = 0; for (pass = 0; pass < pases; pass++) { G_debug(3, "Pass: %d", pass); curcount = 0; /* Move from left upper corner to right lower corner. */ for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { /* Loading water data into window. */ load_window_values(out_water, water_window, rows, cols, row, col); /* Cheking presence of water. */ if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; /* Cell is higher than water level -> NULL. */ } } } } if (curcount == lastcount) break; /* We done. */ lastcount = curcount; curcount = 0; /* Move backwards - from lower right corner to upper left corner. */ for (row = rows - 1; row >= 0; row--) { for (col = cols - 1; col >= 0; col--) { load_window_values(out_water, water_window, rows, cols, row, col); if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; } } } } G_percent(pass + 1, pases, 10); if (curcount == lastcount) break; /* We done. */ lastcount = curcount; } /*pases */ G_percent(pases, pases, 10); /* Show 100%. */ save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth, &max_depth, &area, &volume); G_message(_("Lake depth from %f to %f (specified water level is taken as zero)"), min_depth, max_depth); G_message(_("Lake area %f square meters"), area); G_message(_("Lake volume %f cubic meters"), volume); G_important_message(_("Volume is correct only if lake depth (terrain raster map) is in meters")); /* Close all files. Lake map gets written only now. */ Rast_close(in_terran_fd); Rast_close(out_fd); /* Add blue color gradient from light bank to dark depth */ Rast_init_colors(&colr); if (negative_flag->answer == 1) { Rast_add_f_color_rule(&max_depth, 0, 240, 255, &min_depth, 0, 50, 170, &colr); } else { Rast_add_f_color_rule(&min_depth, 0, 240, 255, &max_depth, 0, 50, 170, &colr); } Rast_write_colors(lakemap, G_mapset(), &colr); Rast_short_history(lakemap, "raster", &history); Rast_command_history(&history); Rast_write_history(lakemap, &history); return EXIT_SUCCESS; }
int main(int argc, char **argv) { char *mapname, /* ptr to name of output layer */ *setname, /* ptr to name of input mapset */ *ipolname; /* name of interpolation method */ int fdi, /* input map file descriptor */ fdo, /* output map file descriptor */ method, /* position of method in table */ permissions, /* mapset permissions */ cell_type, /* output celltype */ cell_size, /* size of a cell in bytes */ row, col, /* counters */ irows, icols, /* original rows, cols */ orows, ocols, have_colors, /* Input map has a colour table */ overwrite, /* Overwrite */ curr_proj; /* output projection (see gis.h) */ void *obuffer, /* buffer that holds one output row */ *obufptr; /* column ptr in output buffer */ struct cache *ibuffer; /* buffer that holds the input map */ func interpolate; /* interpolation routine */ double xcoord1, xcoord2, /* temporary x coordinates */ ycoord1, ycoord2, /* temporary y coordinates */ col_idx, /* column index in input matrix */ row_idx, /* row index in input matrix */ onorth, osouth, /* save original border coords */ oeast, owest, inorth, isouth, ieast, iwest; char north_str[30], south_str[30], east_str[30], west_str[30]; struct Colors colr; /* Input map colour table */ struct History history; struct pj_info iproj, /* input map proj parameters */ oproj; /* output map proj parameters */ struct Key_Value *in_proj_info, /* projection information of */ *in_unit_info, /* input and output mapsets */ *out_proj_info, *out_unit_info; struct GModule *module; struct Flag *list, /* list files in source location */ *nocrop, /* don't crop output map */ *print_bounds, /* print output bounds and exit */ *gprint_bounds; /* same but print shell style */ struct Option *imapset, /* name of input mapset */ *inmap, /* name of input layer */ *inlocation, /* name of input location */ *outmap, /* name of output layer */ *indbase, /* name of input database */ *interpol, /* interpolation method: nearest neighbor, bilinear, cubic */ *memory, /* amount of memory for cache */ *res; /* resolution of target map */ struct Cell_head incellhd, /* cell header of input map */ outcellhd; /* and output map */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("projection")); G_add_keyword(_("transformation")); module->description = _("Re-projects a raster map from given location to the current location."); inmap = G_define_standard_option(G_OPT_R_INPUT); inmap->description = _("Name of input raster map to re-project"); inmap->required = NO; inmap->guisection = _("Source"); inlocation = G_define_option(); inlocation->key = "location"; inlocation->type = TYPE_STRING; inlocation->required = YES; inlocation->description = _("Location containing input raster map"); inlocation->gisprompt = "old,location,location"; inlocation->key_desc = "name"; imapset = G_define_standard_option(G_OPT_M_MAPSET); imapset->label = _("Mapset containing input raster map"); imapset->description = _("default: name of current mapset"); imapset->guisection = _("Source"); indbase = G_define_option(); indbase->key = "dbase"; indbase->type = TYPE_STRING; indbase->required = NO; indbase->description = _("Path to GRASS database of input location"); indbase->gisprompt = "old,dbase,dbase"; indbase->key_desc = "path"; indbase->guisection = _("Source"); outmap = G_define_standard_option(G_OPT_R_OUTPUT); outmap->required = NO; outmap->description = _("Name for output raster map (default: same as 'input')"); outmap->guisection = _("Target"); ipolname = make_ipol_list(); interpol = G_define_option(); interpol->key = "method"; interpol->type = TYPE_STRING; interpol->required = NO; interpol->answer = "nearest"; interpol->options = ipolname; interpol->description = _("Interpolation method to use"); interpol->guisection = _("Target"); interpol->descriptions = make_ipol_desc(); memory = G_define_option(); memory->key = "memory"; memory->type = TYPE_INTEGER; memory->required = NO; memory->description = _("Cache size (MiB)"); res = G_define_option(); res->key = "resolution"; res->type = TYPE_DOUBLE; res->required = NO; res->description = _("Resolution of output raster map"); res->guisection = _("Target"); list = G_define_flag(); list->key = 'l'; list->description = _("List raster maps in input location and exit"); nocrop = G_define_flag(); nocrop->key = 'n'; nocrop->description = _("Do not perform region cropping optimization"); print_bounds = G_define_flag(); print_bounds->key = 'p'; print_bounds->description = _("Print input map's bounds in the current projection and exit"); print_bounds->guisection = _("Target"); gprint_bounds = G_define_flag(); gprint_bounds->key = 'g'; gprint_bounds->description = _("Print input map's bounds in the current projection and exit (shell style)"); gprint_bounds->guisection = _("Target"); /* The parser checks if the map already exists in current mapset, we switch out the check and do it in the module after the parser */ overwrite = G_check_overwrite(argc, argv); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get the method */ for (method = 0; (ipolname = menu[method].name); method++) if (strcmp(ipolname, interpol->answer) == 0) break; if (!ipolname) G_fatal_error(_("<%s=%s> unknown %s"), interpol->key, interpol->answer, interpol->key); interpolate = menu[method].method; mapname = outmap->answer ? outmap->answer : inmap->answer; if (mapname && !list->answer && !overwrite && G_find_raster(mapname, G_mapset())) G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname); setname = imapset->answer ? imapset->answer : G_store(G_mapset()); if (strcmp(inlocation->answer, G_location()) == 0 && (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0)) #if 0 G_fatal_error(_("Input and output locations can not be the same")); #else G_warning(_("Input and output locations are the same")); #endif G_get_window(&outcellhd); if(gprint_bounds->answer && !print_bounds->answer) print_bounds->answer = gprint_bounds->answer; curr_proj = G_projection(); /* Get projection info for output mapset */ if ((out_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of output raster map")); if ((out_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of output raster map")); if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of output raster map")); /* Change the location */ G__create_alt_env(); G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase()); G__setenv("LOCATION_NAME", inlocation->answer); permissions = G__mapset_permissions(setname); if (permissions < 0) /* can't access mapset */ G_fatal_error(_("Mapset <%s> in input location <%s> - %s"), setname, inlocation->answer, permissions == 0 ? _("permission denied") : _("not found")); /* if requested, list the raster maps in source location - MN 5/2001 */ if (list->answer) { int i; char **list; G_verbose_message(_("Checking location <%s> mapset <%s>"), inlocation->answer, setname); list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"), G__getenv("LOCATION_NAME"), setname); for (i = 0; list[i]; i++) { fprintf(stdout, "%s\n", list[i]); } fflush(stdout); exit(EXIT_SUCCESS); /* leave r.proj after listing */ } if (!inmap->answer) G_fatal_error(_("Required parameter <%s> not set"), inmap->key); if (!G_find_raster(inmap->answer, setname)) G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"), inmap->answer, inlocation->answer, setname); /* Read input map colour table */ have_colors = Rast_read_colors(inmap->answer, setname, &colr); /* Get projection info for input mapset */ if ((in_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of input map")); if ((in_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of input map")); if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of input map")); G_free_key_value(in_proj_info); G_free_key_value(in_unit_info); G_free_key_value(out_proj_info); G_free_key_value(out_unit_info); if (G_verbose() > G_verbose_std()) pj_print_proj_params(&iproj, &oproj); /* this call causes r.proj to read the entire map into memeory */ Rast_get_cellhd(inmap->answer, setname, &incellhd); Rast_set_input_window(&incellhd); if (G_projection() == PROJECTION_XY) G_fatal_error(_("Unable to work with unprojected data (xy location)")); /* Save default borders so we can show them later */ inorth = incellhd.north; isouth = incellhd.south; ieast = incellhd.east; iwest = incellhd.west; irows = incellhd.rows; icols = incellhd.cols; onorth = outcellhd.north; osouth = outcellhd.south; oeast = outcellhd.east; owest = outcellhd.west; orows = outcellhd.rows; ocols = outcellhd.cols; if (print_bounds->answer) { G_message(_("Input map <%s@%s> in location <%s>:"), inmap->answer, setname, inlocation->answer); if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); G_format_northing(inorth, north_str, curr_proj); G_format_northing(isouth, south_str, curr_proj); G_format_easting(ieast, east_str, curr_proj); G_format_easting(iwest, west_str, curr_proj); if(gprint_bounds->answer) { fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n", north_str, south_str, west_str, east_str, irows, icols); } else { fprintf(stdout, "Source cols: %d\n", icols); fprintf(stdout, "Source rows: %d\n", irows); fprintf(stdout, "Local north: %s\n", north_str); fprintf(stdout, "Local south: %s\n", south_str); fprintf(stdout, "Local west: %s\n", west_str); fprintf(stdout, "Local east: %s\n", east_str); } /* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */ exit(EXIT_SUCCESS); } /* Cut non-overlapping parts of input map */ if (!nocrop->answer) bordwalk(&outcellhd, &incellhd, &oproj, &iproj); /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */ /* (should probably be a factor based on input and output resolution) */ incellhd.north += 2 * incellhd.ns_res; incellhd.east += 2 * incellhd.ew_res; incellhd.south -= 2 * incellhd.ns_res; incellhd.west -= 2 * incellhd.ew_res; if (incellhd.north > inorth) incellhd.north = inorth; if (incellhd.east > ieast) incellhd.east = ieast; if (incellhd.south < isouth) incellhd.south = isouth; if (incellhd.west < iwest) incellhd.west = iwest; Rast_set_input_window(&incellhd); /* And switch back to original location */ G__switch_env(); /* Adjust borders of output map */ if (!nocrop->answer) bordwalk(&incellhd, &outcellhd, &iproj, &oproj); #if 0 outcellhd.west = outcellhd.south = HUGE_VAL; outcellhd.east = outcellhd.north = -HUGE_VAL; for (row = 0; row < incellhd.rows; row++) { ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd); for (col = 0; col < incellhd.cols; col++) { xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd); pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj); if (xcoord1 > outcellhd.east) outcellhd.east = xcoord1; if (ycoord1 > outcellhd.north) outcellhd.north = ycoord1; if (xcoord1 < outcellhd.west) outcellhd.west = xcoord1; if (ycoord1 < outcellhd.south) outcellhd.south = ycoord1; } } #endif if (res->answer != NULL) /* set user defined resolution */ outcellhd.ns_res = outcellhd.ew_res = atof(res->answer); G_adjust_Cell_head(&outcellhd, 0, 0); Rast_set_output_window(&outcellhd); G_message(" "); G_message(_("Input:")); G_message(_("Cols: %d (%d)"), incellhd.cols, icols); G_message(_("Rows: %d (%d)"), incellhd.rows, irows); G_message(_("North: %f (%f)"), incellhd.north, inorth); G_message(_("South: %f (%f)"), incellhd.south, isouth); G_message(_("West: %f (%f)"), incellhd.west, iwest); G_message(_("East: %f (%f)"), incellhd.east, ieast); G_message(_("EW-res: %f"), incellhd.ew_res); G_message(_("NS-res: %f"), incellhd.ns_res); G_message(" "); G_message(_("Output:")); G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols); G_message(_("Rows: %d (%d)"), outcellhd.rows, orows); G_message(_("North: %f (%f)"), outcellhd.north, onorth); G_message(_("South: %f (%f)"), outcellhd.south, osouth); G_message(_("West: %f (%f)"), outcellhd.west, owest); G_message(_("East: %f (%f)"), outcellhd.east, oeast); G_message(_("EW-res: %f"), outcellhd.ew_res); G_message(_("NS-res: %f"), outcellhd.ns_res); G_message(" "); /* open and read the relevant parts of the input map and close it */ G__switch_env(); Rast_set_input_window(&incellhd); fdi = Rast_open_old(inmap->answer, setname); cell_type = Rast_get_map_type(fdi); ibuffer = readcell(fdi, memory->answer); Rast_close(fdi); G__switch_env(); Rast_set_output_window(&outcellhd); if (strcmp(interpol->answer, "nearest") == 0) { fdo = Rast_open_new(mapname, cell_type); obuffer = (CELL *) Rast_allocate_output_buf(cell_type); } else { fdo = Rast_open_fp_new(mapname); cell_type = FCELL_TYPE; obuffer = (FCELL *) Rast_allocate_output_buf(cell_type); } cell_size = Rast_cell_size(cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2); /**/ G_important_message(_("Projecting...")); G_percent(0, outcellhd.rows, 2); for (row = 0; row < outcellhd.rows; row++) { obufptr = obuffer; for (col = 0; col < outcellhd.cols; col++) { /* project coordinates in output matrix to */ /* coordinates in input matrix */ if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0) Rast_set_null_value(obufptr, 1, cell_type); else { /* convert to row/column indices of input matrix */ col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res; row_idx = (incellhd.north - ycoord1) / incellhd.ns_res; /* and resample data point */ interpolate(ibuffer, obufptr, cell_type, &col_idx, &row_idx, &incellhd); } obufptr = G_incr_void_ptr(obufptr, cell_size); xcoord2 += outcellhd.ew_res; xcoord1 = xcoord2; ycoord1 = ycoord2; } Rast_put_row(fdo, obuffer, cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); ycoord2 -= outcellhd.ns_res; ycoord1 = ycoord2; G_percent(row, outcellhd.rows - 1, 2); } Rast_close(fdo); if (have_colors > 0) { Rast_write_colors(mapname, G_mapset(), &colr); Rast_free_colors(&colr); } Rast_short_history(mapname, "raster", &history); Rast_command_history(&history); Rast_write_history(mapname, &history); G_done_msg(NULL); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKAVG, *inrast_TEMPKMIN, *inrast_TEMPKMAX, *inrast_RNET, *inrast_P; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKAVG, infd_TEMPKMIN, infd_TEMPKMAX, infd_RNET, infd_P; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKAVG, *TEMPKMIN, *TEMPKMAX, *P; char *ETa; /* input-output cell values */ DCELL d_tempkavg, d_tempkmin, d_tempkmax, d_rnet, d_p; DCELL d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKAVG, *input_TEMPKMIN; struct Option *input_TEMPKMAX, *input_P; struct Option *output; struct Flag *zero, *original, *samani; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "modified or original Hargreaves formulation, 2001."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "netradiation_diurnal"; input_RNET->description = _("Name of input diurnal net radiation raster map [W/m2/d]"); input_TEMPKAVG = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKAVG->key = "average_temperature"; input_TEMPKAVG->description = _("Name of input average air temperature raster map [C]"); input_TEMPKMIN = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKMIN->key = "minimum_temperature"; input_TEMPKMIN->description = _("Name of input minimum air temperature raster map [C]"); input_TEMPKMAX = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKMAX->key = "maximum_temperature"; input_TEMPKMAX->description = _("Name of input maximum air temperature raster map [C]"); input_P = G_define_standard_option(G_OPT_R_INPUT); input_P->required = NO; input_P->key = "precipitation"; input_P->label = _("Name of precipitation raster map [mm/month]"); input_P->description = _("Disabled for original Hargreaves (1985)"); output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name for output raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); original = G_define_flag(); original->key = 'h'; original->description = _("Use original Hargreaves (1985)"); samani = G_define_flag(); samani->key = 's'; samani->description = _("Use Hargreaves-Samani (1985)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKAVG = input_TEMPKAVG->answer; TEMPKMIN = input_TEMPKMIN->answer; TEMPKMAX = input_TEMPKMAX->answer; P = input_P->answer; ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKAVG = Rast_open_old(TEMPKAVG, ""); infd_TEMPKMIN = Rast_open_old(TEMPKMIN, ""); infd_TEMPKMAX = Rast_open_old(TEMPKMAX, ""); if (!original->answer) { infd_P = Rast_open_old(P, ""); } /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKAVG, "", &cellhd); Rast_get_cellhd(TEMPKMIN, "", &cellhd); Rast_get_cellhd(TEMPKMAX, "", &cellhd); if (!original->answer) { Rast_get_cellhd(P, "", &cellhd); } /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKAVG = Rast_allocate_d_buf(); inrast_TEMPKMIN = Rast_allocate_d_buf(); inrast_TEMPKMAX = Rast_allocate_d_buf(); if (!original->answer) { inrast_P = Rast_allocate_d_buf(); } /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKAVG, inrast_TEMPKAVG, row); Rast_get_d_row(infd_TEMPKMIN, inrast_TEMPKMIN, row); Rast_get_d_row(infd_TEMPKMAX, inrast_TEMPKMAX, row); if (!original->answer) { Rast_get_d_row(infd_P, inrast_P, row); } for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempkavg = ((DCELL *) inrast_TEMPKAVG)[col]; d_tempkmin = ((DCELL *) inrast_TEMPKMIN)[col]; d_tempkmax = ((DCELL *) inrast_TEMPKMAX)[col]; if (!original->answer) { d_p = ((DCELL *) inrast_P)[col]; } if (Rast_is_d_null_value(&d_rnet) || Rast_is_d_null_value(&d_tempkavg) || Rast_is_d_null_value(&d_tempkmin) || Rast_is_d_null_value(&d_tempkmax) || Rast_is_d_null_value(&d_p)) { Rast_set_d_null_value(&outrast[col], 1); } else { if (original->answer) { d_daily_et = mh_original(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin, d_p); } else if (samani->answer) { d_daily_et = mh_samani(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin); } else { d_daily_et = mh_eto(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin, d_p); } if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKAVG); G_free(inrast_TEMPKMIN); G_free(inrast_TEMPKMAX); if (!original->answer) { G_free(inrast_P); } Rast_close(infd_RNET); Rast_close(infd_TEMPKAVG); Rast_close(infd_TEMPKMIN); Rast_close(infd_TEMPKMAX); if (!original->answer) { Rast_close(infd_P); } /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return(EXIT_SUCCESS); }