void G3d_setNullValue(void *c, int nofElts, int type) { if (type == FCELL_TYPE) { G_set_f_null_value((float *)c, nofElts); return; } G_set_d_null_value((double *)c, nofElts); }
/************************************************************** * apply_filter: apply the filter to a single neighborhood * * filter: filter to be applied * input: input buffers **************************************************************/ DCELL apply_filter(FILTER * filter, DCELL ** input) { int size = filter->size; double **matrix = filter->matrix; double divisor = filter->divisor; int r, c; DCELL v; v = 0; if (divisor == 0) { int have_result = 0; for (r = 0; r < size; r++) for (c = 0; c < size; c++) { if (G_is_d_null_value(&input[r][c])) continue; v += input[r][c] * matrix[r][c]; divisor += filter->dmatrix[r][c]; have_result = 1; } if (have_result) v /= divisor; else G_set_d_null_value(&v, 1); } else { for (r = 0; r < size; r++) for (c = 0; c < size; c++) { if (G_is_d_null_value(&input[r][c])) { G_set_d_null_value(&v, 1); return v; } v += input[r][c] * matrix[r][c]; } v /= divisor; } return v; }
int extract_areas(void) { double nullVal; row = col = top = 0; /* get started for read of first */ bottom = 1; /* line from raster map */ area_num = 0; tl_area = 0; G_set_d_null_value(&nullVal, 1); /* represents the "outside", the external null values */ assign_area(nullVal, 0); G_message(_("Extracting areas...")); scan_length = read_next(); while (read_next()) { /* read rest of file, one row at *//* a time */ G_percent(row, n_rows, 2); for (col = 0; col < scan_length - 1; col++) { tl = get_raster_value(buffer[top], col); /* top left in window */ tr = get_raster_value(buffer[top], col + 1); /* top right */ bl = get_raster_value(buffer[bottom], col); /* bottom left */ br = get_raster_value(buffer[bottom], col + 1); /* bottom right */ update_list(nabors()); } if (h_ptr != NULPTR) /* if we have a loose end, */ end_hline(); /* tie it down */ row++; } G_percent(row, n_rows, 2); write_area(a_list, e_list, area_num, n_equiv); G_free(a_list); G_free(e_list); return 0; } /* extract_areas */
void w_skew(DCELL * result, DCELL(*values)[2], int n, const void *closure) { DCELL sum, ave, sumsq, sumcb, sdev; int count; int i; sum = 0.0; count = 0; for (i = 0; i < n; i++) { if (G_is_d_null_value(&values[i][0])) continue; sum += values[i][0] * values[i][1]; count += values[i][1]; } if (count == 0) { G_set_d_null_value(result, 1); return; } ave = sum / count; sumsq = 0; for (i = 0; i < n; i++) { DCELL d; if (G_is_d_null_value(&values[i][0])) continue; d = values[i][0] - ave; sumsq += d * d * values[i][1]; sumcb += d * d * d * values[i][1]; } sdev = sqrt(sumsq / count); *result = sumcb / (count * sdev * sdev * sdev); }
void w_kurt(DCELL * result, DCELL(*values)[2], int n, const void *closure) { DCELL sum, ave, sumsq, sumqt, var; int count; int i; sum = 0.0; count = 0; for (i = 0; i < n; i++) { if (G_is_d_null_value(&values[i][0])) continue; sum += values[i][0] * values[i][1]; count += values[i][1]; } if (count == 0) { G_set_d_null_value(result, 1); return; } ave = sum / count; sumsq = 0; for (i = 0; i < n; i++) { DCELL d; if (G_is_d_null_value(&values[i][0])) continue; d = values[i][0] - ave; sumsq += d * d * values[i][1]; sumqt += d * d * d * values[i][1]; } var = sumsq / count; *result = sumqt / (count * var * var) - 3; }
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 QgsGrassGisLib::readRasterRow( int fd, void * buf, int row, RASTER_MAP_TYPE data_type, bool noDataAsZero ) { if ( row < 0 || row >= mRows ) { QgsDebugMsg( QString( "row %1 out of range 0 - %2" ).arg( row ).arg( mRows ) ); return 0; } // TODO: use cached block with more rows Raster raster = mRasters.value( fd ); //if ( !raster.provider ) return -1; if ( !raster.input ) return -1; // Create extent for current row QgsRectangle blockRect = mExtent; double yRes = mExtent.height() / mRows; double yMax = mExtent.yMaximum() - yRes * row; //QgsDebugMsg( QString( "height = %1 mRows = %2" ).arg( mExtent.height() ).arg( mRows ) ); //QgsDebugMsg( QString( "row = %1 yRes = %2 yRes * row = %3" ).arg( row ).arg( yRes ).arg( yRes * row ) ); //QgsDebugMsg( QString( "mExtent.yMaximum() = %1 yMax = %2" ).arg( mExtent.yMaximum() ).arg( yMax ) ); blockRect.setYMaximum( yMax ); blockRect.setYMinimum( yMax - yRes ); QgsRasterBlock *block = raster.input->block( raster.band, blockRect, mColumns, 1 ); if ( !block ) return -1; QGis::DataType requestedType = qgisRasterType( data_type ); //QgsDebugMsg( QString("data_type = %1").arg(data_type) ); //QgsDebugMsg( QString("requestedType = %1").arg(requestedType) ); //QgsDebugMsg( QString("requestedType size = %1").arg( QgsRasterBlock::typeSize( requestedType ) ) ); //QgsDebugMsg( QString("block->dataType = %1").arg( block->dataType() ) ); block->convert( requestedType ); memcpy( buf, block->bits( 0 ), QgsRasterBlock::typeSize( requestedType ) * mColumns ); for ( int i = 0; i < mColumns; i++ ) { QgsDebugMsgLevel( QString( "row = %1 i = %2 val = %3 isNoData = %4" ).arg( row ).arg( i ).arg( block->value( i ) ).arg( block->isNoData( i ) ), 5 ); //(( CELL * ) buf )[i] = i; if ( block->isNoData( 0, i ) ) { if ( noDataAsZero ) { switch ( data_type ) { case CELL_TYPE: G_zero(( char * ) &(( CELL * ) buf )[i], G_raster_size( data_type ) ); break; case FCELL_TYPE: G_zero(( char * ) &(( FCELL * ) buf )[i], G_raster_size( data_type ) ); break; case DCELL_TYPE: G_zero(( char * ) &(( DCELL * ) buf )[i], G_raster_size( data_type ) ); break; default: break; } } else { switch ( data_type ) { case CELL_TYPE: G_set_c_null_value( &(( CELL * ) buf )[i], 1 ); break; case FCELL_TYPE: G_set_f_null_value( &(( FCELL * ) buf )[i], 1 ); break; case DCELL_TYPE: G_set_d_null_value( &(( DCELL * ) buf )[i], 1 ); break; default: break; } } } //else //{ //memcpy( &( buf[i] ), block->bits( 0, i ), 4 ); //buf[i] = (int) block->value( 0, i); //QgsDebugMsg( QString("buf[i] = %1").arg(buf[i])); //} } delete block; return 1; }
int find_con(int r, int c, double *d1, double *d2, DCELL * con1, DCELL * con2) { int ct, low_ct, node_ct; int rr, cc, dor, doc; double dd, shortest; DCELL value; G_set_d_null_value(con1, 1); G_set_d_null_value(con2, 1); *d1 = *d2 = 1.0; shortest = nrows * ncols; for (rr = minr; rr <= maxr; rr++) { for (cc = minc; cc <= maxc; cc++) FLAG_UNSET(seen, rr, cc); } minr = nrows; minc = ncols; maxr = maxc = -1; FLAG_SET(seen, r, c); if (r < minr) minr = r; if (r > maxr) maxr = r; if (c < minc) minc = c; if (c > maxc) maxc = c; node_ct = 0; zero = addpts(zero, r, c, r, c, &node_ct); low_ct = 0; while (1) { ct = low_ct++; if (node_ct <= ct) return 1; rr = zero[ct].r; cc = zero[ct].c; dor = ABS(rr - r); doc = ABS(cc - c); if (rr >= 0 && cc >= 0 && rr < nrows && cc < ncols && zero[ct].d < shortest && !flag_get(mask, rr, cc)) { dseg_get(&con, rr, cc, &value); if (G_is_d_null_value(&value)) zero = addpts(zero, r, c, rr, cc, &node_ct); else if (G_is_d_null_value(con1)) { *con1 = value; *d1 = MIN(dor, doc) * 1.414 + ABS(dor - doc); shortest = *d1 * 2.0 * i_val_l_f; } else if (*con1 == value) { dd = MIN(dor, doc) * 1.414 + ABS(dor - doc); if (dd < *d1) { *d1 = dd; shortest = dd * 2.0 * i_val_l_f; } } else if (G_is_d_null_value(con2)) { *con2 = value; *d2 = MIN(dor, doc) * 1.414 + ABS(dor - doc); shortest = *d2; } else { dd = MIN(dor, doc) * 1.414 + ABS(dor - doc); shortest = MIN(shortest, dd); } } } return 0; }
int main(int argc, char *argv[]) { char *input; char *output; char *title; FILE *fd; int cf; struct Cell_head cellhd; CELL *cell; FCELL *fcell; DCELL *dcell; int row, col; int nrows, ncols; static int missingval; int rtype; double mult_fact; double x; struct GModule *module; struct History history; struct { struct Option *input, *output, *type, *title, *mult; } parm; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, import"); module->description = _("Converts an ESRI ARC/INFO ascii raster file (GRID) " "into a (binary) raster map layer."); parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->description = _("ARC/INFO ASCII raster file (GRID) to be imported"); parm.input->gisprompt = "old_file,file,input"; parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.type = G_define_option(); parm.type->key = "type"; parm.type->type = TYPE_STRING; parm.type->required = NO; parm.type->options = "CELL,FCELL,DCELL"; parm.type->answer = "FCELL"; parm.type->description = _("Storage type for resultant raster map"); 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 for resultant raster map"); parm.mult = G_define_option(); parm.mult->key = "mult"; parm.mult->type = TYPE_DOUBLE; parm.mult->answer = "1.0"; parm.mult->required = NO; parm.mult->description = _("Multiplier for ASCII data"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); input = parm.input->answer; output = parm.output->answer; if (title = parm.title->answer) G_strip(title); sscanf(parm.mult->answer, "%lf", &mult_fact); if (strcmp("CELL", parm.type->answer) == 0) rtype = CELL_TYPE; else if (strcmp("DCELL", parm.type->answer) == 0) rtype = DCELL_TYPE; else rtype = FCELL_TYPE; if (strcmp("-", input) == 0) { Tmp_file = G_tempfile(); if (NULL == (Tmp_fd = fopen(Tmp_file, "w+"))) G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file); unlink(Tmp_file); if (0 > file_cpy(stdin, Tmp_fd)) exit(EXIT_FAILURE); fd = Tmp_fd; } else fd = fopen(input, "r"); if (fd == NULL) G_fatal_error(_("Unable to open input file <%s>"), input); if (!gethead(fd, &cellhd, &missingval)) G_fatal_error(_("Can't get cell header")); nrows = cellhd.rows; ncols = cellhd.cols; if (G_set_window(&cellhd) < 0) G_fatal_error(_("Can't set window")); if (nrows != G_window_rows()) G_fatal_error(_("OOPS: rows changed from %d to %d"), nrows, G_window_rows()); if (ncols != G_window_cols()) G_fatal_error(_("OOPS: cols changed from %d to %d"), ncols, G_window_cols()); switch (rtype) { case CELL_TYPE: cell = G_allocate_c_raster_buf(); break; case FCELL_TYPE: fcell = G_allocate_f_raster_buf(); break; case DCELL_TYPE: dcell = G_allocate_d_raster_buf(); break; } cf = G_open_raster_new(output, rtype); if (cf < 0) G_fatal_error(_("Unable to create raster map <%s>"), output); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 5); for (col = 0; col < ncols; col++) { if (fscanf(fd, "%lf", &x) != 1) { G_unopen_cell(cf); G_fatal_error(_("Data conversion failed at row %d, col %d"), row + 1, col + 1); } switch (rtype) { case CELL_TYPE: if ((int)x == missingval) G_set_c_null_value(cell + col, 1); else cell[col] = (CELL) x *mult_fact; break; case FCELL_TYPE: if ((int)x == missingval) G_set_f_null_value(fcell + col, 1); else fcell[col] = (FCELL) x *mult_fact; break; case DCELL_TYPE: if ((int)x == missingval) G_set_d_null_value(dcell + col, 1); else dcell[col] = (DCELL) x *mult_fact; break; } } switch (rtype) { case CELL_TYPE: G_put_c_raster_row(cf, cell); break; case FCELL_TYPE: G_put_f_raster_row(cf, fcell); break; case DCELL_TYPE: G_put_d_raster_row(cf, dcell); break; } } /* G_message(_("CREATING SUPPORT FILES FOR %s"), output); */ G_close_cell(cf); if (title) G_put_cell_title(output, title); G_short_history(output, "raster", &history); G_command_history(&history); G_write_history(output, &history); exit(EXIT_SUCCESS); }
int calculateD(int fd, area_des ad, double *result) { DCELL *buf; DCELL *buf_sup; DCELL corrCell; DCELL precCell; DCELL supCell; int i, j; int mask_fd = -1, *mask_buf; int ris = 0; int masked = FALSE; int areaPatch = 0; /*if all cells are null areaPatch=0 */ long npatch = 0; long tot = 0; long zero = 0; long totCorr = 0; long idCorr = 0; long lastId = 0; long doppi = 0; long np = 0; long *mask_patch_sup; long *mask_patch_corr; double indice = 0; double somma = 0; double area = 0; double mn = 0; double sd = 0; double cv = 0; avlID_tree albero = NULL; avlID_table *array = NULL; generic_cell gc; gc.t = DCELL_TYPE; /* open mask if needed */ if (ad->mask == 1) { if ((mask_fd = open(ad->mask_name, O_RDONLY, 0755)) < 0) return RLI_ERRORE; mask_buf = G_malloc(ad->cl * sizeof(int)); if (mask_buf == NULL) { G_fatal_error("malloc mask_buf failed"); return RLI_ERRORE; } masked = TRUE; } mask_patch_sup = G_malloc(ad->cl * sizeof(long)); if (mask_patch_sup == NULL) { G_fatal_error("malloc mask_patch_sup failed"); return RLI_ERRORE; } mask_patch_corr = G_malloc(ad->cl * sizeof(long)); if (mask_patch_corr == NULL) { G_fatal_error("malloc mask_patch_corr failed"); return RLI_ERRORE; } buf_sup = G_allocate_d_raster_buf(); if (buf_sup == NULL) { G_fatal_error("malloc buf_sup failed"); return RLI_ERRORE; } buf = G_allocate_d_raster_buf(); if (buf == NULL) { G_fatal_error("malloc buf failed"); return RLI_ERRORE; } G_set_d_null_value(buf_sup + ad->x, ad->cl); /*the first time buf_sup is all null */ for (i = 0; i < ad->cl; i++) { mask_patch_sup[i] = 0; mask_patch_corr[i] = 0; } for (j = 0; j < ad->rl; j++) /*for each raster row */ { if (j > 0) { buf_sup = RLI_get_dcell_raster_row(fd, j - 1 + ad->y, ad); } buf = RLI_get_dcell_raster_row(fd, j + ad->y, ad); if (masked) { if (read(mask_fd, mask_buf, (ad->cl * sizeof(int))) < 0) { G_fatal_error("mask read failed"); return RLI_ERRORE; } } G_set_d_null_value(&precCell, 1); for (i = 0; i < ad->cl; i++) { /* for each dcell in the row */ area++; corrCell = buf[i + ad->x]; if (masked && mask_buf[i + ad->x] == 0) { G_set_d_null_value(&corrCell, 1); area--; } if (!(G_is_null_value(&corrCell, gc.t))) { areaPatch++; if (i > 0) precCell = buf[i - 1 + ad->x]; if (j == 0) G_set_d_null_value(&supCell, 1); else supCell = buf_sup[i + ad->x]; if (corrCell != precCell) /* ? * 1 2 * */ { if (corrCell != supCell) { /* 3 * 1 2 * */ /*new patch */ if (idCorr == 0) { /*first patch */ lastId = 1; idCorr = 1; totCorr = 1; mask_patch_corr[i] = idCorr; } else /*not first patch */ /* put in the tree the previous value */ { if (albero == NULL) { albero = avlID_make(idCorr, totCorr); if (albero == NULL) { G_fatal_error("avlID_make error"); return RLI_ERRORE; } npatch++; } else /*tree not empty */ { ris = avlID_add(&albero, idCorr, totCorr); switch (ris) { case AVL_ERR: { G_fatal_error("avlID_add error"); return RLI_ERRORE; } case AVL_ADD: { npatch++; break; } case AVL_PRES: { break; } default: { G_fatal_error ("avlID_add unknown error"); return RLI_ERRORE; } } } totCorr = 1; lastId++; idCorr = lastId; mask_patch_corr[i] = idCorr; } } else /*current cell and upper cell are equal */ /* 2 * 1 2 * */ { if (albero == NULL) { albero = avlID_make(idCorr, totCorr); if (albero == NULL) { G_fatal_error("avlID_make error"); return RLI_ERRORE; } npatch++; } else { /*tree not null */ ris = avlID_add(&albero, idCorr, totCorr); switch (ris) { case AVL_ERR: { G_fatal_error("avlID_add error"); return RLI_ERRORE; } case AVL_ADD: { npatch++; break; } case AVL_PRES: { break; } default: { G_fatal_error("avlID_add unknown error"); return RLI_ERRORE; } } } idCorr = mask_patch_sup[i]; mask_patch_corr[i] = idCorr; totCorr = 1; } } else { /*current cell and previuos cell are equal */ /* ? * 1 1 */ if (corrCell == supCell) { /*current cell and upper cell are equal */ /* 1 * 1 1 */ if (mask_patch_sup[i] != mask_patch_corr[i - 1]) { long r = 0; long del = mask_patch_sup[i]; r = avlID_sub(&albero, del); /*r=number of cell of patch removed */ if (r == 0) { G_fatal_error("avlID_sub error"); return RLI_ERRORE; } /*Remove one patch because it makes part of a patch already found */ ris = avlID_add(&albero, idCorr, r); switch (ris) { case AVL_ERR: { G_fatal_error("avlID_add error"); return RLI_ERRORE; } case AVL_ADD: { npatch++; break; } case AVL_PRES: { break; } default: { G_fatal_error("avlID_add unknown error"); return RLI_ERRORE; } } r = i; while (r < ad->cl) { if (mask_patch_sup[r] == del) { mask_patch_sup[r] = idCorr; } r++; } mask_patch_corr[i] = idCorr; } else { mask_patch_corr[i] = idCorr; } } else { /*current cell and upper cell are not equal */ /* 2 * 1 1 */ mask_patch_corr[i] = idCorr; } totCorr++; } } else { /*cell is null or is not to consider */ mask_patch_corr[i] = 0; } } { int ii; long c; for (ii = 0; ii < ad->cl; ii++) { c = mask_patch_corr[ii]; mask_patch_sup[ii] = c; mask_patch_corr[ii] = 0; } } } if (areaPatch != 0) { if (albero == NULL) { albero = avlID_make(idCorr, totCorr); if (albero == NULL) { G_fatal_error("avlID_make error"); return RLI_ERRORE; } npatch++; } else { ris = avlID_add(&albero, idCorr, totCorr); switch (ris) { case AVL_ERR: { G_fatal_error("avlID_add error"); return RLI_ERRORE; } case AVL_ADD: { npatch++; break; } case AVL_PRES: { break; } default: { G_fatal_error("avlID_add unknown error"); return RLI_ERRORE; } } } array = G_malloc(npatch * sizeof(avlID_tableRow)); if (array == NULL) { G_fatal_error("malloc array failed"); return RLI_ERRORE; } tot = avlID_to_array(albero, zero, array); if (tot != npatch) { G_warning ("avlID_to_array unaspected value. the result could be wrong"); return RLI_ERRORE; } for (i = 0; i < npatch; i++) { if (array[i]->tot == 0) { doppi++; } } np = npatch; npatch = npatch - doppi; mn = areaPatch / npatch; /* calculate summary */ for (i = 0; i < np; i++) { long areaPi = 0; double diff; if (array[i]->tot != 0) { ris = ris + array[i]->tot; areaPi = (double)array[i]->tot; diff = areaPi - mn; somma = somma + (diff * diff); } } sd = sqrt(somma / npatch); cv = sd * 100 / mn; indice = cv; G_free(array); } else indice = (double)(-1); if (masked) G_free(mask_buf); G_free(mask_patch_sup); *result = indice; return RLI_OK; }
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); }
/* writes one GRASS DCELL null value into the output row */ void write_row_null (DCELL *row, long easting) { G_set_d_null_value (&row[easting], 1); }
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; }
static void seed(struct ClassSig *Sig, int nbands) { int i, b1, b2; double period; double *mean, **R; /* Compute the mean of variance for each band */ mean = G_alloc_vector(nbands); R = G_alloc_matrix(nbands, nbands); n_nulls = (int *)G_calloc(nbands, sizeof(int)); total_nulls = 0; for (b1 = 0; b1 < nbands; b1++) { n_nulls[b1] = 0; mean[b1] = 0.0; for (i = 0; i < Sig->ClassData.npixels; i++) { if (G_is_d_null_value(&Sig->ClassData.x[i][b1])) { n_nulls[b1]++; total_nulls++; } else mean[b1] += Sig->ClassData.x[i][b1]; } mean[b1] /= (double)(Sig->ClassData.npixels - n_nulls[b1]); } for (b1 = 0; b1 < nbands; b1++) for (b2 = 0; b2 < nbands; b2++) { R[b1][b2] = 0.0; for (i = 0; i < Sig->ClassData.npixels; i++) { if (!G_is_d_null_value(&Sig->ClassData.x[i][b1]) && !G_is_d_null_value(&Sig->ClassData.x[i][b2])) R[b1][b2] += (Sig->ClassData.x[i][b1]) * (Sig->ClassData.x[i][b2]); } R[b1][b2] /= (double)(Sig->ClassData.npixels - n_nulls[b1] - n_nulls[b2]); R[b1][b2] -= mean[b1] * mean[b2]; } /* Compute the sampling period for seeding */ if (Sig->nsubclasses > 1) { period = (Sig->ClassData.npixels - 1) / (Sig->nsubclasses - 1.0); } else period = 0; /* Seed the means and set the diagonal covariance components */ for (i = 0; i < Sig->nsubclasses; i++) { for (b1 = 0; b1 < nbands; b1++) { if (G_is_d_null_value(&Sig->ClassData.x[(int)(i * period)][b1])) G_set_d_null_value(&Sig->SubSig[i].means[b1], 1); else Sig->SubSig[i].means[b1] = Sig->ClassData.x[(int)(i * period)][b1]; } for (b1 = 0; b1 < nbands; b1++) for (b2 = 0; b2 < nbands; b2++) { Sig->SubSig[i].R[b1][b2] = R[b1][b2]; } Sig->SubSig[i].pi = 1.0 / Sig->nsubclasses; } G_free_vector(mean); G_free_matrix(R); compute_constants(Sig, nbands); }