int main( int argc, char **argv ) { char *mapset; char *name; int fp; struct GModule *module; struct Option *map; struct Option *win; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->keywords = ( "display, raster" ); module->description = ( "Output raster map layers in a format suitable for display in QGIS" ); map = G_define_standard_option( G_OPT_R_MAP ); map->description = ( "Raster map to be displayed" ); win = G_define_option(); win->key = "window"; win->type = TYPE_DOUBLE; win->multiple = YES; win->description = "xmin,ymin,xmax,ymax,ncols,nrows"; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); name = map->answer; /* Make sure map is available */ mapset = G_find_cell2( name, "" ); if ( mapset == NULL ) G_fatal_error(( "Raster map <%s> not found" ), name ); /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and * cellhd, and G_open_cell_old fails, so it is better to read window from map */ /* G_get_window( &window ); */ G_get_cellhd( name, mapset, &window ); window.west = atof( win->answers[0] ); window.south = atof( win->answers[1] ); window.east = atof( win->answers[2] ); window.north = atof( win->answers[3] ); window.cols = atoi( win->answers[4] ); window.rows = atoi( win->answers[5] ); G_adjust_Cell_head( &window, 1, 1 ); G_set_window( &window ); fp = G_raster_map_is_fp( name, mapset ); /* use DCELL even if the map is FCELL */ if ( fp ) display( name, mapset, DCELL_TYPE ); else display( name, mapset, CELL_TYPE ); exit( EXIT_SUCCESS ); }
/* * do_histogram() - Creates histogram for CELL * * RETURN: 0 on success / 1 on failure */ int do_histogram(char *name, char *mapset) { CELL *cell; struct Cell_head cellhd; struct Cell_stats statf; int nrows, ncols; int row; int fd; if (G_get_cellhd(name, mapset, &cellhd) < 0) return 1; G_set_window(&cellhd); if ((fd = G_open_cell_old(name, mapset)) < 0) return 1; nrows = G_window_rows(); ncols = G_window_cols(); cell = G_allocate_cell_buf(); G_init_cell_stats(&statf); /* Update statistics for each row */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); if (G_get_map_row_nomask(fd, cell, row) < 0) break; G_update_cell_stats(cell, ncols, &statf); } /* Write histogram if it made it through the loop */ if (row == nrows) G_write_histogram_cs(name, &statf); G_free_cell_stats(&statf); G_close_cell(fd); G_free(cell); if (row == nrows) return 0; return 1; }
int patchAreaDistributionCV(int fd, char **par, area_des ad, double *result) { char *mapset; double indice = 0; struct Cell_head hd; int ris = RLI_OK; mapset = G_find_cell(ad->raster, ""); if (G_get_cellhd(ad->raster, mapset, &hd) == -1) return RLI_ERRORE; switch (ad->data_type) { case CELL_TYPE: { ris = calculate(fd, ad, &indice); break; } case DCELL_TYPE: { ris = calculateD(fd, ad, &indice); break; } case FCELL_TYPE: { ris = calculateF(fd, ad, &indice); break; } default: { G_fatal_error("data type unknown"); return RLI_ERRORE; } } if (ris != RLI_OK) { *result = -1; return RLI_ERRORE; } *result = indice; return RLI_OK; }
int get_cats(char *name, char *mapset) { int fd; int row, nrows, ncols; CELL *cell; struct Cell_head cellhd; /* set the window to the cell header */ if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error(_("Cannot read header of raster map <%s> in <%s>"), name, mapset); G_set_window(&cellhd); /* open the raster map */ fd = G_open_cell_old(name, mapset); if (fd < 0) G_fatal_error(_("Cannot open cell file of raster map <%s> in <%s>"), name, mapset); nrows = G_window_rows(); ncols = G_window_cols(); cell = G_allocate_cell_buf(); G_init_cell_stats(&statf); /* read the raster map */ G_verbose_message(_("Reading <%s> in <%s>"), name, mapset); for (row = 0; row < nrows; row++) { if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); if (G_get_c_raster_row_nomask(fd, cell, row) < 0) exit(EXIT_SUCCESS); G_update_cell_stats(cell, ncols, &statf); } /* done */ if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); G_close_cell(fd); G_free(cell); G_rewind_cell_stats(&statf); return 0; }
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand, const char * pszMapset, const char * pszCellName ) { struct Cell_head sCellInfo; // Note: GISDBASE, LOCATION_NAME ans MAPSET was set in GRASSDataset::Open this->poDS = poDS; this->nBand = nBand; this->valid = false; this->pszCellName = G_store ( (char *) pszCellName ); this->pszMapset = G_store ( (char *) pszMapset ); G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo ); nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset ); /* -------------------------------------------------------------------- */ /* Get min/max values. */ /* -------------------------------------------------------------------- */ struct FPRange sRange; if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, &sRange ) == -1 ) { bHaveMinMax = FALSE; } else { bHaveMinMax = TRUE; G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax ); } /* -------------------------------------------------------------------- */ /* Setup band type, and preferred nodata value. */ /* -------------------------------------------------------------------- */ // Negative values are also (?) stored as 4 bytes (format = 3) // => raster with format < 3 has only positive values // GRASS modules usually do not waste space and only the format necessary to keep // full raster values range is used -> no checks if shorter type could be used if( nGRSType == CELL_TYPE ) { if ( sCellInfo.format == 0 ) { // 1 byte / cell -> possible range 0,255 if ( bHaveMinMax && dfCellMin > 0 ) { this->eDataType = GDT_Byte; dfNoData = 0.0; } else if ( bHaveMinMax && dfCellMax < 255 ) { this->eDataType = GDT_Byte; dfNoData = 255.0; } else { // maximum is not known or full range is used this->eDataType = GDT_UInt16; dfNoData = 256.0; } nativeNulls = false; } else if ( sCellInfo.format == 1 ) { // 2 bytes / cell -> possible range 0,65535 if ( bHaveMinMax && dfCellMin > 0 ) { this->eDataType = GDT_UInt16; dfNoData = 0.0; } else if ( bHaveMinMax && dfCellMax < 65535 ) { this->eDataType = GDT_UInt16; dfNoData = 65535; } else { // maximum is not known or full range is used CELL cval; this->eDataType = GDT_Int32; G_set_c_null_value ( &cval, 1); dfNoData = (double) cval; nativeNulls = true; } nativeNulls = false; } else { // 3-4 bytes CELL cval; this->eDataType = GDT_Int32; G_set_c_null_value ( &cval, 1); dfNoData = (double) cval; nativeNulls = true; } } else if( nGRSType == FCELL_TYPE ) { FCELL fval; this->eDataType = GDT_Float32; G_set_f_null_value ( &fval, 1); dfNoData = (double) fval; nativeNulls = true; } else if( nGRSType == DCELL_TYPE ) { DCELL dval; this->eDataType = GDT_Float64; G_set_d_null_value ( &dval, 1); dfNoData = (double) dval; nativeNulls = true; } nBlockXSize = poDS->nRasterXSize;; nBlockYSize = 1; G_set_window( &(((GRASSDataset *)poDS)->sCellInfo) ); if ( (hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset)) < 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName ); return; } G_copy((void *) &sOpenWindow, (void *) &(((GRASSDataset *)poDS)->sCellInfo), sizeof(struct Cell_head)); /* -------------------------------------------------------------------- */ /* Do we have a color table? */ /* -------------------------------------------------------------------- */ poCT = NULL; if( G_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 ) { int maxcolor; CELL min, max; G_get_color_range ( &min, &max, &sGrassColors); if ( bHaveMinMax ) { if ( max < dfCellMax ) { maxcolor = max; } else { maxcolor = (int) ceil ( dfCellMax ); } if ( maxcolor > GRASS_MAX_COLORS ) { maxcolor = GRASS_MAX_COLORS; CPLDebug( "GRASS", "Too many values, color table cut to %d entries.", maxcolor ); } } else { if ( max < GRASS_MAX_COLORS ) { maxcolor = max; } else { maxcolor = GRASS_MAX_COLORS; CPLDebug( "GRASS", "Too many values, color table set to %d entries.", maxcolor ); } } poCT = new GDALColorTable(); for( int iColor = 0; iColor <= maxcolor; iColor++ ) { int nRed, nGreen, nBlue; GDALColorEntry sColor; #if GRASS_VERSION_MAJOR >= 7 if( Rast_get_c_color( &iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) #else if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) #endif { sColor.c1 = nRed; sColor.c2 = nGreen; sColor.c3 = nBlue; sColor.c4 = 255; poCT->SetColorEntry( iColor, &sColor ); } else { sColor.c1 = 0; sColor.c2 = 0; sColor.c3 = 0; sColor.c4 = 0; poCT->SetColorEntry( iColor, &sColor ); } } /* Create metadata enries for color table rules */ char key[200], value[200]; int rcount = G_colors_count ( &sGrassColors ); sprintf ( value, "%d", rcount ); this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", value ); /* Add the rules in reverse order */ for ( int i = rcount-1; i >= 0; i-- ) { DCELL val1, val2; unsigned char r1, g1, b1, r2, g2, b2; G_get_f_color_rule ( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &sGrassColors, i ); sprintf ( key, "COLOR_TABLE_RULE_RGB_%d", rcount-i-1 ); sprintf ( value, "%e %e %d %d %d %d %d %d", val1, val2, r1, g1, b1, r2, g2, b2 ); this->SetMetadataItem( key, value ); } } else { this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", "0" ); } this->valid = true; }
int main( int argc, char **argv ) { struct GModule *module; struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt, *north_opt, *south_opt, *east_opt, *west_opt, *rows_opt, *cols_opt; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Get info about locations,mapsets,maps" ); info_opt = G_define_option(); info_opt->key = "info"; info_opt->type = TYPE_STRING; info_opt->description = "info key"; info_opt->options = "proj,window,size,query,info,colors,stats"; rast_opt = G_define_standard_option( G_OPT_R_INPUT ); rast_opt->key = "rast"; rast_opt->required = NO; vect_opt = G_define_standard_option( G_OPT_V_INPUT ); vect_opt->key = "vect"; vect_opt->required = NO; coor_opt = G_define_option(); coor_opt->key = "coor"; coor_opt->type = TYPE_DOUBLE; coor_opt->multiple = YES; north_opt = G_define_option(); north_opt->key = "north"; north_opt->type = TYPE_STRING; south_opt = G_define_option(); south_opt->key = "south"; south_opt->type = TYPE_STRING; east_opt = G_define_option(); east_opt->key = "east"; east_opt->type = TYPE_STRING; west_opt = G_define_option(); west_opt->key = "west"; west_opt->type = TYPE_STRING; rows_opt = G_define_option(); rows_opt->key = "rows"; rows_opt->type = TYPE_INTEGER; cols_opt = G_define_option(); cols_opt->key = "cols"; cols_opt->type = TYPE_INTEGER; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); if ( strcmp( "proj", info_opt->answer ) == 0 ) { G_get_window( &window ); /* code from g.proj */ if ( window.proj != PROJECTION_XY ) { struct Key_Value *projinfo, *projunits; char *wkt; projinfo = G_get_projinfo(); projunits = G_get_projunits(); wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 ); fprintf( stdout, "%s", wkt ); } } else if ( strcmp( "window", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } // raster width and height else if ( strcmp( "size", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%d,%d", window.cols, window.rows ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } // raster informations else if ( strcmp( "info", info_opt->answer ) == 0 ) { struct FPRange range; double zmin, zmax; // Data type RASTER_MAP_TYPE raster_type = G_raster_map_type( rast_opt->answer, "" ); fprintf( stdout, "TYPE:%d\n", raster_type ); // Statistics if ( G_read_fp_range( rast_opt->answer, "", &range ) < 0 ) { G_fatal_error(( "Unable to read range file" ) ); } G_get_fp_range_min_max( &range, &zmin, &zmax ); fprintf( stdout, "MIN_VALUE:%.17e\n", zmin ); fprintf( stdout, "MAX_VALUE:%.17e\n", zmax ); } else if ( strcmp( "colors", info_opt->answer ) == 0 ) { // Color table struct Colors colors; int i, ccount; if ( G_read_colors( rast_opt->answer, "", &colors ) == 1 ) { //int maxcolor; //CELL min, max; //G_get_color_range ( &min, &max, &colors); ccount = G_colors_count( &colors ); for ( i = ccount - 1; i >= 0; i-- ) { DCELL val1, val2; unsigned char r1, g1, b1, r2, g2, b2; G_get_f_color_rule( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &colors, i ); fprintf( stdout, "%.17e %.17e %d %d %d %d %d %d\n", val1, val2, r1, g1, b1, r2, g2, b2 ); } } } else if ( strcmp( "query", info_opt->answer ) == 0 ) { double x, y; int row, col; //x = atof( coor_opt->answers[0] ); //y = atof( coor_opt->answers[1] ); if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; char buff[101]; G_get_cellhd( rast_opt->answer, "", &window ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); // wait for coors from stdin while ( fgets( buff, 100, stdin ) != 0 ) { if ( sscanf( buff, "%lf%lf", &x, &y ) != 2 ) { fprintf( stdout, "value:error\n" ); } else { col = ( int ) G_easting_to_col( x, &window ); row = ( int ) G_northing_to_row( y, &window ); if ( col == window.cols ) col--; if ( row == window.rows ) row--; if ( col < 0 || col > window.cols || row < 0 || row > window.rows ) { fprintf( stdout, "value:out\n" ); } else { void *ptr; double val; #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = cell[col]; ptr = &( cell[col] ); } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = dcell[col]; ptr = &( dcell[col] ); } if ( G_is_null_value( ptr, rast_type ) ) { fprintf( stdout, "value:null\n" ); } else { fprintf( stdout, "value:%f\n", val ); } } } fflush( stdout ); } G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } else if ( strcmp( "stats", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; int ncols, nrows; int row, col; void *ptr; double val; double min = DBL_MAX; double max = -DBL_MAX; double sum = 0; // sum of values int count = 0; // count of non null values double mean = 0; double squares_sum = 0; // sum of squares double stdev = 0; // standard deviation G_get_cellhd( rast_opt->answer, "", &window ); window.north = atof( north_opt->answer ); window.south = atof( south_opt->answer ); window.east = atof( east_opt->answer ); window.west = atof( west_opt->answer ); window.rows = ( int ) atoi( rows_opt->answer ); window.cols = ( int ) atoi( cols_opt->answer ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); ncols = G_window_cols(); nrows = G_window_rows(); #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); // Calc stats is very slow for large rasters -> prefer optimization for speed over // code length and readability (which is not currently true) for ( row = 0; row < nrows; row++ ) { if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } } for ( col = 0; col < ncols; col++ ) { if ( rast_type == CELL_TYPE ) { val = cell[col]; ptr = &( cell[col] ); } else { val = dcell[col]; ptr = &( dcell[col] ); } if ( ! G_is_null_value( ptr, rast_type ) ) { if ( val < min ) min = val; if ( val > max ) max = val; sum += val; count++; squares_sum += pow( val, 2 ); } } } mean = sum / count; squares_sum -= count * pow( mean, 2 ); stdev = sqrt( squares_sum / ( count - 1 ) ); fprintf( stdout, "MIN:%.17e\n", min ); fprintf( stdout, "MAX:%.17e\n", max ); fprintf( stdout, "SUM:%.17e\n", sum ); fprintf( stdout, "MEAN:%.17e\n", mean ); fprintf( stdout, "COUNT:%d\n", count ); fprintf( stdout, "STDEV:%.17e\n", stdev ); fprintf( stdout, "SQSUM:%.17e\n", squares_sum ); G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } exit( EXIT_SUCCESS ); }
int main(int argc, char *argv[]) { char group[INAME_LEN], extension[INAME_LEN]; int order; /* ADDED WITH CRS MODIFICATIONS */ char *ipolname; /* name of interpolation method */ int method; int n, i, m, k = 0; int got_file = 0, target_overwrite = 0; char *overstr; struct Cell_head cellhd; struct Option *grp, /* imagery group */ *val, /* transformation order */ *ifile, /* input files */ *ext, /* extension */ *tres, /* target resolution */ *mem, /* amount of memory for cache */ *interpol; /* interpolation method: nearest neighbor, bilinear, cubic */ struct Flag *c, *a; struct GModule *module; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("imagery, rectify"); module->description = _("Rectifies an image by computing a coordinate " "transformation for each pixel in the image based on the " "control points."); grp = G_define_standard_option(G_OPT_I_GROUP); ifile = G_define_standard_option(G_OPT_R_INPUTS); ifile->required = NO; ext = G_define_option(); ext->key = "extension"; ext->type = TYPE_STRING; ext->required = YES; ext->multiple = NO; ext->description = _("Output raster map(s) suffix"); val = G_define_option(); val->key = "order"; val->type = TYPE_INTEGER; val->required = YES; val->description = _("Rectification polynom order (1-3)"); tres = G_define_option(); tres->key = "res"; tres->type = TYPE_DOUBLE; tres->required = NO; tres->description = _("Target resolution (ignored if -c flag used)"); mem = G_define_option(); mem->key = "memory"; mem->type = TYPE_DOUBLE; mem->key_desc = "memory in MB"; mem->required = NO; mem->answer = "300"; mem->description = _("Amount of memory to use in MB"); 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"); c = G_define_flag(); c->key = 'c'; c->description = _("Use current region settings in target location (def.=calculate smallest area)"); a = G_define_flag(); a->key = 'a'; a->description = _("Rectify all raster maps in group"); 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; G_strip(grp->answer); strcpy(group, grp->answer); strcpy(extension, ext->answer); order = atoi(val->answer); seg_mb = NULL; if (mem->answer) { if (atoi(mem->answer) > 0) seg_mb = mem->answer; } if (!ifile->answers) a->answer = 1; /* force all */ /* Find out how many files on command line */ if (!a->answer) { for (m = 0; ifile->answers[m]; m++) { k = m; } k++; } if (order < 1 || order > MAXORDER) G_fatal_error(_("Invalid order (%d); please enter 1 to %d"), order, MAXORDER); /* determine the number of files in this group */ if (I_get_group_ref(group, &ref) <= 0) G_fatal_error(_("Group <%s> does not exist"), grp->answer); if (ref.nfiles <= 0) { G_important_message(_("Group <%s> contains no raster maps; run i.group"), grp->answer); exit(EXIT_SUCCESS); } ref_list = (int *)G_malloc(ref.nfiles * sizeof(int)); if (a->answer) { for (n = 0; n < ref.nfiles; n++) { ref_list[n] = 1; } } else { char xname[GNAME_MAX], xmapset[GMAPSET_MAX], *name, *mapset; for (n = 0; n < ref.nfiles; n++) ref_list[n] = 0; for (m = 0; m < k; m++) { got_file = 0; if (G__name_is_fully_qualified(ifile->answers[m], xname, xmapset)) { name = xname; mapset = xmapset; } else { name = ifile->answers[m]; mapset = NULL; } got_file = 0; for (n = 0; n < ref.nfiles; n++) { if (mapset) { if (strcmp(name, ref.file[n].name) == 0 && strcmp(mapset, ref.file[n].mapset) == 0) { got_file = 1; ref_list[n] = 1; break; } } else { if (strcmp(name, ref.file[n].name) == 0) { got_file = 1; ref_list[n] = 1; break; } } } if (got_file == 0) err_exit(ifile->answers[m], group); } } /* read the control points for the group */ get_control_points(group, order); /* get the target */ get_target(group); /* Check the GRASS_OVERWRITE environment variable */ if ((overstr = getenv("GRASS_OVERWRITE"))) /* OK ? */ target_overwrite = atoi(overstr); if (!target_overwrite) { /* check if output exists in target location/mapset */ char result[GNAME_MAX]; select_target_env(); for (i = 0; i < ref.nfiles; i++) { if (!ref_list[i]) continue; strcpy(result, ref.file[i].name); strcat(result, extension); if (G_legal_filename(result) < 0) G_fatal_error(_("Extension <%s> is illegal"), extension); if (G_find_cell(result, G_mapset())) { G_warning(_("The following raster map already exists in")); G_warning(_("target LOCATION %s, MAPSET %s:"), G_location(), G_mapset()); G_warning("<%s>", result); G_fatal_error(_("Orthorectification cancelled.")); } } select_current_env(); } else G_debug(1, "Overwriting OK"); /* do not use current region in target location */ if (!c->answer) { double res = -1; if (tres->answer) { if (!((res = atof(tres->answer)) > 0)) G_warning(_("Target resolution must be > 0, ignored")); } /* Calculate smallest region */ if (a->answer) { if (G_get_cellhd(ref.file[0].name, ref.file[0].mapset, &cellhd) < 0) G_fatal_error(_("Unable to read header of raster map <%s>"), ref.file[0].name); } else { if (G_get_cellhd(ifile->answers[0], ref.file[0].mapset, &cellhd) < 0) G_fatal_error(_("Unable to read header of raster map <%s>"), ifile->answers[0]); } georef_window(&cellhd, &target_window, order, res); } G_verbose_message(_("Using region: N=%f S=%f, E=%f W=%f"), target_window.north, target_window.south, target_window.east, target_window.west); exec_rectify(order, extension, interpol->answer); G_done_msg(" "); exit(EXIT_SUCCESS); }
int describe(char *name, char *mapset, int compact, char *no_data_str, int range, int windowed, int nsteps, int as_int, int skip_nulls) { int fd; struct Cell_stats statf; CELL *buf, *b; int nrows, ncols; int row, col; struct Cell_head window; CELL negmin = 0, negmax = 0, zero = 0, posmin = 0, posmax = 0; CELL null = 0; RASTER_MAP_TYPE map_type; struct Quant q; struct FPRange r; DCELL dmin, dmax; int (*get_row) (); if (windowed) { get_row = G_get_c_raster_row; } else { char msg[100]; if (G_get_cellhd(name, mapset, &window) < 0) { sprintf(msg, "can't get cell header for [%s] in [%s]", name, mapset); G_fatal_error(msg); } G_set_window(&window); get_row = G_get_c_raster_row_nomask; } fd = G_open_cell_old(name, mapset); if (fd < 0) return 0; map_type = G_get_raster_map_type(fd); if (as_int) map_type = CELL_TYPE; /* read as int */ /* allocate the cell buffer */ buf = G_allocate_cell_buf(); if (map_type != CELL_TYPE && range) /* this will make it report fp range */ { range = 0; nsteps = 1; } /* start the cell stats */ if (!range) { G_init_cell_stats(&statf); } else { zero = 0; negmin = 0; negmax = 0; posmin = 0; posmax = 0; null = 0; dmin = 0.0; dmax = 0.0; } /* set up quantization rules */ if (map_type != CELL_TYPE) { G_quant_init(&q); G_read_fp_range(name, mapset, &r); G_get_fp_range_min_max(&r, &dmin, &dmax); G_quant_add_rule(&q, dmin, dmax, 1, nsteps); G_set_quant_rules(fd, &q); } nrows = G_window_rows(); ncols = G_window_cols(); G_verbose_message("Reading [%s in %s] ...", name, mapset); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); if ((*get_row) (fd, b = buf, row) < 0) break; if (range) { for (col = ncols; col-- > 0; b++) { if (G_is_c_null_value(b)) null = 1; else if (*b == 0) zero = 1; else if (*b < 0) { if (!negmin) negmin = negmax = *b; else if (*b > negmax) negmax = *b; else if (*b < negmin) negmin = *b; } else { if (!posmin) posmin = posmax = *b; else if (*b > posmax) posmax = *b; else if (*b < posmin) posmin = *b; } } } else G_update_cell_stats(buf, ncols, &statf); } G_percent(nrows, nrows, 2); G_close_cell(fd); G_free(buf); if (range) { if (compact) compact_range_list(negmin, negmax, zero, posmin, posmax, null, no_data_str, skip_nulls); else range_list(negmin, negmax, zero, posmin, posmax, null, no_data_str, skip_nulls); } else { G_rewind_cell_stats(&statf); if (compact) compact_list(&statf, dmin, dmax, no_data_str, skip_nulls, map_type, nsteps); else long_list(&statf, dmin, dmax, no_data_str, skip_nulls, map_type, nsteps); G_free_cell_stats(&statf); } return 1; }
bool GRASS_EXPORT QgsGrass::mapRegion( int type, QString gisbase, QString location, QString mapset, QString map, struct Cell_head *window ) { QgsDebugMsg( "entered." ); QgsDebugMsg( QString( "map = %1" ).arg( map ) ); QgsDebugMsg( QString( "mapset = %1" ).arg( mapset ) ); QgsGrass::setLocation( gisbase, location ); if ( type == Raster ) { if ( G_get_cellhd( map.toUtf8().data(), mapset.toUtf8().data(), window ) < 0 ) { QMessageBox::warning( 0, QObject::tr( "Warning" ), QObject::tr( "Cannot read raster map region" ) ); return false; } } else if ( type == Vector ) { // Get current projection region( gisbase, location, mapset, window ); struct Map_info Map; int level = Vect_open_old_head( &Map, map.toUtf8().data(), mapset.toUtf8().data() ); if ( level < 2 ) { QMessageBox::warning( 0, QObject::tr( "Warning" ), QObject::tr( "Cannot read vector map region" ) ); return false; } BOUND_BOX box; Vect_get_map_box( &Map, &box ); window->north = box.N; window->south = box.S; window->west = box.W; window->east = box.E; window->top = box.T; window->bottom = box.B; // Is this optimal ? window->ns_res = ( window->north - window->south ) / 1000; window->ew_res = window->ns_res; if ( window->top > window->bottom ) { window->tb_res = ( window->top - window->bottom ) / 10; } else { window->top = window->bottom + 1; window->tb_res = 1; } G_adjust_Cell_head3( window, 0, 0, 0 ); Vect_close( &Map ); } else if ( type == Region ) { if ( G__get_window( window, ( char * ) "windows", map.toUtf8().data(), mapset.toUtf8().data() ) != NULL ) { QMessageBox::warning( 0, QObject::tr( "Warning" ), QObject::tr( "Cannot read region" ) ); return false; } } return true; }
int main(int argc, char **argv) { struct GModule *module; int i, first = 1; char *mapset; char **rast, **vect; int nrasts, nvects; struct Cell_head window, temp_window; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("display, setup"); module->description = "Sets window region so that all currently displayed raster " "and vector maps can be shown in a monitor."; if (argc > 1 && G_parser(argc, argv)) exit(-1); if (R_open_driver() != 0) G_fatal_error(_("No graphics device selected")); if (D_get_cell_list(&rast, &nrasts) < 0) rast = NULL; if (D_get_dig_list(&vect, &nvects) < 0) vect = NULL; R_close_driver(); if (rast == NULL && vect == NULL) G_fatal_error(_("No raster or vector map displayed")); G_get_window(&window); if (rast) { for (i = 0; i < nrasts; i++) { mapset = G_find_cell2(rast[i], ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), rast[i]); if (G_get_cellhd(rast[i], mapset, &temp_window) >= 0) { if (first) { first = 0; G_copy(&window, &temp_window, sizeof(window)); } else { if (window.east < temp_window.east) window.east = temp_window.east; if (window.west > temp_window.west) window.west = temp_window.west; if (window.south > temp_window.south) window.south = temp_window.south; if (window.north < temp_window.north) window.north = temp_window.north; /* if(window.ns_res < nsres) nsres = window.ns_res; if(window.ew_res < ewres) ewres = window.ew_res; */ } } } G_adjust_Cell_head3(&window, 0, 0, 0); } if (vect) { struct Map_info Map; G_copy(&temp_window, &window, sizeof(window)); Vect_set_open_level(2); for (i = 0; i < nvects; i++) { mapset = G_find_vector2(vect[i], ""); if (mapset == NULL) G_fatal_error(_("Vector map <%s> not found"), vect[i]); if (Vect_open_old_head(&Map, vect[i], mapset) == 2) { if (first) { first = 0; window.east = Map.plus.box.E; window.west = Map.plus.box.W; window.south = Map.plus.box.S; window.north = Map.plus.box.N; } else { if (window.east < Map.plus.box.E) window.east = Map.plus.box.E; if (window.west > Map.plus.box.W) window.west = Map.plus.box.W; if (window.south > Map.plus.box.S) window.south = Map.plus.box.S; if (window.north < Map.plus.box.N) window.north = Map.plus.box.N; } Vect_close(&Map); } } if (window.north == window.south) { window.north += 0.5 * temp_window.ns_res; window.south -= 0.5 * temp_window.ns_res; } if (window.east == window.west) { window.east += 0.5 * temp_window.ew_res; window.west -= 0.5 * temp_window.ew_res; } G_align_window(&window, &temp_window); } G_adjust_Cell_head3(&window, 0, 0, 0); G_put_window(&window); exit(0); }
/* * main function */ int main(int argc, char *argv[]) { /* struct Cell_head window; database window */ struct Cell_head cellhd; /* it stores region information, and header information of rasters */ char *name, *name2; /* input raster name */ char *result; /* output raster name */ char *mapset; /* mapset name */ void *inrast; /* input buffer */ unsigned char *outrast; /* output buffer */ int nrows, ncols; int row, col; int infd, outfd; /* file descriptor */ int verbose; struct History history; /* holds meta-data (title, comments,..) */ struct GModule *module; /* GRASS module for parsing arguments */ struct Option *input, *output, *input2; /* options */ FILE *in; /*file for Path loss factors*/ struct Flag *flag1; /* flags */ char buffer_out[1000]; strcpy(buffer_out,getenv("GISBASE")); strcat(buffer_out,"/etc/radio_coverage/lossfactors_new.txt"); /*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); buffer_out=strcat(buffer_path,buffer_path1); G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);*/ /* initialize GIS environment */ G_gisinit(argv[0]); /* reads grass env, stores program name to G_program_name() */ /* initialize module */ module = G_define_module(); module->keywords = _("raster, clutter"); module->description = _("Clutter convert module"); /* Define the different options as defined in gis.h */ input = G_define_standard_option(G_OPT_R_INPUT); input2 = G_define_standard_option(G_OPT_F_INPUT); input2->key = "Path_loss_values"; input2->type = TYPE_STRING; input2->required = YES; input2->answer = buffer_out;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage"); input2->gisprompt = "old_file,file,input"; input2->description = _("Path loss factors for land usage"); /* Define the different flags */ flag1 = G_define_flag(); flag1->key = 'o'; flag1->description = _("Old_Cipher"); output = G_define_standard_option(G_OPT_R_OUTPUT); /* options and flags parser */ if (G_parser(argc, argv)) { exit(EXIT_FAILURE); } /*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); strcat(buffer_path,buffer_path1); G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); input2->answer = buffer_path;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage");*/ /* stores options and flags to variables */ name = input->answer; name2 = input2->answer; result = output->answer; verbose = (flag1->answer); G_message(_("Verbose: %d"),verbose); /* returns NULL if the map was not found in any mapset, * mapset name otherwise */ //G_message(_("3_START")); mapset = G_find_cell2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), name); if (G_legal_filename(result) < 0) G_fatal_error(_("<%s> is an illegal file name"), result); /* G_open_cell_old - returns file destriptor (>0) */ if ((infd = G_open_cell_old(name, mapset)) < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); /* controlling, if we can open input raster */ if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error(_("Unable to read file header of <%s>"), name); G_debug(3, "number of rows %d", cellhd.rows); G_set_window(&cellhd); G_get_set_window(&cellhd); /* Allocate input buffer */ inrast = G_allocate_raster_buf(FCELL_TYPE); /* Allocate output buffer, use input map data_type */ nrows = G_window_rows(); ncols = G_window_cols(); outrast = G_allocate_raster_buf(FCELL_TYPE); G_message(_("nrows %d and ncols %d"),nrows,ncols); /* controlling, if we can write the raster */ if ((outfd = G_open_raster_new(result, FCELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), result); /* do Clutter Convert */ /* open file for model tuning parameters*/ char fileName[150]; strcpy (fileName, name2); //G_message(_("Path: %s"),name2); if( (in = fopen(fileName,"r")) == NULL ) G_fatal_error(_("Unable to open file <%s>"), fileName); char buffer[256]; double terr_path_loss[100]; int counter=0; fgets (buffer, 250, in); while(fgets(buffer,250,in)!=NULL){ sscanf(buffer,"%lf %lf", &terr_path_loss[counter]); counter++; } int cipher_cont=0; /* old or new clutter */ if (verbose == 1) { cipher_cont=1; G_message(_("Parameter UR: %f, GP: %f, RP: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9]); } else if (verbose == 0) { cipher_cont=11; G_message(_("Parameter UR1: %f, UR2: %f, UR3: %f, UR4: %f, UR5: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9], terr_path_loss[10], terr_path_loss[11]); } G_message(_("Counter: %d"),counter); G_message(_("cipher_cont: %d"),cipher_cont); G_message(_("START")); /* for each row */ for (row = 0; row < nrows; row++) { FCELL f_in, f_out; /* read input map */ if (G_get_raster_row(infd, inrast, row, FCELL_TYPE) < 0) G_fatal_error(_("Unable to read raster map <%s> row %d"), name, row); /* process the data */ for (col = 0; col < ncols; col++) { f_in = ((FCELL *) inrast)[col]; //G_message(_("Input data: %d"),(int)f_in); f_out = terr_path_loss[(int)f_in-cipher_cont]; //G_message(_("Output data: %f"),(double)f_out); ((FCELL *) outrast)[col] = f_out; } /* write raster row to output raster map */ if (G_put_raster_row(outfd, outrast, FCELL_TYPE) < 0) G_fatal_error(_("Failed writing raster map <%s>"), result); } //G_message(_("END_clutconvert_test")); G_message(_("END")); /* memory cleanup */ G_free(inrast); G_free(outrast); /* closing raster maps */ G_close_cell(infd); G_close_cell(outfd); /* add command line incantation to history file */ G_short_history(result, "raster", &history); G_command_history(&history); G_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; struct Range range; char *name; /* input raster name */ char *result; /* output raster name */ char *mapset; /* mapset name */ DCELL *inrast; /* input buffer */ DCELL *outrast; /* output buffer */ int row,col; int infd, outfd; /* file descriptor */ int verbose; double *weights; /* array of weights */ DCELL **D_rows; DCELL *tmp; int nrows; int ncols; double min, max; /* raster map range */ RASTER_MAP_TYPE data_type; /* type of the map */ void *values; /* neighborhood values */ int n,i; /* number of neighborhood cells */ int size; /* matrix size */ double ssigma; /* sigma of the spatial part */ double csigma; /* sigma of the color part */ char title[1024]; /* map title */ struct GModule *module; /* GRASS module for parsing arguments */ struct { struct Option *input, *output; struct Option *sigma_s, *sigma_c, *size; struct Option *title; } parm; struct { struct Flag *quiet; struct Flag *print_sigmas; } flag; /* initialize GIS environment */ G_gisinit(argv[0]); /* reads grass env, stores program name to G_program_name */ /* initialize module */ module = G_define_module(); module->description = ("Gaussian filter for raster maps."); /* Define the different options */ parm.input = G_define_option() ; parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->description= ("Name of an input layer" ); parm.output = G_define_option() ; parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = YES; parm.output->description= ("Name of an output layer"); parm.sigma_s = G_define_option() ; parm.sigma_s->key = "ssigma"; parm.sigma_s->type = TYPE_DOUBLE; parm.sigma_s->required = NO; parm.sigma_s->description= ("Sigma for space part of the filter\n\t(default: 0.465*((size-1)/2)"); parm.sigma_c = G_define_option() ; parm.sigma_c->key = "csigma"; parm.sigma_c->type = TYPE_DOUBLE; parm.sigma_c->required = NO; parm.sigma_c->description= ("Sigma for color part of the filter\n(default: 0.465*((color_range)/2)"); parm.size = G_define_option() ; parm.size->key = "size"; parm.size->type = TYPE_INTEGER; parm.size->required = YES; parm.size->description= ("Size of the matrix (odd number)"); flag.print_sigmas = G_define_flag() ; flag.print_sigmas->key = 's' ; flag.print_sigmas->description = "Print calculated values for sigmas" ; flag.quiet = G_define_flag() ; flag.quiet->key = 'q' ; flag.quiet->description = "Quiet" ; /* options and flags pareser */ if (G_parser(argc, argv)) exit (-1); /* stores options and flags to variables */ name = parm.input->answer; result = parm.output->answer; verbose = (! flag.quiet->answer); sscanf(parm.size->answer, "%d", &size); if (!parm.sigma_s->answer) ssigma = 0.465*((size-1)/2); else sscanf(parm.sigma_s->answer, "%lf", &ssigma); /* controlling the input values */ if (size%2 == 0) G_fatal_error("Size <%d> is not odd number", size); /* returs NULL if the map was not found in any mapset, * mapset name otherwise*/ mapset = G_find_cell2 (name, ""); if (mapset == NULL) G_fatal_error ("cell file [%s] not found", name); /* color sigma next */ if (!parm.sigma_c->answer) { if (G_read_range(name, mapset, &range) < 0) G_fatal_error("Could not read the raster map range"); /* for raster maps with range from 0-255 the result * should be around 60 */ min = (double)range.min; max = (double)range.max; csigma = 0.456*(max - min)/2; } else sscanf(parm.sigma_c->answer, "%lf", &csigma); /* print if appropriate */ if (flag.print_sigmas->answer) printf("Space sigma: %f\nColor sigma: %f\n", ssigma, csigma); if (G_legal_filename (result) < 0) G_fatal_error ("[%s] is an illegal name", result); /* count weights */ weights = (double *)malloc(size * size * sizeof(double)); /* stores values of gauss. bell into 'weigts'*/ count_weights(weights, size, ssigma); /* determine the inputmap type (CELL/FCELL/DCELL) */ data_type = G_raster_map_type(name, mapset); /* G_open_cell_old - returns file destriptor (>0) */ if ( (infd = G_open_cell_old (name, mapset)) < 0) G_fatal_error ("Cannot open cell file [%s]", name); /* controlling, if we can open input raster */ if (G_get_cellhd (name, mapset, &cellhd) < 0) G_fatal_error ("Cannot read file header of [%s]", name); /* Allocate input buffer */ inrast = G_allocate_raster_buf(data_type); /* Allocate output buffer, use input map data_type */ nrows = G_window_rows(); ncols = G_window_cols(); outrast = G_allocate_d_raster_buf(); /* Allocate values buffers */ values = (DCELL *) malloc(size * size * sizeof(DCELL)); /* allocating memory for rows */ D_rows = (DCELL **)malloc(size * sizeof(DCELL)); for (i = 0; i < size; i++) { D_rows[i] = G_allocate_raster_buf(DCELL_TYPE); } if (values == NULL) G_fatal_error("Cannot allocate memory"); /* controlling, if we can write the raster */ if ( (outfd = G_open_raster_new (result, data_type)) < 0) G_fatal_error ("Could not open <%s>",result); /* write first rows as NULL values */ for (row = 0; row < size/2; row++) { G_set_d_null_value(outrast, ncols); if (G_put_d_raster_row (outfd, outrast) < 0) G_fatal_error ("Cannot write to <%s>",result); } /* allocate first size/2 rows */ for (row = 0; row < size; row++) if (G_get_d_raster_row(infd, D_rows[row], row) < 0) G_fatal_error ("Could not open <%s>",result); /****************************************************************/ /* for each row inside the region */ for ( row = size/2; row < nrows - size/2; row++) { if (verbose) G_percent (row, nrows, 2); /* allocate new last row */ G_get_d_raster_row(infd, D_rows[size-1], row+(size/2)); /*process the data */ for (col=0; col < ncols; col++){ /* skip the outside columns */ if ( (col - size/2) < 0 || ncols <= (col + size/2)) { G_set_d_null_value(outrast, 1); } /* work only with columns, which are inside */ else { /* store values of the matrix into arry 'values', 'n' is * number of elements of the matrix */ n = D_gather(infd, values, D_rows, col, row,size); ((DCELL *)outrast)[col] = D_bilateral(values, ssigma, csigma, size, weights); } } /* for each column */ /* write raster row to output raster file */ G_put_d_raster_row (outfd, outrast); /* switch rows */ tmp = D_rows[0]; for (i = 0; i < size; i++){ D_rows[i] = D_rows[i + 1]; } D_rows[size-1] = tmp; } /* for each row */ /* write last rows as NULL values */ for (i = 0; i < size/2; i++) { G_set_d_null_value(outrast, ncols); G_put_d_raster_row (outfd, outrast); } /* memory cleaning */ G_free(outrast); G_free(inrast); G_free(values); for (i = 0; i < size; i++) { G_free(D_rows[i]); } free((void *) D_rows); /* closing rastr files */ G_close_cell (infd); G_close_cell (outfd); /* set the map title */ sprintf(title, "Bilateral filter of %s with %dx%d matrix: ssigma %.3f, csigma %.3f", name, size, size, ssigma, csigma ); G_put_cell_title (result, title ); return 0; }
int main( int argc, char **argv ) { char *mapset = 0; char *name = 0; struct GModule *module; struct Option *map; struct Option *win; struct Option *format; struct Cell_head window; RASTER_MAP_TYPE raster_type; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Output raster map layers in a format suitable for display in QGIS" ); map = G_define_standard_option( G_OPT_R_MAP ); map->description = ( "Raster map to be displayed" ); format = G_define_option(); format->key = "format"; format->type = TYPE_STRING; format->description = "format"; format->options = "color,value"; win = G_define_option(); win->key = "window"; win->type = TYPE_DOUBLE; win->multiple = YES; win->description = "xmin,ymin,xmax,ymax,ncols,nrows"; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); name = map->answer; /* Make sure map is available */ #if GRASS_VERSION_MAJOR < 7 mapset = G_find_cell2( name, "" ); if ( !mapset ) G_fatal_error( ( "Raster map <%s> not found" ), name ); #else mapset = ""; #endif /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and * cellhd, and G_open_cell_old fails, so it is better to read window from map */ /* G_get_window( &window ); */ G_get_cellhd( name, mapset, &window ); window.west = atof( win->answers[0] ); window.south = atof( win->answers[1] ); window.east = atof( win->answers[2] ); window.north = atof( win->answers[3] ); window.cols = atoi( win->answers[4] ); window.rows = atoi( win->answers[5] ); G_adjust_Cell_head( &window, 1, 1 ); G_set_window( &window ); G_suppress_masking(); // must be after G_set_window() raster_type = G_raster_map_type( name, "" ); display( name, mapset, raster_type, format->answer ); exit( EXIT_SUCCESS ); }
int main(int argc, char *argv[]) { char *name, *mapset; char rname[GNAME_MAX], rmapset[GMAPSET_MAX]; char path[GPATH_MAX]; int row, col, null_fd; unsigned char *null_bits; RASTER_MAP_TYPE map_type; int change_null = 0, create, remove, only_int, only_fp, only_null; int is_reclass; struct GModule *module; struct { struct Option *map; struct Option *setnull; struct Option *null; } parms; struct { struct Flag *f; struct Flag *n; struct Flag *i; struct Flag *c; struct Flag *r; } flags; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, null data"); module->description = _("Manages NULL-values of given raster map."); parms.map = G_define_standard_option(G_OPT_R_MAP); parms.map->description = _("Name of raster map for which to edit null file"); parms.setnull = G_define_option(); parms.setnull->key = "setnull"; parms.setnull->key_desc = "val[-val]"; parms.setnull->type = TYPE_STRING; parms.setnull->required = NO; parms.setnull->multiple = YES; parms.setnull->description = _("List of cell values to be set to NULL"); parms.setnull->guisection = _("Modify"); parms.null = G_define_option(); parms.null->key = "null"; parms.null->type = TYPE_DOUBLE; parms.null->required = NO; parms.null->multiple = NO; parms.null->description = _("The value to replace the null value by"); parms.null->guisection = _("Modify"); flags.f = G_define_flag(); flags.f->key = 'f'; flags.f->description = _("Only do the work if the map is floating-point"); flags.f->guisection = _("Check"); flags.i = G_define_flag(); flags.i->key = 'i'; flags.i->description = _("Only do the work if the map is integer"); flags.i->guisection = _("Check"); flags.n = G_define_flag(); flags.n->key = 'n'; flags.n->description = _("Only do the work if the map doesn't have a NULL-value bitmap file"); flags.n->guisection = _("Check"); flags.c = G_define_flag(); flags.c->key = 'c'; flags.c->description = _("Create NULL-value bitmap file validating all data cells"); flags.r = G_define_flag(); flags.r->key = 'r'; flags.r->description = _("Remove NULL-value bitmap file"); flags.r->guisection = _("Remove"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); only_int = flags.i->answer; only_fp = flags.f->answer; only_null = flags.n->answer; create = flags.c->answer; remove = flags.r->answer; name = parms.map->answer; mapset = G_find_cell2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), name); is_reclass = (G_is_reclass(name, mapset, rname, rmapset) > 0); if (is_reclass) G_fatal_error(_("Raster map <%s> is a reclass of map <%s@%s>. " "Consider to generate a copy with r.mapcalc. Exiting."), name, rname, rmapset); if (strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("Raster map <%s> is not in your mapset <%s>"), name, G_mapset()); if (parms.null->answer) { if (sscanf(parms.null->answer, "%lf", &new_null) == 1) change_null = 1; else G_fatal_error(_("%s is illegal entry for null"), parms.null->answer); } map_type = G_raster_map_type(name, mapset); if (only_null && G_find_file_misc("cell_misc", "null", name, mapset)) G_fatal_error(_("Raster map <%s> already has a null bitmap file"), name); if (map_type == CELL_TYPE) { if (only_fp) G_fatal_error(_("<%s> is integer raster map (CELL)"), name); if ((double)((int)new_null) != new_null) { G_warning(_("<%s> is integer raster map (CELL). Using null=%d."), name, (int)new_null); new_null = (double)((int)new_null); } } else if (only_int) G_fatal_error(_("<%s> is floating pointing raster map"), name); parse_vallist(parms.setnull->answers, &d_mask); if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error(_("Unable to read header of raster map <%s>"), G_fully_qualified_name(name, mapset)); if (create) { /* write a file of no-nulls */ null_bits = (unsigned char *)G__allocate_null_bits(cellhd.cols); /* init all cells to 0's */ for (col = 0; col < G__null_bitstream_size(cellhd.cols); col++) null_bits[col] = 0; null_fd = G_open_new_misc("cell_misc", "null", name); G_verbose_message(_("Writing new null file for raster map <%s>..."), name); for (row = 0; row < cellhd.rows; row++) { G_percent(row, cellhd.rows, 1); if (G__write_null_bits(null_fd, null_bits, row, cellhd.cols, 0) < 0) G_fatal_error(_("Error writing null row %d"), row); } G_percent(row, cellhd.rows, 1); close(null_fd); G_done_msg(_("Raster map <%s> modified."), name); exit(EXIT_SUCCESS); } if (remove) { /* write a file of no-nulls */ G_verbose_message(_("Removing null file for raster map <%s>..."), name); null_fd = G_open_new_misc("cell_misc", "null", name); G__file_name_misc(path, "cell_misc", "null", name, mapset); unlink(path); G_done_msg(_("Raster map <%s> modified."), name); exit(EXIT_SUCCESS); } process(name, mapset, change_null, map_type); exit(EXIT_SUCCESS); }
GDALDataset *GRASSDataset::Open( GDALOpenInfo * poOpenInfo ) { char *pszGisdb = NULL, *pszLoc = NULL; char *pszMapset = NULL, *pszElem = NULL, *pszName = NULL; char **papszCells = NULL; char **papszMapsets = NULL; /* -------------------------------------------------------------------- */ /* Does this even look like a grass file path? */ /* -------------------------------------------------------------------- */ if( strstr(poOpenInfo->pszFilename,"/cellhd/") == NULL && strstr(poOpenInfo->pszFilename,"/group/") == NULL ) return NULL; /* Always init, if no rasters are opened G_no_gisinit resets the projection and * rasters in different projection may be then opened */ // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only. G_set_gisrc_mode ( G_GISRC_MODE_MEMORY ); // Init GRASS libraries (required) G_no_gisinit(); // Doesn't check write permissions for mapset compare to G_gisinit // Set error function G_set_error_routine ( (GrassErrorHandler) Grass2CPLErrorHook ); // GISBASE is path to the directory where GRASS is installed, if ( !getenv( "GISBASE" ) ) { static char* gisbaseEnv = NULL; const char *gisbase = GRASS_GISBASE; CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE " "enviroment variable was not set, using:\n%s", gisbase ); char buf[2000]; snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase ); buf[sizeof(buf)-1] = '\0'; CPLFree(gisbaseEnv); gisbaseEnv = CPLStrdup ( buf ); putenv( gisbaseEnv ); } if ( !SplitPath( poOpenInfo->pszFilename, &pszGisdb, &pszLoc, &pszMapset, &pszElem, &pszName) ) { return NULL; } /* -------------------------------------------------------------------- */ /* Check element name */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") != 0 && strcmp(pszElem,"group") != 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } /* -------------------------------------------------------------------- */ /* Set GRASS variables */ /* -------------------------------------------------------------------- */ G__setenv( "GISDBASE", pszGisdb ); G__setenv( "LOCATION_NAME", pszLoc ); G__setenv( "MAPSET", pszMapset); // group is searched only in current mapset G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); /* -------------------------------------------------------------------- */ /* Check if this is a valid grass cell. */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") == 0 ) { if ( G_find_file2("cell", pszName, pszMapset) == NULL ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } papszMapsets = CSLAddString( papszMapsets, pszMapset ); papszCells = CSLAddString( papszCells, pszName ); } /* -------------------------------------------------------------------- */ /* Check if this is a valid GRASS imagery group. */ /* -------------------------------------------------------------------- */ else { struct Ref ref; I_init_group_ref( &ref ); if ( I_get_group_ref( pszName, &ref ) == 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } for( int iRef = 0; iRef < ref.nfiles; iRef++ ) { papszCells = CSLAddString( papszCells, ref.file[iRef].name ); papszMapsets = CSLAddString( papszMapsets, ref.file[iRef].mapset ); G_add_mapset_to_search_path ( ref.file[iRef].mapset ); } I_free_group_ref( &ref ); } G_free( pszMapset ); G_free( pszName ); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GRASSDataset *poDS; poDS = new GRASSDataset(); /* notdef: should only allow read access to an existing cell, right? */ poDS->eAccess = poOpenInfo->eAccess; poDS->pszGisdbase = pszGisdb; poDS->pszLocation = pszLoc; poDS->pszElement = pszElem; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ #if GRASS_VERSION_MAJOR >= 7 Rast_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ); #else if( G_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ) != 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster header"); delete poDS; return NULL; } #endif poDS->nRasterXSize = poDS->sCellInfo.cols; poDS->nRasterYSize = poDS->sCellInfo.rows; poDS->adfGeoTransform[0] = poDS->sCellInfo.west; poDS->adfGeoTransform[1] = poDS->sCellInfo.ew_res; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = poDS->sCellInfo.north; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -1 * poDS->sCellInfo.ns_res; /* -------------------------------------------------------------------- */ /* Try to get a projection definition. */ /* -------------------------------------------------------------------- */ struct Key_Value *projinfo, *projunits; projinfo = G_get_projinfo(); projunits = G_get_projunits(); poDS->pszProjection = GPJ_grass_to_wkt ( projinfo, projunits, 0, 0); if (projinfo) G_free_key_value(projinfo); if (projunits) G_free_key_value(projunits); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; papszCells[iBand] != NULL; iBand++ ) { GRASSRasterBand *rb = new GRASSRasterBand( poDS, iBand+1, papszMapsets[iBand], papszCells[iBand] ); if ( !rb->valid ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster band %d", iBand); delete rb; delete poDS; return NULL; } poDS->SetBand( iBand+1, rb ); } CSLDestroy(papszCells); CSLDestroy(papszMapsets); /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { delete poDS; CPLError( CE_Failure, CPLE_NotSupported, "The GRASS driver does not support update access to existing" " datasets.\n" ); return NULL; } return poDS; }
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; char *inmap; int infile, outfile; DCELL *outbuf; int row, col; struct Cell_head dst_w, src_w; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, 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"; 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 G_fatal_error(_("Invalid method: %s"), method->answer); G_get_set_window(&dst_w); inmap = G_find_cell2(rastin->answer, ""); if (!inmap) G_fatal_error(_("Raster map <%s> not found"), rastin->answer); /* set window to old map */ G_get_cellhd(rastin->answer, inmap, &src_w); /* enlarge source window */ { double north = G_row_to_northing(0.5, &dst_w); double south = G_row_to_northing(dst_w.rows - 0.5, &dst_w); int r0 = (int)floor(G_northing_to_row(north, &src_w) - 0.5) - 1; int r1 = (int)floor(G_northing_to_row(south, &src_w) - 0.5) + 3; double west = G_col_to_easting(0.5, &dst_w); double east = G_col_to_easting(dst_w.cols - 0.5, &dst_w); int c0 = (int)floor(G_easting_to_col(west, &src_w) - 0.5) - 1; int c1 = (int)floor(G_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; } G_set_window(&src_w); /* allocate buffers for input rows */ for (row = 0; row < neighbors; row++) bufs[row] = G_allocate_d_raster_buf(); cur_row = -100; /* open old map */ infile = G_open_cell_old(rastin->answer, inmap); if (infile < 0) G_fatal_error(_("Unable to open raster map <%s>"), rastin->answer); /* reset window to current region */ G_set_window(&dst_w); outbuf = G_allocate_d_raster_buf(); /* open new map */ outfile = G_open_raster_new(rastout->answer, DCELL_TYPE); if (outfile < 0) G_fatal_error(_("Unable to create raster map <%s>"), rastout->answer); G_suppress_warnings(1); /* otherwise get complaints about window changes */ switch (neighbors) { case 1: /* nearest */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f + 0.5); G_percent(row, dst_w.rows, 2); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f + 0.5); double c = bufs[0][mapcol0]; if (G_is_d_null_value(&c)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = c; } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; case 2: /* bilinear */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_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); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_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 (G_is_d_null_value(&c00) || G_is_d_null_value(&c01) || G_is_d_null_value(&c10) || G_is_d_null_value(&c11)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = G_interp_bilinear(u, v, c00, c01, c10, c11); } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; case 4: /* bicubic */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_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); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_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 (G_is_d_null_value(&c00) || G_is_d_null_value(&c01) || G_is_d_null_value(&c02) || G_is_d_null_value(&c03) || G_is_d_null_value(&c10) || G_is_d_null_value(&c11) || G_is_d_null_value(&c12) || G_is_d_null_value(&c13) || G_is_d_null_value(&c20) || G_is_d_null_value(&c21) || G_is_d_null_value(&c22) || G_is_d_null_value(&c23) || G_is_d_null_value(&c30) || G_is_d_null_value(&c31) || G_is_d_null_value(&c32) || G_is_d_null_value(&c33)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = G_interp_bicubic(u, v, c00, c01, c02, c03, c10, c11, c12, c13, c20, c21, c22, c23, c30, c31, c32, c33); } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; } G_percent(dst_w.rows, dst_w.rows, 2); G_close_cell(infile); G_close_cell(outfile); /* record map metadata/history info */ sprintf(title, "Resample by %s interpolation", method->answer); G_put_cell_title(rastout->answer, title); G_short_history(rastout->answer, "raster", &history); strncpy(history.datsrc_1, rastin->answer, RECORD_LEN); history.datsrc_1[RECORD_LEN - 1] = '\0'; /* strncpy() doesn't null terminate if maxfill */ G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); sprintf(history.datsrc_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); G_command_history(&history); G_write_history(rastout->answer, &history); /* copy color table from source map */ if (G_read_colors(rastin->answer, inmap, &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), rastin->answer); G_mark_colors_as_fp(&colors); if (G_write_colors(rastout->answer, G_mapset(), &colors) < 0) G_fatal_error(_("Unable to write color table for %s"), rastout->answer); return (EXIT_SUCCESS); }
GDALDataset *GRASSDataset::Open( GDALOpenInfo * poOpenInfo ) { static int bDoneGISInit = FALSE; char *pszMapset = NULL, *pszCell = NULL; char **papszCells = NULL; char **papszMapsets = NULL; if( !bDoneGISInit ) { G_set_error_routine( (GrassErrorHandler) Grass2CPLErrorHook ); G_gisinit_2( "GDAL", NULL, NULL, NULL ); } /* -------------------------------------------------------------------- */ /* Check if this is a valid grass cell. */ /* -------------------------------------------------------------------- */ if( G_check_cell( poOpenInfo->pszFilename, &pszMapset, &pszCell ) ) { papszCells = CSLAddString( papszCells, pszCell ); papszMapsets = CSLAddString( papszMapsets, pszMapset ); G_free( pszMapset ); G_free( pszCell ); } /* -------------------------------------------------------------------- */ /* Check if this is a valid GRASS imagery group. */ /* -------------------------------------------------------------------- */ else if( I_check_group( poOpenInfo->pszFilename, &pszMapset, &pszCell ) ) { struct Ref ref; I_init_group_ref( &ref ); I_get_group_ref( pszCell, &ref ); for( int iRef = 0; iRef < ref.nfiles; iRef++ ) { papszCells = CSLAddString( papszCells, ref.file[iRef].name ); papszMapsets = CSLAddString( papszMapsets, ref.file[iRef].mapset ); } I_free_group_ref( &ref ); G_free( pszMapset ); G_free( pszCell ); } else return NULL; /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GRASSDataset *poDS; poDS = new GRASSDataset(); /* notdef: should only allow read access to an existing cell, right? */ poDS->eAccess = poOpenInfo->eAccess; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ struct Cell_head sCellInfo; if( G_get_cellhd( papszCells[0], papszMapsets[0], &sCellInfo ) != 0 ) { /* notdef: report failure. */ return NULL; } poDS->nRasterXSize = sCellInfo.cols; poDS->nRasterYSize = sCellInfo.rows; G_set_window( &sCellInfo ); poDS->adfGeoTransform[0] = sCellInfo.west; poDS->adfGeoTransform[1] = sCellInfo.ew_res; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = sCellInfo.north; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -1 * sCellInfo.ns_res; /* -------------------------------------------------------------------- */ /* Try to get a projection definition. */ /* -------------------------------------------------------------------- */ char *pszProj4; pszProj4 = G_get_cell_as_proj4( papszCells[0], papszMapsets[0] ); if( pszProj4 != NULL ) { OGRSpatialReference oSRS; if( oSRS.importFromProj4( pszProj4 ) == OGRERR_NONE ) { oSRS.exportToWkt( &(poDS->pszProjection) ); } G_free( pszProj4 ); } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; papszCells[iBand] != NULL; iBand++ ) { poDS->SetBand( iBand+1, new GRASSRasterBand( poDS, iBand+1, papszMapsets[iBand], papszCells[iBand] ) ); } /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { delete poDS; CPLError( CE_Failure, CPLE_NotSupported, "The GRASS driver does not support update access to existing" " datasets.\n" ); return NULL; } return poDS; }
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand, const char * pszMapset, const char * pszCellName ) { struct Cell_head sCellInfo; this->poDS = poDS; this->nBand = nBand; G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo ); nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset ); /* -------------------------------------------------------------------- */ /* Get min/max values. */ /* -------------------------------------------------------------------- */ struct FPRange sRange; if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, &sRange ) == -1 ) { bHaveMinMax = FALSE; } else { bHaveMinMax = TRUE; G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax ); } /* -------------------------------------------------------------------- */ /* Setup band type, and preferred nodata value. */ /* -------------------------------------------------------------------- */ dfNoData = 0.0; if( nGRSType == CELL_TYPE && sCellInfo.format == 0 ) { if( bHaveMinMax && dfCellMin < 1.0 && dfCellMax > 254.0 ) { this->eDataType = GDT_UInt16; dfNoData = 256.0; } else { this->eDataType = GDT_Byte; if( dfCellMax < 255.0 ) dfNoData = 255.0; else dfNoData = 0.0; } } else if( nGRSType == CELL_TYPE && sCellInfo.format == 1 ) { this->eDataType = GDT_UInt16; dfNoData = 65535.0; } else if( nGRSType == CELL_TYPE ) { this->eDataType = GDT_UInt32; dfNoData = 65535.0; } else if( nGRSType == FCELL_TYPE ) { this->eDataType = GDT_Float32; dfNoData = -12345.0; } else if( nGRSType == DCELL_TYPE ) { this->eDataType = GDT_Float64; dfNoData = -12345.0; } nBlockXSize = poDS->nRasterXSize;; nBlockYSize = 1; hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset); /* -------------------------------------------------------------------- */ /* Do we have a color table? */ /* -------------------------------------------------------------------- */ struct Colors sGrassColors; poCT = NULL; if( G_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 ) { poCT = new GDALColorTable(); for( int iColor = 0; iColor < 256; iColor++ ) { int nRed, nGreen, nBlue; GDALColorEntry sColor; if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) { sColor.c1 = nRed; sColor.c2 = nGreen; sColor.c3 = nBlue; sColor.c4 = 255; poCT->SetColorEntry( iColor, &sColor ); } else { sColor.c1 = 0; sColor.c2 = 0; sColor.c3 = 0; sColor.c4 = 0; poCT->SetColorEntry( iColor, &sColor ); } } G_free_colors( &sGrassColors ); } }
void* raster2array(const char* name, struct Cell_head* header, int* rows, int* cols, RASTER_MAP_TYPE out_type) { // Open the raster map and load the dem // for simplicity sake, the dem will be an array of // doubles, converted from any possible GRASS CELL type. char* mapset = G_find_cell2(name, ""); if (mapset == NULL) G_fatal_error("Raster map <%s> not found", name); // Find out the cell type of the DEM RASTER_MAP_TYPE type = G_raster_map_type(name, mapset); // Get a file descriptor for the DEM raster map int infd; if ((infd = G_open_cell_old(name, mapset)) < 0) G_fatal_error("Unable to open raster map <%s>", name); // Get header info for the DEM raster map struct Cell_head cellhd; if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error("Unable to open raster map <%s>", name); // Create a GRASS buffer for the DEM raster void* inrast = G_allocate_raster_buf(type); // Get the max rows and max cols from the window information, since the // header gives the values for the full raster const int maxr = G_window_rows(); const int maxc = G_window_cols(); // Read in the raster line by line, copying it into the double array // rast for return. void* rast; switch (out_type) { case CELL_TYPE: rast = (int*) calloc(maxr * maxc, sizeof(int)); break; case FCELL_TYPE: rast = (float*) calloc(maxr * maxc, sizeof(float)); break; case DCELL_TYPE: rast = (double*) calloc(maxr * maxc, sizeof(double)); break; } if (rast == NULL) { G_fatal_error("Unable to allocate memory for raster map <%s>", name); } int row, col; for (row = 0; row < maxr; ++row) { if (G_get_raster_row(infd, inrast, row, type) < 0) G_fatal_error("Unable to read raster map <%s> row %d", name, row); for (col = 0; col < maxc; ++col) { int index = col + row * maxc; if (out_type == CELL_TYPE) { switch (type) { case CELL_TYPE: ((int*) rast)[index] = ((int *) inrast)[col]; break; case FCELL_TYPE: ((int*) rast)[index] = (int) ((float *) inrast)[col]; break; case DCELL_TYPE: ((int*) rast)[index] = (int) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == FCELL_TYPE) { switch (type) { case CELL_TYPE: ((float*) rast)[index] = (float) ((int *) inrast)[col]; break; case FCELL_TYPE: ((float*) rast)[index] = ((float *) inrast)[col]; break; case DCELL_TYPE: ((float*) rast)[index] = (float) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == DCELL_TYPE) { switch (type) { case CELL_TYPE: ((double*) rast)[index] = (double) ((int *) inrast)[col]; break; case FCELL_TYPE: ((double*) rast)[index] = (double) ((float *) inrast)[col]; break; case DCELL_TYPE: ((double*) rast)[index] = ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } } } // Return cellhd, maxr, and maxc by pointer if (header != NULL) *header = cellhd; if (rows != NULL) *rows = maxr; if (cols != NULL) *cols = maxc; return rast; }
int main(int argc, char *argv[]) { /* Global variable & function declarations */ char Cellmap_orig[50]; FILE *realfp, *imagfp; /* the input and output file descriptors */ int outputfd, maskfd; /* the input and output file descriptors */ char *realmapset, *imagmapset; /* the input mapset names */ struct Cell_head orig_wind, realhead; CELL *cell_row, *maskbuf = NULL; int i, j; /* Loop control variables */ int or, oc; /* Original dimensions of image */ int rows, cols; /* Smallest powers of 2 >= number of rows & columns */ long totsize; /* Total number of data points */ int halfrows, halfcols; double *data[2]; /* Data structure containing real & complex values of FFT */ struct Option *op1, *op2, *op3; struct GModule *module; G_gisinit(argv[0]); /* Set description */ module = G_define_module(); module->keywords = _("imagery, FFT"); module->description = _("Inverse Fast Fourier Transform (IFFT) for image processing."); /* define options */ op1 = G_define_standard_option(G_OPT_R_INPUT); op1->key = "real_image"; op1->description = _("Name of input raster map (image fft, real part)"); op2 = G_define_standard_option(G_OPT_R_INPUT); op2->key = "imaginary_image"; op2->description = _("Name of input raster map (image fft, imaginary part"); op3 = G_define_standard_option(G_OPT_R_OUTPUT); op3->key = "output_image"; op3->description = _("Name for output raster map"); /*call parser */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); strcpy(Cellmap_real, op1->answer); strcpy(Cellmap_imag, op2->answer); strcpy(Cellmap_orig, op3->answer); /* open input raster map */ if ((realmapset = G_find_cell(Cellmap_real, "")) == NULL) G_fatal_error(_("Raster map <%s> not found"), Cellmap_real); if ((realfp = G_fopen_old_misc("cell_misc", "fftreal", Cellmap_real, realmapset)) == NULL) G_fatal_error(_("Unable to open real-image in the 'cell_misc' directory. " "Raster map probably wasn't created by i.fft")); if ((imagmapset = G_find_cell(Cellmap_imag, "")) == NULL) G_fatal_error(_("Raster map <%s> not found"), Cellmap_imag); if ((imagfp = G_fopen_old_misc("cell_misc", "fftimag", Cellmap_imag, imagmapset)) == NULL) G_fatal_error(_("Unable to open imaginary-image in the 'cell_misc' directory. " "Raster map probably wasn't created by i.fft")); /* check command line args for validity */ if (G_legal_filename(Cellmap_orig) < 0) G_fatal_error(_("<%s> is an illegal file name"), Cellmap_orig); /* get and compare the original window data */ get_orig_window(&orig_wind, realmapset, imagmapset); or = orig_wind.rows; oc = orig_wind.cols; G_get_cellhd(Cellmap_real, realmapset, &realhead); G_set_window(&realhead); /* set the window to the whole cell map */ /* get the rows and columns in the current window */ rows = G_window_rows(); cols = G_window_cols(); totsize = rows * cols; halfrows = rows / 2; halfcols = cols / 2; G_verbose_message(_("Power 2 values: %d rows %d columns"), rows, cols); /* Allocate appropriate memory for the structure containing the real and complex components of the FFT. DATA[0] will contain the real, and DATA[1] the complex component. */ data[0] = (double *)G_malloc((rows * cols) * sizeof(double)); data[1] = (double *)G_malloc((rows * cols) * sizeof(double)); /* Initialize real & complex components to zero */ G_message(_("Reading raster maps...")); { fread((char *)data[0], sizeof(double), totsize, realfp); fread((char *)data[1], sizeof(double), totsize, imagfp); } /* Read in cell map values */ G_message(_("Masking raster maps...")); maskfd = G_maskfd(); if (maskfd >= 0) maskbuf = G_allocate_cell_buf(); if (maskfd >= 0) { for (i = 0; i < rows; i++) { double *data0, *data1; data0 = data[0] + i * cols; data1 = data[1] + i * cols; G_get_map_row(maskfd, maskbuf, i); for (j = 0; j < cols; j++, data0++, data1++) { if (maskbuf[j] == (CELL) 0) { *(data0) = 0.0; *(data1) = 0.0; } } } } G_message(_("Rotating data...")); /* rotate the data array for standard display */ for (i = 0; i < rows; i++) { double temp; for (j = 0; j < halfcols; j++) { temp = *(data[0] + i * cols + j); *(data[0] + i * cols + j) = *(data[0] + i * cols + j + halfcols); *(data[0] + i * cols + j + halfcols) = temp; temp = *(data[1] + i * cols + j); *(data[1] + i * cols + j) = *(data[1] + i * cols + j + halfcols); *(data[1] + i * cols + j + halfcols) = temp; } } for (i = 0; i < halfrows; i++) { double temp; for (j = 0; j < cols; j++) { temp = *(data[0] + i * cols + j); *(data[0] + i * cols + j) = *(data[0] + (i + halfrows) * cols + j); *(data[0] + (i + halfrows) * cols + j) = temp; temp = *(data[1] + i * cols + j); *(data[1] + i * cols + j) = *(data[1] + (i + halfrows) * cols + j); *(data[1] + (i + halfrows) * cols + j) = temp; } } /* close input cell maps and release the row buffers */ fclose(realfp); fclose(imagfp); if (maskfd >= 0) { G_close_cell(maskfd); G_free(maskbuf); } /* perform inverse FFT */ G_message(_("Starting Inverse FFT...")); fft(1, data, totsize, cols, rows); /* set up a window for the transform cell map */ G_set_window(&orig_wind); /* open the output cell map and allocate a cell row buffer */ if ((outputfd = G_open_cell_new(Cellmap_orig)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), Cellmap_orig); cell_row = G_allocate_cell_buf(); /* Write out result to a new cell map */ G_message(_("Writing data...")); for (i = 0; i < or; i++) { for (j = 0; j < oc; j++) { *(cell_row + j) = (CELL) (*(data[0] + i * cols + j) + 0.5); } G_put_raster_row(outputfd, cell_row, CELL_TYPE); G_percent(i+1, or, 2); } G_close_cell(outputfd); G_free(cell_row); { struct Colors colors; struct Range range; CELL min, max; /* make a real component color table */ G_read_range(Cellmap_orig, G_mapset(), &range); G_get_range_min_max(&range, &min, &max); G_make_grey_scale_colors(&colors, min, max); G_write_colors(Cellmap_orig, G_mapset(), &colors); } /* Release memory resources */ G_free(data[0]); G_free(data[1]); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main( int argc, char **argv ) { struct GModule *module; struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Get info about locations,mapsets,maps" ); info_opt = G_define_option(); info_opt->key = "info"; info_opt->type = TYPE_STRING; info_opt->description = "info key"; info_opt->options = "proj,window,query"; rast_opt = G_define_standard_option( G_OPT_R_INPUT ); rast_opt->key = "rast"; rast_opt->required = NO; vect_opt = G_define_standard_option( G_OPT_V_INPUT ); vect_opt->key = "vect"; vect_opt->required = NO; coor_opt = G_define_option(); coor_opt->key = "coor"; coor_opt->type = TYPE_DOUBLE; coor_opt->multiple = YES; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); if ( strcmp( "proj", info_opt->answer ) == 0 ) { G_get_window( &window ); /* code from g.proj */ if ( window.proj != PROJECTION_XY ) { struct Key_Value *projinfo, *projunits; char *wkt; projinfo = G_get_projinfo(); projunits = G_get_projunits(); wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 ); fprintf( stdout, "%s", wkt ); } } else if ( strcmp( "window", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } else if ( strcmp( "query", info_opt->answer ) == 0 ) { double x, y; int row, col; x = atof( coor_opt->answers[0] ); y = atof( coor_opt->answers[1] ); if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; G_get_cellhd( rast_opt->answer, "", &window ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); col = ( int ) G_easting_to_col( x, &window ); row = ( int ) G_northing_to_row( y, &window ); if ( col == window.cols ) col--; if ( row == window.rows ) row--; if ( col < 0 || col > window.cols || row < 0 || row > window.rows ) { fprintf( stdout, "value:null\n" ); } else { void *ptr; double val; #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = cell[col]; ptr = &( cell[col] ); } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = dcell[col]; ptr = &( dcell[col] ); } if ( G_is_null_value( ptr, rast_type ) ) { fprintf( stdout, "value:null\n" ); } else { fprintf( stdout, "value:%f\n", val ); } } G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } exit( EXIT_SUCCESS ); }
int main(int argc, char *argv[]) { char mapset[GMAPSET_MAX]; char name[GNAME_MAX]; char *camera; struct GModule *module; struct Option *group_opt, *map_opt, *target_map_opt; struct Cell_head cellhd; int ok; int nfiles; /* must run in a term window */ G_putenv("GRASS_UI_TERM", "1"); G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("imagery, orthorectify"); module->description = _("Creates control points on an image " "to be ortho-rectified."); group_opt = G_define_option(); group_opt->key = "group"; group_opt->type = TYPE_STRING; group_opt->required = YES; group_opt->multiple = NO; group_opt->description = _("Name of imagery group"); map_opt = G_define_standard_option(G_OPT_R_MAP); map_opt->required = NO; map_opt->description = _("Name of image to be rectified which will " "be initially drawn on screen"); target_map_opt = G_define_standard_option(G_OPT_R_MAP); target_map_opt->key = "target"; target_map_opt->required = NO; target_map_opt->description = _("Name of a map from target mapset which " "will be initially drawn on screen"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_suppress_masking(); /* need to do this for target location */ camera = (char *)G_malloc(40 * sizeof(char)); strcpy(name, group_opt->answer); interrupt_char = G_intr_char(); tempfile1 = G_tempfile(); tempfile2 = G_tempfile(); tempfile_dot = G_tempfile(); tempfile_dot2 = G_tempfile(); tempfile_win = G_tempfile(); tempfile_win2 = G_tempfile(); cell_list = G_tempfile(); vect_list = G_tempfile(); group_list = G_tempfile(); digit_points = G_tempfile(); if (R_open_driver() != 0) G_fatal_error(_("No graphics device selected")); /* get group ref */ strcpy(group.name, name); if (!I_find_group(group.name)) G_fatal_error(_("Group [%s] not found"), group.name); /* get the group ref */ I_get_group_ref(group.name, &group.group_ref); nfiles = group.group_ref.nfiles; /* write block files to block list file */ prepare_group_list(); /** look for camera info for this group**/ G_suppress_warnings(1); if (!I_get_group_camera(group.name, camera)) G_fatal_error(_("No camera reference file selected for group [%s]"), group.name); if (!I_get_cam_info(camera, &group.camera_ref)) G_fatal_error(_("Bad format in camera file for group [%s]"), group.name); G_suppress_warnings(0); /* get initial camera exposure station, if any */ if (!(ok = I_find_initial(group.name))) G_warning(_("No initial camera exposure station for group [%s]"), group.name); if (ok && (!I_get_init_info(group.name, &group.camera_exp)) ) G_warning(_("Bad format in initial camera exposure station for group [%s]"), group.name); /* get target info and environment */ G_suppress_warnings(1); get_target(); find_target_files(); G_suppress_warnings(0); /* read group reference points, if any */ G_suppress_warnings(1); if (!I_get_ref_points(group.name, &group.photo_points)) { G_suppress_warnings(0); if (group.photo_points.count == 0) G_fatal_error(_("No photo points for group [%s]"), group.name); else if (group.ref_equation_stat == 0) G_fatal_error(_("Poorly placed photo points for group [%s]"), group.name); } G_suppress_warnings(0); /* determine transformation equation */ Compute_ref_equation(); /* read group control points, format: image x,y,cfl; target E,N,Z */ G_suppress_warnings(1); if (!I_get_con_points(group.name, &group.control_points)) group.control_points.count = 0; G_suppress_warnings(0); /* compute image coordinates of photo control points */ /******** I_convert_con_points (group.name, &group.control_points, &group.control_points, group.E12, group.N12); ********/ /* determine transformation equation */ G_message(_("Computing equations ...")); if (group.control_points.count > 0) Compute_ortho_equation(); /* signal (SIGINT, SIG_IGN); */ /* signal (SIGQUIT, SIG_IGN); */ select_current_env(); Init_graphics(); display_title(VIEW_MAP1); select_target_env(); display_title(VIEW_MAP2); select_current_env(); Begin_curses(); G_set_error_routine(error); /* #ifdef SIGTSTP signal (SIGTSTP, SIG_IGN); #endif */ /* Set image to be rectified */ if (map_opt->answer) { char *ms; ms = G_find_cell(map_opt->answer, ""); if (ms == NULL) { G_fatal_error(_("Raster map <%s> not found"), map_opt->answer); } strcpy(name, map_opt->answer); strcpy(mapset, ms); if (G_get_cellhd(name, mapset, &cellhd) < 0) { G_fatal_error(_("Unable to read raster header of <%s>"), map_opt->answer); } } else { /* ask user for group file to be displayed */ do { if (!choose_groupfile(name, mapset)) quit(EXIT_SUCCESS); /* display this file in "map1" */ } while (G_get_cellhd(name, mapset, &cellhd) < 0); } G_adjust_window_to_box(&cellhd, &VIEW_MAP1->cell.head, VIEW_MAP1->nrows, VIEW_MAP1->ncols); Configure_view(VIEW_MAP1, name, mapset, cellhd.ns_res, cellhd.ew_res); drawcell(VIEW_MAP1); /* Set target map if specified */ if (target_map_opt->answer) { char *ms; select_target_env(); ms = G_find_cell(target_map_opt->answer, ""); if (ms == NULL) { G_fatal_error(_("Raster map <%s> not found"), target_map_opt->answer); } strcpy(name, target_map_opt->answer); strcpy(mapset, ms); if (G_get_cellhd(name, mapset, &cellhd) < 0) { G_fatal_error(_("Unable to read raster header of <%s>"), target_map_opt->answer); } G_adjust_window_to_box(&cellhd, &VIEW_MAP2->cell.head, VIEW_MAP2->nrows, VIEW_MAP2->ncols); Configure_view(VIEW_MAP2, name, mapset, cellhd.ns_res, cellhd.ew_res); drawcell(VIEW_MAP2); from_flag = 1; from_keyboard = 0; from_screen = 1; } display_conz_points(1); Curses_clear_window(PROMPT_WINDOW); /* determine initial input method. */ setup_digitizer(); if (use_digitizer) { from_digitizer = 1; from_keyboard = 0; from_flag = 1; } /* go do the work */ driver(); quit(EXIT_SUCCESS); }