Exemplo n.º 1
0
void read_dem_header ( image<short> & dem )
{
    char file[1000];
    GDALDataset  *df;
    GDALRasterBand *bd;
    double        trans[6];
    int rows, cols;

    strcpy ( file, p.value("dem_file").c_str());
    if ( strlen(file) == 0 ) {
        fprintf(stderr,"Need to specify a dem file\n");
        exit(1);
    }

    df = (GDALDataset *) GDALOpen( file, GA_ReadOnly );
    if( df == NULL ) {
        fprintf(stderr,"Could not open dem file: %s\n", file );
        exit(1);
    }
    rows = df->GetRasterYSize();
    cols = df->GetRasterXSize();
    dem.create(rows,cols);

    if( df->GetGeoTransform( trans ) == CE_None ) {
        dem_east = trans[0];
        dem_north = trans[3];
        dem_wid = trans[1];
    } else {
        fprintf(stderr,"Dem file: %s has no geographic metadata\n", file );
        exit(1);
    }

    delete df;
}
Exemplo n.º 2
0
int Raster<T>::ReadAsInt32(const char* filename)
{
	GDALDataset  *poDataset = (GDALDataset *) GDALOpen( filename, GA_ReadOnly );
	if( poDataset == NULL )
	{
		cerr << "Open file: " << filename << " failed.\n";
		return -1;
	}

	GDALRasterBand  *poBand= poDataset->GetRasterBand(1);
	m_nCols = poBand->GetXSize();
	m_nRows = poBand->GetYSize();
	m_nAll = m_nRows * m_nCols;

	m_noDataValue = poBand->GetNoDataValue();
	double adfGeoTransform[6];
	poDataset->GetGeoTransform(adfGeoTransform);
	m_dx = adfGeoTransform[1];
	m_dy = -adfGeoTransform[5];
	m_xMin = adfGeoTransform[0];
	m_yMax = adfGeoTransform[3];

	m_proj = poDataset->GetProjectionRef();

	if (m_data != NULL)
		CPLFree(m_data);

	m_dType = GDT_Int32;
	m_data = (T*) CPLMalloc(sizeof(int)*m_nAll);
	
	poBand->RasterIO(GF_Read, 0, 0, m_nCols, m_nRows, m_data, m_nCols, m_nRows, m_dType, 0, 0);
	GDALClose(poDataset);

	return 0;
}
Exemplo n.º 3
0
CPLErr GDALOverviewDataset::GetGeoTransform( double * padfTransform )

{
    double adfGeoTransform[6];
    if( poMainDS->GetGeoTransform(adfGeoTransform) == CE_None )
    {
        if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 )
        {
            adfGeoTransform[1] *= (double)poMainDS->GetRasterXSize() / nRasterXSize;
            adfGeoTransform[5] *= (double)poMainDS->GetRasterYSize() / nRasterYSize;
        }
        else
        {
            /* If the x and y ratios are not equal, then we cannot really */
            /* compute a geotransform */
            double dfRatio = (double)poMainDS->GetRasterXSize() / nRasterXSize;
            adfGeoTransform[1] *= dfRatio;
            adfGeoTransform[2] *= dfRatio;
            adfGeoTransform[4] *= dfRatio;
            adfGeoTransform[5] *= dfRatio;
        }
        memcpy( padfTransform, adfGeoTransform, sizeof(double)*6 );

        return CE_None;
    }
    else
        return CE_Failure;
}
Exemplo n.º 4
0
SEXP
RGDAL_GetGeoTransform(SEXP sxpDataset) {

  GDALDataset *pDataset = getGDALDatasetPtr(sxpDataset);

  SEXP sxpGeoTrans = allocVector(REALSXP, 6);
  SEXP ceFail = NEW_LOGICAL(1);
  LOGICAL_POINTER(ceFail)[0] = FALSE;

  installErrorHandler();
  CPLErr err = pDataset->GetGeoTransform(REAL(sxpGeoTrans));

  if (err == CE_Failure) {

    REAL(sxpGeoTrans)[0] = 0; // x-origin ul
    REAL(sxpGeoTrans)[1] = 1; // x-resolution (pixel width)
    REAL(sxpGeoTrans)[2] = 0; // x-oblique
    REAL(sxpGeoTrans)[3] = (double) pDataset->GetRasterYSize();
 // y-origin ul; 091028
    REAL(sxpGeoTrans)[4] = 0; // y-oblique
    REAL(sxpGeoTrans)[5] = -1; // y-resolution (pixel height); 091028 added sign
    LOGICAL_POINTER(ceFail)[0] = TRUE;

  }
  setAttrib(sxpGeoTrans, install("CE_Failure"), ceFail);
  uninstallErrorHandlerAndTriggerError();

  return(sxpGeoTrans);

}
Exemplo n.º 5
0
void SmallpatchSieveFilter::SieveFilter(const char* Src_path, const char* Dst_Path, int SizeThresthod, int Connectedness)
{
	GDALAllRegister();
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO");
	GDALDriver* poDriver = GetGDALDriverManager()->GetDriverByName("GTIFF");
	if (poDriver == NULL)
	{
		cout << "不能创建指定类型的文件:" << endl;
	}
	GDALDataset* poSrc = (GDALDataset*)GDALOpen(Src_path,GA_ReadOnly);
	int NewBandXsize = poSrc->GetRasterXSize();
	int NewBandYsize = poSrc->GetRasterYSize();
	GDALDataType Type = poSrc->GetRasterBand(1)->GetRasterDataType();
	
	GDALDataset* poDstDS = poDriver->Create(Dst_Path, NewBandXsize, NewBandYsize, 1, Type, NULL);
	double GeoTrans[6] = { 0 };
	poSrc->GetGeoTransform(GeoTrans);
	poDstDS->SetGeoTransform(GeoTrans);
	poDstDS->SetProjection(poSrc->GetProjectionRef());
	GDALRasterBandH HImgBand = (GDALRasterBandH)poSrc->GetRasterBand(1);
	GDALRasterBandH HPDstDSBand = (GDALRasterBandH)poDstDS->GetRasterBand(1);
	GDALSetRasterColorTable(HPDstDSBand, GDALGetRasterColorTable(HImgBand));

	GDALSieveFilter(HImgBand, NULL, HPDstDSBand, SizeThresthod, Connectedness, NULL, NULL, NULL);

	GDALClose((GDALDatasetH)poDstDS);
};
Exemplo n.º 6
0
/*! \file io.cpp
    With a little bit of a elaboration, should you feel it necessary.
*/
int printRasterInfo(const char* pszFilename)
{
    /** An enum type.
     *  The documentation block cannot be put after the enum!
     */

    GDALDataset *poDataset;
    GDALAllRegister();
    poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly );

    if( poDataset == NULL )
    {
        std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl;
        return -1;
    }
    else
    {
        std::cout << "Dataset: " << pszFilename << std::endl;
        double adfGeoTransform[6];
        std::cout << " Driver: " << poDataset->GetDriver()->GetDescription() << "/" <<
                poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl;
        std::cout << " Size: " << poDataset->GetRasterXSize() << "x" << poDataset->GetRasterYSize() << "x" <<
                poDataset->GetRasterCount() << std::endl;
        if( poDataset->GetProjectionRef()  != NULL )
            std::cout << " Projection: " << poDataset->GetProjectionRef() << std::endl;
        if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
        {
            std::cout << " Origin: (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl;
            std::cout << " Pixel Size: (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << std::endl;
        }
    }
    return 0;
}
Exemplo n.º 7
0
void RasterImageLayer::loadFile()
{
    GDALDataset *ds = static_cast<GDALDataset*>(GDALOpen(m_filename.toLocal8Bit(), GA_ReadOnly));
    if (ds == nullptr)
    {
        qWarning() << "Error opening file:" << m_filename;
    }
    else
    {
        projection().setGeogCS(new OGRSpatialReference(ds->GetProjectionRef()));
        projection().setProjCS(new OGRSpatialReference(ds->GetProjectionRef()));
        projection().setDomain({-180., -90., 360., 180.});

        std::vector<double> geoTransform(6);
        int xsize = ds->GetRasterXSize();
        int ysize = ds->GetRasterYSize();
        ds->GetGeoTransform(geoTransform.data());
        vertData.resize(4);
        vertData[0] = QVector2D(geoTransform[0], geoTransform[3]);
        vertData[1] = QVector2D(geoTransform[0] + geoTransform[2] * ysize,
                geoTransform[3] + geoTransform[5] * ysize);
        vertData[2] = QVector2D(geoTransform[0] + geoTransform[1] * xsize + geoTransform[2] * ysize,
                geoTransform[3] + geoTransform[4] * xsize + geoTransform[5] * ysize);
        vertData[3] = QVector2D(geoTransform[0] + geoTransform[1] * xsize,
                geoTransform[3] + geoTransform[4] * xsize);
        texData = {{0., 0.}, {0., 1.}, {1., 1.}, {1., 0.}};

        int numBands = ds->GetRasterCount();
        qDebug() << "Bands:" << numBands;

        imData = QImage(xsize, ysize, QImage::QImage::Format_RGBA8888);
        imData.fill(QColor(255, 255, 255, 255));
        // Bands start at 1
        for (int i = 1; i <= numBands; ++i)
        {
            GDALRasterBand *band = ds->GetRasterBand(i);
            switch(band->GetColorInterpretation())
            {
            case GCI_RedBand:
                band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits(),
                               xsize, ysize, GDT_Byte, 4, 0);
                break;
            case GCI_GreenBand:
                band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits() + 1,
                               xsize, ysize, GDT_Byte, 4, 0);
                break;
            case GCI_BlueBand:
                band->RasterIO(GF_Read, 0, 0, xsize, ysize, imData.bits() + 2,
                               xsize, ysize, GDT_Byte, 4, 0);
                break;
            default:
                qWarning() << "Unhandled color interpretation:" << band->GetColorInterpretation();
            }
        }

        GDALClose(ds);
        newFile = true;
    }
}
Exemplo n.º 8
0
int main()
{
    GDALDataset  *poDataset;
    GDALAllRegister();
    poDataset = (GDALDataset *) GDALOpen( "GE01.tif", GA_ReadOnly );
    printf("Working! \n");

    if( poDataset != NULL ){
    	//Get Dataset Information
        double adfGeoTransform[6];

		printf( "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

		printf( "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() );

		if( poDataset->GetProjectionRef()  != NULL )
    		printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );

		if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ){
    		printf( "Origin = (%.6f,%.6f)\n",
            adfGeoTransform[0], adfGeoTransform[3] );
    		printf( "Pixel Size = (%.6f,%.6f)\n",
            adfGeoTransform[1], adfGeoTransform[5] );
		}

		//Fetch Raster Band
		GDALRasterBand  *poBand;
		int             nBlockXSize, nBlockYSize;
		int             bGotMin, bGotMax;
		double          adfMinMax[2];
		poBand = poDataset->GetRasterBand( 1 );
		poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
		printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
		        nBlockXSize, nBlockYSize,
		        GDALGetDataTypeName(poBand->GetRasterDataType()),
		        GDALGetColorInterpretationName(
		            poBand->GetColorInterpretation()) );
		adfMinMax[0] = poBand->GetMinimum( &bGotMin );
		adfMinMax[1] = poBand->GetMaximum( &bGotMax );
		if( ! (bGotMin && bGotMax) )
		    GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
		printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] );
		if( poBand->GetOverviewCount() > 0 )
		    printf( "Band has %d overviews.\n", poBand->GetOverviewCount() );
		if( poBand->GetColorTable() != NULL )
		    printf( "Band has a color table with %d entries.\n", 
		             poBand->GetColorTable()->GetColorEntryCount() );

		//Close Dataset
		GDALClose(poDataset);
		//Exit      
		return 0;
	}


}
Exemplo n.º 9
0
void bin2ascii(char *binFile, char *asciiFile){
    GDALDataset *layer;
    GDALAllRegister();
    layer = (GDALDataset *)GDALOpen(binFile, GA_ReadOnly);
    
    int bandNumber = 1;
    GDALRasterBand *band = layer->GetRasterBand(bandNumber);
    GDALDataType type    = band->GetRasterDataType();

    double ranges[6];
    layer->GetGeoTransform(ranges);

    ofstream outFile;
    outFile.open(asciiFile);
     
    outFile<<"ncols "<<layer->GetRasterXSize()<<"\n";
    outFile<<"nrows "<<layer->GetRasterYSize()<<"\n";
    outFile<<"xllcorner "<<ranges[0]<<"\n";
    outFile<<"yllcorner "<<(ranges[3] + layer->GetRasterXSize() * ranges[4] + layer->GetRasterYSize() * ranges[5])<<"\n";
    outFile<<"cellsize " <<ranges[1]<<"\n";
    outFile<<"nodata_value "<<"-9999"<<"\n";
    //getchar(); getchar();

    int cols = layer->GetRasterXSize();
    int rows = layer->GetRasterYSize();
    double NODATA_VAL = band->GetNoDataValue();

    cout<<"NODATA_VALUE= "<<NODATA_VAL<<"\n";

    int size = GDALGetDataTypeSize(type) / 8;
    void *data = CPLMalloc(size);
    //CPLErr err = band->RasterIO(GF_Read, 0, 0, cols, rows, data, cols, rows, type, 0, 0);
	//getchar(); getchar();
    //for(int j=0; j<rows*cols; j++){
	//int col, row;
    for(int row=0; row<rows; row++){
	for(int col=0; col<cols; col++){	
	 
	CPLErr err = band->RasterIO(GF_Read, col, row, 1, 1, data, 1, 1, type, 0, 0);
	double tempVal = readValueB2A(data, type, 0);
	outFile<<( tempVal != NODATA_VAL ? tempVal : -9999)<<" "; 
	
    	    //if((j+1)%cols == 0){
	//	cout<<"\n";
		//getchar(); getchar();
	//	}
	}
	outFile<<"\n"; 
	//getchar();
    }
	cout<<"Bin2Ascii.. Done!\n";
	outFile.close();
	//getchar(); getchar();
}
Exemplo n.º 10
0
int main(int argc, char** argv )
{
	float xright,ybottom,x,y;
	if (argc > 1)
	{
		// Now getting information for this dataset
		cout << "File Inputed: " << argv[1] << endl;

		// Lets open a Tif
		GDALDataset *poDataset;

		// Register all gdal drivers -- load every possible driver gdal has
		GDALAllRegister();

		// lets load a "dataset" which is gdal terminology for your data
		poDataset = (GDALDataset*) GDALOpen(argv[1], GA_ReadOnly);

		// Get width and height of this dataset

		int width = GDALGetRasterXSize(poDataset);
		int height = GDALGetRasterYSize(poDataset);
		cout << "Data size: " << width << " " << height << endl;

		// Get projection information of this dataset
		string proj;
		proj = string(poDataset->GetProjectionRef());
		cout << "Projection: " << proj << endl;

		// get geo transform for this dataset
		double adfGeoTransform[6];
		if ( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
		{
			printf( "Origin = (%.6f,%.6f)\n",
			        adfGeoTransform[0], adfGeoTransform[3] );

			printf( "Pixel Size = (%.6f,%.6f)\n",
			        adfGeoTransform[1], adfGeoTransform[5] );
			x = adfGeoTransform[0];
			y = adfGeoTransform[3];
			xright = x + adfGeoTransform[1] * width;
			ybottom = y + adfGeoTransform[5] * height;
			cout << "East: " << x << " West: " << xright << " North: " << y << " South: " << ybottom << endl; 
			cout << "Pixel Size(x y): " << adfGeoTransform[1] << " " << adfGeoTransform[5] << endl;
		}
		else
		{
			return 1;
		}
		
	}
	return 0;

}
Exemplo n.º 11
0
int
NBHeightMapper::loadTiff(const std::string& file) {
#ifdef HAVE_GDAL
    GDALAllRegister();
    GDALDataset* poDataset = (GDALDataset*)GDALOpen(file.c_str(), GA_ReadOnly);
    if (poDataset == 0) {
        WRITE_ERROR("Cannot load GeoTIFF file.");
        return 0;
    }
    const int xSize = poDataset->GetRasterXSize();
    const int ySize = poDataset->GetRasterYSize();
    double adfGeoTransform[6];
    if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) {
        Position topLeft(adfGeoTransform[0], adfGeoTransform[3]);
        mySizeOfPixel.set(adfGeoTransform[1], adfGeoTransform[5]);
        const double horizontalSize = xSize * mySizeOfPixel.x();
        const double verticalSize = ySize * mySizeOfPixel.y();
        myBoundary.add(topLeft);
        myBoundary.add(topLeft.x() + horizontalSize, topLeft.y() + verticalSize);
    } else {
        WRITE_ERROR("Could not parse geo information from " + file + ".");
        return 0;
    }
    const int picSize = xSize * ySize;
    myRaster = (int16_t*)CPLMalloc(sizeof(int16_t) * picSize);
    for (int i = 1; i <= poDataset->GetRasterCount(); i++) {
        GDALRasterBand* poBand = poDataset->GetRasterBand(i);
        if (poBand->GetColorInterpretation() != GCI_GrayIndex) {
            WRITE_ERROR("Unknown color band in " + file + ".");
            clearData();
            break;
        }
        if (poBand->GetRasterDataType() != GDT_Int16) {
            WRITE_ERROR("Unknown data type in " + file + ".");
            clearData();
            break;
        }
        assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize());
        if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, myRaster, xSize, ySize, GDT_Int16, 0, 0) == CE_Failure) {
            WRITE_ERROR("Failure in reading " + file + ".");
            clearData();
            break;
        }
    }
    GDALClose(poDataset);
    return picSize;
#else
    UNUSED_PARAMETER(file);
    WRITE_ERROR("Cannot load GeoTIFF file since SUMO was compiled without GDAL support.");
    return 0;
#endif
}
Exemplo n.º 12
0
/**
*@brief 点对点的转换
*@param tifPath [in] tif图片路径
*@param toWkt [in] 目标点的wkt字符串
*@param x [in] x点经度
*@param y [in] y点纬度
*@return 转换后的经纬度坐标
*/
double *GdalProjection::PointToPoint(const char *tifPath,const char *toWkt,int x,int y)
{
    GDALDataset *poDataset = gbase.OpenDatasetR(tifPath);
    const char *fromWkt = poDataset->GetProjectionRef();
    double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6);
    poDataset->GetGeoTransform(adfGeoTransform);
    double nx = gbase.GetLonOfPoint(adfGeoTransform,x,y);
    double ny = gbase.GetLatOfPoint(adfGeoTransform,x,y);
    double *ptop = PointToPoint(fromWkt,toWkt,nx,ny);
    GDALClose(poDataset);
    CPLFree(adfGeoTransform);
    return ptop;
}
Exemplo n.º 13
0
/**
 * Set location of the station based on latitude and longitude.  Datum
 * transformation info may need to occur
 * @param Lat latitude of the station
 * @param Lon longitude of the station
 * @param demFile file name of the input dem, for coord tranformation
 * @param datum datum to convert to.
 */
void wxStation::set_location_LatLong( double Lat, double Lon,
                                      const std::string demFile,
                      const char *datum )
{
    lon = Lon;
    lat = Lat;

    if( demFile.empty() || demFile == "" )
        return;
    GDALDataset *poDS = (GDALDataset*)GDALOpen( demFile.c_str(), GA_ReadOnly );

    if( poDS == NULL )
        return;

    double projX = lon;
    double projY = lat;

    GDALPointFromLatLon( projX, projY, poDS, datum );

    projXord = projX;
    projYord = projY;

    //still assume dem is projected.
    double llx = 0.0;
    double lly = 0.0;
    double adfGeoTransform[6];

    if( poDS->GetGeoTransform( adfGeoTransform ) != CE_None )
    {
        xord = projXord;
        yord = projYord;
        return;
    }

    llx = adfGeoTransform[0];
    lly = adfGeoTransform[3] + ( adfGeoTransform[5] * poDS->GetRasterYSize() );

    xord = projXord - llx;
    yord = projYord - lly;

    if( EQUAL( datum, "WGS84" ) )
        datumType = WGS84;
    else if( EQUAL( datum, "NAD83" ) )
        datumType = NAD83;
    else if ( EQUAL( datum, "NAD27" ) )
        datumType = NAD27;

    coordType = GEOGCS;

    GDALClose( (GDALDatasetH)poDS );
}
Exemplo n.º 14
0
void getGDALHeader(const std::string &filename, int &height, int &width, T &no_data, double *geotrans){
  GDALAllRegister();
  GDALDataset *fin = (GDALDataset*)GDALOpen(filename.c_str(), GA_ReadOnly);
  assert(fin!=NULL);

  GDALRasterBand *band   = fin->GetRasterBand(1);

  height  = band->GetYSize();
  no_data = band->GetNoDataValue();
  width   = band->GetXSize();

  fin->GetGeoTransform(geotrans);

  GDALClose(fin);
}
Exemplo n.º 15
0
  void saveGDAL(const std::string &filename, const std::string &template_name, int xoffset, int yoffset){
    GDALDataset *fintempl = (GDALDataset*)GDALOpen(template_name.c_str(), GA_ReadOnly);
    assert(fintempl!=NULL); //TODO: Error handle

    GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
    assert(poDriver!=NULL); //TODO: Error handle
    GDALDataset *fout    = poDriver->Create(filename.c_str(), viewWidth(), viewHeight(), 1, myGDALType(), NULL);
    assert(fout!=NULL);     //TODO: Error handle

    GDALRasterBand *oband = fout->GetRasterBand(1);
    oband->SetNoDataValue(no_data);

    //The geotransform maps each grid cell to a point in an affine-transformed
    //projection of the actual terrain. The geostransform is specified as follows:
    //    Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
    //    Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
    //In case of north up images, the GT(2) and GT(4) coefficients are zero, and
    //the GT(1) is pixel width, and GT(5) is pixel height. The (GT(0),GT(3))
    //position is the top left corner of the top left pixel of the raster.
    double geotrans[6];
    fintempl->GetGeoTransform(geotrans);

    //We shift the top-left pixel of hte image eastward to the appropriate
    //coordinate
    geotrans[0] += xoffset*geotrans[1];

    //We shift the top-left pixel of the image southward to the appropriate
    //coordinate
    geotrans[3] += yoffset*geotrans[5];

    #ifdef DEBUG
      std::cerr<<"Filename: "<<std::setw(20)<<filename<<" Xoffset: "<<std::setw(6)<<xoffset<<" Yoffset: "<<std::setw(6)<<yoffset<<" Geotrans0: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[0]<<" Geotrans3: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[3]<< std::endl;
    #endif

    fout->SetGeoTransform(geotrans);

    const char* projection_string=fintempl->GetProjectionRef();
    fout->SetProjection(projection_string);

    GDALClose(fintempl);

    for(int y=0;y<view_height;y++)
      oband->RasterIO(GF_Write, 0, y, viewWidth(), 1, data[y].data(), viewWidth(), 1, myGDALType(), 0, 0);

    GDALClose(fout);
  }
Exemplo n.º 16
0
gdal_datasource::gdal_datasource(parameters const& params)
   : datasource(params),
     desc_(*params.get<std::string>("type"),"utf-8")
{

#ifdef MAPNIK_DEBUG
   std::clog << "\nGDAL Plugin: Initializing...\n";
#endif

   GDALAllRegister();

   boost::optional<std::string> file = params.get<std::string>("file");
   if (!file) throw datasource_exception("missing <file> parameter");

   boost::optional<std::string> base = params.get<std::string>("base");
   if (base)
      dataset_name_ = *base + "/" + *file;
   else
      dataset_name_ = *file;

   shared_dataset_ = *params_.get<mapnik::boolean>("shared",false);
   band_ = *params_.get<int>("band", -1);

   GDALDataset *dataset = open_dataset();
   
   // TODO: Make more class attributes from geotransform...
   width_ = dataset->GetRasterXSize();
   height_ = dataset->GetRasterYSize();

   double tr[6];
   dataset->GetGeoTransform(tr);
   double dx = tr[1];
   double dy = tr[5];
   double x0 = tr[0];
   double y0 = tr[3];
   double x1 = tr[0] + width_ * dx + height_ *tr[2];
   double y1 = tr[3] + width_ *tr[4] + height_ * dy;
   extent_.init(x0,y0,x1,y1);
   GDALClose(dataset);
   
#ifdef MAPNIK_DEBUG
   std::clog << "GDAL Plugin: Raster Size=" << width_ << "," << height_ << "\n";
   std::clog << "GDAL Plugin: Raster Extent=" << extent_ << "\n";
#endif

}
Exemplo n.º 17
0
/**
 * Set the location of the station in lat/lon based on projected coordinates
 * @param Xord x coordinate in system
 * @param Yord y coordinate in system
 * @param demFile name of the dem file to create the coordinate transformation
 * from
 */
void wxStation::set_location_projected( double Xord, double Yord,
                    std::string demFile )
{
    projXord = Xord;
    projYord = Yord;

    if( demFile.empty() || demFile == "" )
        return;

    //get llcorner to subtract
    GDALDataset *poDS = (GDALDataset*) GDALOpen( demFile.c_str(), GA_ReadOnly );
    if( poDS == NULL ){
        xord = Xord;
        yord = Yord;
        return;
    }

    double adfGeoTransform[6];

    if( poDS->GetGeoTransform( adfGeoTransform ) != CE_None ) {
        xord = Xord;
        yord = Yord;
        return;
    }

    double llx = 0.0;
    double lly = 0.0;
    llx = adfGeoTransform[0];
    lly = adfGeoTransform[3] + ( adfGeoTransform[5] * poDS->GetRasterYSize() );

    xord = Xord - llx;
    yord = Yord - lly;

    double lonx = projXord;
    double laty = projYord;

    GDALPointToLatLon( lonx, laty, poDS, "WGS84" );
    datumType = WGS84;
    coordType = PROJCS;

    lon = lonx;
    lat = laty;

    GDALClose( (GDALDatasetH)poDS );
}
Exemplo n.º 18
0
/**
*@brief 数组对数组的转换
*@param tifPath [in] tif图片路径
*@param toWkt [in] 目标点的wkt字符串
*@param x [in] 经度数组
*@param y [in] 纬度数组
*@param nCount [in] 数组大小
*@return 转换后的经纬度坐标
*/
vector<double *> GdalProjection::ArrayToArray(const char *tifPath,const char *toWkt,int *x,int *y,int nCount)
{
    vector<double *> ve;
    GDALDataset *poDataset = gbase.OpenDatasetR(tifPath);
    const char *fromWkt = poDataset->GetProjectionRef();
    double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6);
    poDataset->GetGeoTransform(adfGeoTransform);
    double *nx = (double *)CPLMalloc(sizeof(double) * nCount);
    double *ny = (double *)CPLMalloc(sizeof(double) * nCount);
    for (int i = 0; i < nCount; i++)
    {
        nx[i]  =  gbase.GetLonOfPoint(adfGeoTransform,x[i],y[i]);
        ny[i]  =  gbase.GetLatOfPoint(adfGeoTransform,x[i],y[i]);
    }
    free(x);
    free(y);
    ve = ArrayToArray(fromWkt,toWkt,nx,ny,nCount);
    return ve;
}
Exemplo n.º 19
0
void getGDALHeader(
  const   std::string &filename,
  int32_t &height,
  int32_t &width,
  T       &no_data,
  double  geotransform[6]
){
  GDALAllRegister();
  GDALDataset *fin = (GDALDataset*)GDALOpen(filename.c_str(), GA_ReadOnly);
  if(fin==NULL)
    throw std::runtime_error("Could not get GDAL header: file '" + filename + "'' did not open!");

  GDALRasterBand *band   = fin->GetRasterBand(1);

  height  = band->GetYSize();
  no_data = band->GetNoDataValue();
  width   = band->GetXSize();

  fin->GetGeoTransform(geotransform);

  GDALClose(fin);
}
Exemplo n.º 20
0
const QString OmgGdal::getAsciiHeader(const QString theFileName)
{
  GDALAllRegister();
  GDALDataset  *gdalDataset = (GDALDataset *) GDALOpen( theFileName.local8Bit(), GA_ReadOnly );
  if ( gdalDataset == NULL )
  {
    return QString("");
  }

  //get dimensions and no data value
  int myColsInt = gdalDataset->GetRasterXSize();
  int myRowsInt = gdalDataset->GetRasterYSize();
  double myNullValue=gdalDataset->GetRasterBand(1)->GetNoDataValue();
  //get the geotransform stuff from gdal
  double myTransform[6];
  if (gdalDataset->GetGeoTransform(myTransform) != CE_None)
  {
    std::cout << "Failed to get geo transform from GDAL, aborting" << std::endl;
    GDALClose(gdalDataset);
    return QString("");
  }
  else

  {
    GDALClose(gdalDataset);
  }

  QString myHeader;

  myHeader =  "NCOLS "        + QString::number(myColsInt) + "\r\n";
  myHeader += "NROWS "        + QString::number(myRowsInt) + "\r\n";
  myHeader += "XLLCORNER "    + QString::number(myTransform[0]) +  "\r\n";;
  //negative y is bodged for now
  myHeader += "YLLCORNER -"   + QString::number(myTransform[3]) +  "\r\n"; 
  myHeader += "CELLSIZE "     + QString::number(myTransform[1]) +  "\r\n";
  myHeader += "NODATA_VALUE " + QString::number(myNullValue) +  "\r\n";

  return myHeader;
}
Exemplo n.º 21
0
SEXP
RGDAL_GetGeoTransform(SEXP sxpDataset) {

  GDALDataset *pDataset = getGDALDatasetPtr(sxpDataset);

  SEXP sxpGeoTrans = allocVector(REALSXP, 6);

  CPLErr err = pDataset->GetGeoTransform(REAL(sxpGeoTrans));

  if (err == CE_Failure) {

    REAL(sxpGeoTrans)[0] = 0;
    REAL(sxpGeoTrans)[1] = 1;
    REAL(sxpGeoTrans)[2] = 0;
    REAL(sxpGeoTrans)[3] = 0;
    REAL(sxpGeoTrans)[4] = 0;
    REAL(sxpGeoTrans)[5] = 1;

  }

  return(sxpGeoTrans);

}
Exemplo n.º 22
0
void CCreateMapFineTune::slotSave()
{
    IMap& map = CMapDB::self().getMap();
    GDALDataset * srcds = map.getDataset();
    if(srcds == 0)
    {
        return;
    }

    double adfGeoTransform[6];
    double u1, v1, u2, v2;
    map.dimensions(u1, v1, u2, v2);
    map.convertRad2M(u1, v1);
    map.convertRad2M(u2, v2);

    srcds->GetGeoTransform( adfGeoTransform );
    adfGeoTransform[0] = u1;
    adfGeoTransform[3] = v1;

    progressBar->show();
    GDALDriver * driver = srcds->GetDriver();

    char **papszOptions = NULL;
    papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" );
    papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "DEFLATE" );

    GDALDataset * dstds = driver->CreateCopy(labelOutfile->text().toLocal8Bit(), srcds, false, papszOptions, ProgressFunc, this);
    if(dstds)
    {
        dstds->SetGeoTransform( adfGeoTransform );
        GDALClose(dstds);
    }
    CSLDestroy( papszOptions );

    progressBar->hide();
}
Exemplo n.º 23
0
/**
  @brief  Retrieve height, width, data type, and geotransform from a GDAL file
  @author Richard Barnes ([email protected])

  @param[in]  filename   GDAL file to peek at
  @param[out] height     Height of the raster in cells
  @param[out] width      Width of the raster in cells
  @param[out] dtype      Data type of the file in question
  @param[out] geo_trans  Returns the SIX elements of the raster's geotransform
*/
void getGDALDimensions(
  const   std::string &filename,
  int32_t &height,
  int32_t &width,
  GDALDataType &dtype,
  double geotransform[6]
){
  GDALAllRegister();
  GDALDataset *fin = (GDALDataset*)GDALOpen(filename.c_str(), GA_ReadOnly);
  if(fin==NULL)
    throw std::runtime_error("Could not open file '"+filename+"' to get dimensions.");

  GDALRasterBand *band = fin->GetRasterBand(1);
  
  dtype = band->GetRasterDataType();

  if(geotransform!=NULL && fin->GetGeoTransform(geotransform)!=CE_None)
    throw std::runtime_error("Error getting geotransform from '"+filename+"'.");

  height  = band->GetYSize();
  width   = band->GetXSize();

  GDALClose(fin);
}
Exemplo n.º 24
0
FXImage*
GUISUMOAbstractView::checkGDALImage(Decal& d) {
#ifdef HAVE_GDAL
    GDALAllRegister();
    GDALDataset* poDataset = (GDALDataset*)GDALOpen(d.filename.c_str(), GA_ReadOnly);
    if (poDataset == 0) {
        return 0;
    }
    const int xSize = poDataset->GetRasterXSize();
    const int ySize = poDataset->GetRasterYSize();
    // checking for geodata in the picture and try to adapt position and scale
    if (d.width <= 0.) {
        double adfGeoTransform[6];
        if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) {
            Position topLeft(adfGeoTransform[0], adfGeoTransform[3]);
            const double horizontalSize = xSize * adfGeoTransform[1];
            const double verticalSize = ySize * adfGeoTransform[5];
            Position bottomRight(topLeft.x() + horizontalSize, topLeft.y() + verticalSize);
            if (GeoConvHelper::getProcessing().x2cartesian(topLeft) && GeoConvHelper::getProcessing().x2cartesian(bottomRight)) {
                d.width = bottomRight.x() - topLeft.x();
                d.height = topLeft.y() - bottomRight.y();
                d.centerX = (topLeft.x() + bottomRight.x()) / 2;
                d.centerY = (topLeft.y() + bottomRight.y()) / 2;
                //WRITE_MESSAGE("proj: " + toString(poDataset->GetProjectionRef()) + " dim: " + toString(d.width) + "," + toString(d.height) + " center: " + toString(d.centerX) + "," + toString(d.centerY));
            } else {
                WRITE_WARNING("Could not convert coordinates in " + d.filename + ".");
            }
        }
    }
#endif
    if (d.width <= 0.) {
        d.width = getGridWidth();
        d.height = getGridHeight();
    }

    // trying to read the picture
#ifdef HAVE_GDAL
    const int picSize = xSize * ySize;
    FXColor* result;
    if (!FXMALLOC(&result, FXColor, picSize)) {
        WRITE_WARNING("Could not allocate memory for " + d.filename + ".");
        return 0;
    }
    for (int j = 0; j < picSize; j++) {
        result[j] = FXRGB(0, 0, 0);
    }
    bool valid = true;
    for (int i = 1; i <= poDataset->GetRasterCount(); i++) {
        GDALRasterBand* poBand = poDataset->GetRasterBand(i);
        int shift = -1;
        if (poBand->GetColorInterpretation() == GCI_RedBand) {
            shift = 0;
        } else if (poBand->GetColorInterpretation() == GCI_GreenBand) {
            shift = 1;
        } else if (poBand->GetColorInterpretation() == GCI_BlueBand) {
            shift = 2;
        } else if (poBand->GetColorInterpretation() == GCI_AlphaBand) {
            shift = 3;
        } else {
            WRITE_MESSAGE("Unknown color band in " + d.filename + ", maybe fox can parse it.");
            valid = false;
            break;
        }
        assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize());
        if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, ((unsigned char*)result) + shift, xSize, ySize, GDT_Byte, 4, 4 * xSize) == CE_Failure) {
            valid = false;
            break;
        }
    }
    GDALClose(poDataset);
    if (valid) {
        return new FXImage(getApp(), result, IMAGE_OWNED | IMAGE_KEEP | IMAGE_SHMI | IMAGE_SHMP, xSize, ySize);
    }
    FXFREE(&result);
#endif
    return 0;
}
Exemplo n.º 25
0
std::tuple<boost::shared_ptr<Map_Matrix<DataFormat> >, std::string, GeoTransform>  read_in_map(fs::path file_path, GDALDataType data_type, const bool doCategorise) throw(std::runtime_error)
{

    std::string projection;
    GeoTransform transformation;
    GDALDriver driver;
    
	//Check that the file name is valid
	if (!(fs::is_regular_file(file_path)))
	{
		throw std::runtime_error("Input file is not a regular file");
	}	

	// Get GDAL to open the file - code is based on the tutorial at http://www.gdal.org/gdal_tutorial.html
	GDALDataset *poDataset;
	GDALAllRegister(); //This registers all availble raster file formats for use with this utility. How neat is that. We can input any GDAL supported rater file format.

	//Open the Raster by calling GDALOpen. http://www.gdal.org/gdal_8h.html#a6836f0f810396c5e45622c8ef94624d4
	//char pszfilename[] = file_path.c_str(); //Set this to the file name, as GDALOpen requires the standard C char pointer as function parameter.
	poDataset = (GDALDataset *) GDALOpen (file_path.string().c_str(), GA_ReadOnly);
	if (poDataset == NULL)
	{
		throw std::runtime_error("Unable to open file");
	}
	
//	Print some general information about the raster
	double        adfGeoTransform[6]; //An array of doubles that will be used to save information about the raster - where the origin is, what the raster pizel size is.
    
    
    printf( "Driver: %s/%s\n",
            poDataset->GetDriver()->GetDescription(),
            poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

    printf( "Size is %dx%dx%d\n", 
            poDataset->GetRasterXSize(), poDataset->GetRasterYSize(),
            poDataset->GetRasterCount() );

    if( poDataset->GetProjectionRef()  != NULL )
    {
        printf( "Projection is `%s'\n", poDataset->GetProjectionRef() );
        projection = poDataset->GetProjectionRef();
    }

    if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None )
    {
        printf( "Origin = (%.6f,%.6f)\n",
                adfGeoTransform[0], adfGeoTransform[3] );

        printf( "Pixel Size = (%.6f,%.6f)\n",
                adfGeoTransform[1], adfGeoTransform[5] );
        
        transformation.x_origin = adfGeoTransform[0];
        transformation.pixel_width = adfGeoTransform[1];
        transformation.x_line_space = adfGeoTransform[2];
        transformation.y_origin = adfGeoTransform[3];
        transformation.pixel_height = adfGeoTransform[4];
        transformation.y_line_space = adfGeoTransform[5];
        
    }


	/// Some raster file formats allow many layers of data (called a 'band', with each having the same pixel size and origin location and spatial extent). We will get the data for the first layer into a Boost Array.
	//Get the data from the first band, 
	// TODO implement method with input to specify what band.
	    GDALRasterBand  *poBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];
        
        poBand = poDataset->GetRasterBand( 1 );
        poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
        printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
                nBlockXSize, nBlockYSize,
                GDALGetDataTypeName(poBand->GetRasterDataType()),
                GDALGetColorInterpretationName(
                    poBand->GetColorInterpretation()) );

        adfMinMax[0] = poBand->GetMinimum( &bGotMin );
        adfMinMax[1] = poBand->GetMaximum( &bGotMax );
        if( ! (bGotMin && bGotMax) )
            GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);

        printf( "Min=%.3fd, Max=%.3f\n", adfMinMax[0], adfMinMax[1] );
        
        if( poBand->GetOverviewCount() > 0 )
            printf( "Band has %d overviews.\n", poBand->GetOverviewCount() );

        if( poBand->GetColorTable() != NULL )
            printf( "Band has a color table with %d entries.\n", 
                     poBand->GetColorTable()->GetColorEntryCount() );

		DataFormat * pafScanline;
        int   nXSize = poBand->GetXSize();
		int   nYSize = poBand->GetYSize();
		boost::shared_ptr<Map_Matrix<DataFormat> > in_map(new Map_Matrix<DataFormat>(nYSize, nXSize));
		//get a c array of this size and read into this.
		
		
		//pafScanline = new DataFormat[nXSize];
		//for (int i = 0; i < nYSize; i++) //rows
		//{
		//	poBand->RasterIO(GF_Read, 0, i, nXSize, 1,
		//		pafScanline, nXSize, 1, data_type,
		//		0, 0);
		//	for (int j = 0; j < nXSize; j++) //cols
		//	{
		//		in_map->Get(i, j) = pafScanline[j];
		//	}
		//}
    
        //get a c array of this size and read into this.
        pafScanline = new DataFormat[nXSize * nYSize];
        //pafScanline = (float *) CPLMalloc(sizeof(float)*nXSize);
        poBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			pafScanline, nXSize, nYSize, data_type,
                          0, 0 );
    
        //Copy into Map_Matrix.
        int pafIterator = 0;
		// Note: Map Matrixes indexes are in opposite order to C arrays. e.g. map matrix is indexed by (row, Col) which is (y, x) and c matrices are done by (x, y) which is (Col, Row)
        
        //for (int i = 0; i < nXSize; i++)
        //{
        //    for(int j = 0; j < nYSize; j++)
        //    {
        //        in_map->Get(j, i) = pafScanline[pafIterator];
        //        pafIterator++;
        //    }
        //}		
		for (int i = 0; i < nYSize; i++) //rows
		{
			for (int j = 0; j < nXSize; j++) //cols
			{
				in_map->Get(i, j) = pafScanline[pafIterator];
				pafIterator++;
			}
		}


    
    //free the c array storage
    delete pafScanline;
    int pbsuccess; // can be used with get no data value
    in_map->SetNoDataValue(poBand->GetNoDataValue(&pbsuccess));
    //This creates a list (map?) listing all the unique values contained in the raster.
	if (doCategorise) in_map->updateCategories();

    
	//Close GDAL, freeing the memory GDAL is using
	GDALClose( (GDALDatasetH)poDataset);

    return (std::make_tuple(in_map, projection, transformation));
}
Exemplo n.º 26
0
void readFrames( int argc, char* argv[] )
{
  pfs::DOMIO pfsio;

  bool verbose = false;
  
  // Parse command line parameters
  static struct option cmdLineOptions[] = {
    { "help", no_argument, NULL, 'h' },
    { "verbose", no_argument, NULL, 'v' },
    { NULL, 0, NULL, 0 }
  };
  static const char optstring[] = "hv";
    
  pfs::FrameFileIterator it( argc, argv, "rb", NULL, NULL,
    optstring, cmdLineOptions );
    
  int optionIndex = 0;
  while( 1 ) {
    int c = getopt_long (argc, argv, optstring, cmdLineOptions, &optionIndex);
    if( c == -1 ) break;
    switch( c ) {
    case 'h':
      printHelp();
      throw QuietException();
    case 'v':
      verbose = true;
      break;
    case '?':
      throw QuietException();
    case ':':
      throw QuietException();
    }
  }

  GDALAllRegister();

  GDALDataset *poDataset;
  GDALRasterBand *poBand;
  double adfGeoTransform[6];
  size_t nBlockXSize, nBlockYSize, nBands;
  int bGotMin, bGotMax;
  double adfMinMax[2];
  float *pafScanline;

  while( true ) {
    pfs::FrameFile ff = it.getNextFrameFile();
    if( ff.fh == NULL ) break; // No more frames
    it.closeFrameFile( ff );

    VERBOSE_STR << "reading file '" << ff.fileName << "'" << std::endl;
    if( !( poDataset = (GDALDataset *) GDALOpen( ff.fileName, GA_ReadOnly ) ) ) {
      std::cerr << "input does not seem to be in a format supported by GDAL" << std::endl;
      throw QuietException();
    }
    VERBOSE_STR << "GDAL driver: " << poDataset->GetDriver()->GetDescription()
	<< " / " << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl;
    nBlockXSize = poDataset->GetRasterXSize();
    nBlockYSize = poDataset->GetRasterYSize();
    nBands = poDataset->GetRasterCount();
    VERBOSE_STR << "Data size " << nBlockXSize << "x" << nBlockYSize << "x" << nBands << std::endl;
    if( poDataset->GetProjectionRef() ) {
      VERBOSE_STR << "Projection " << poDataset->GetProjectionRef() << std::endl;
    }
    if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) {
      VERBOSE_STR << "Origin = (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl;
      VERBOSE_STR << "Pixel Size = (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << ")" << std::endl;
    }

    if( nBlockXSize==0  || nBlockYSize==0 
	    || ( SIZE_MAX / nBlockYSize < nBlockXSize ) 
	    || ( SIZE_MAX / (nBlockXSize * nBlockYSize ) < 4 ) ) {
      std::cerr << "input data has invalid size" << std::endl;
      throw QuietException();
    }
    if( !(pafScanline = (float *) CPLMalloc( sizeof(float) * nBlockXSize ) ) ) {
      std::cerr << "not enough memory" << std::endl;
      throw QuietException();
    }

    pfs::Frame *frame = pfsio.createFrame( nBlockXSize, nBlockYSize );
    pfs::Channel *C[nBands];
    char channel_name[32];

    frame->getTags()->setString( "X-GDAL_DRIVER_SHORTNAME", poDataset->GetDriver()->GetDescription() );
    frame->getTags()->setString( "X-GDAL_DRIVER_LONGNAME", poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );
    frame->getTags()->setString( "X-PROJECTION", poDataset->GetProjectionRef() );
    if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) {
      frame->getTags()->setString( "X-ORIGIN_X", stringify(adfGeoTransform[0]).c_str() );
      frame->getTags()->setString( "X-ORIGIN_Y", stringify(adfGeoTransform[3]).c_str() );
      frame->getTags()->setString( "X-PIXEL_WIDTH", stringify(adfGeoTransform[1]).c_str() );
      frame->getTags()->setString( "X-PIXEL_HEIGHT", stringify(adfGeoTransform[5]).c_str() );
    }

    for ( size_t band = 1; band <= nBands; band++) {
      size_t nBandXSize, nBandYSize;
      VERBOSE_STR << "Band " << band << ": " << std::endl;
      snprintf( channel_name, 32, "X-GDAL%zu", band );
      C[band - 1] = frame->createChannel( channel_name );
      poBand = poDataset->GetRasterBand( band );
      nBandXSize = poBand->GetXSize();
      nBandYSize = poBand->GetYSize();
      VERBOSE_STR << "    " << nBandXSize << "x" << nBandYSize << std::endl;
      if( nBandXSize != (int)nBlockXSize || nBandYSize != (int)nBlockYSize ) {
        std::cerr << "data in band " << band << " has different size" << std::endl;
        throw QuietException();
      }
      VERBOSE_STR << "    Type " << GDALGetDataTypeName( poBand->GetRasterDataType() ) << ", "
	  << "Color Interpretation " << GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) << std::endl;
      adfMinMax[0] = poBand->GetMinimum( &bGotMin );
      adfMinMax[1] = poBand->GetMaximum( &bGotMax );
      if( ! (bGotMin && bGotMax) ) {
      	  GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
      }
      VERBOSE_STR << "    Min " << adfMinMax[0] << ", Max " << adfMinMax[1] << std::endl;
      C[band - 1]->getTags()->setString( "X-TYPE", 
	      GDALGetDataTypeName( poBand->GetRasterDataType() ) );
      C[band - 1]->getTags()->setString( "X-COLOR_INTERPRETATION", 
	      GDALGetColorInterpretationName( poBand->GetColorInterpretation() ) );
      C[band - 1]->getTags()->setString( "X-MIN", stringify(adfMinMax[0]).c_str() );
      C[band - 1]->getTags()->setString( "X-MAX", stringify(adfMinMax[1]).c_str() );
      for( size_t y = 0; y < nBlockYSize; y++ ) {
        if( poBand->RasterIO( GF_Read, 0, y, nBlockXSize, 1, pafScanline, 
		    nBlockXSize, 1, GDT_Float32, 0, 0) != CE_None ) {
          std::cerr << "input error" << std::endl;
          throw QuietException();
	}
	memcpy( C[band - 1]->getRawData() + y * nBlockXSize, pafScanline, nBlockXSize * sizeof(float) );
      }
    }
    CPLFree( pafScanline );
    GDALClose( poDataset );

    const char *fileNameTag = strcmp( "-", ff.fileName )==0 ? "stdin" : ff.fileName;
    frame->getTags()->setString( "FILE_NAME", fileNameTag );
        
    pfsio.writeFrame( frame, stdout );
    pfsio.freeFrame( frame );
  }
}
Exemplo n.º 27
0
gdal_datasource::gdal_datasource(parameters const& params)
    : datasource(params),
      desc_(gdal_datasource::name(), "utf-8"),
      nodata_value_(params.get<double>("nodata")),
      nodata_tolerance_(*params.get<double>("nodata_tolerance",1e-12))
{
    MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource: Initializing...";

#ifdef MAPNIK_STATS
    mapnik::progress_timer __stats__(std::clog, "gdal_datasource::init");
#endif

    GDALAllRegister();

    boost::optional<std::string> file = params.get<std::string>("file");
    if (! file) throw datasource_exception("missing <file> parameter");

    boost::optional<std::string> base = params.get<std::string>("base");
    if (base)
    {
        dataset_name_ = *base + "/" + *file;
    }
    else
    {
        dataset_name_ = *file;
    }

    shared_dataset_ = *params.get<mapnik::boolean_type>("shared", false);
    band_ = *params.get<mapnik::value_integer>("band", -1);

    GDALDataset *dataset = open_dataset();

    nbands_ = dataset->GetRasterCount();
    width_ = dataset->GetRasterXSize();
    height_ = dataset->GetRasterYSize();
    desc_.add_descriptor(mapnik::attribute_descriptor("nodata", mapnik::Double));

    double tr[6];
    bool bbox_override = false;
    boost::optional<std::string> bbox_s = params.get<std::string>("extent");
    if (bbox_s)
    {
        MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource: BBox Parameter=" << *bbox_s;

        bbox_override = extent_.from_string(*bbox_s);
        if (! bbox_override)
        {
            throw datasource_exception("GDAL Plugin: bbox parameter '" + *bbox_s + "' invalid");
        }
    }

    if (bbox_override)
    {
        tr[0] = extent_.minx();
        tr[1] = extent_.width() / (double)width_;
        tr[2] = 0;
        tr[3] = extent_.maxy();
        tr[4] = 0;
        tr[5] = -extent_.height() / (double)height_;
        MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource extent override gives Geotransform="
                               << tr[0] << "," << tr[1] << ","
                               << tr[2] << "," << tr[3] << ","
                               << tr[4] << "," << tr[5];
    }
    else
    {
        if (dataset->GetGeoTransform(tr) != CPLE_None)
        {
            MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource GetGeotransform failure gives="
                                   << tr[0] << "," << tr[1] << ","
                                   << tr[2] << "," << tr[3] << ","
                                   << tr[4] << "," << tr[5];
        }
        else
        {
            MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource Geotransform="
                                   << tr[0] << "," << tr[1] << ","
                                   << tr[2] << "," << tr[3] << ","
                                   << tr[4] << "," << tr[5];
        }
    }

    // TODO - We should throw for true non-north up images, but the check
    // below is clearly too restrictive.
    // https://github.com/mapnik/mapnik/issues/970
    /*
      if (tr[2] != 0 || tr[4] != 0)
      {
      throw datasource_exception("GDAL Plugin: only 'north up' images are supported");
      }
    */

    dx_ = tr[1];
    dy_ = tr[5];

    if (! bbox_override)
    {
        double x0 = tr[0];
        double y0 = tr[3];
        double x1 = tr[0] + width_ * dx_ + height_ *tr[2];
        double y1 = tr[3] + width_ *tr[4] + height_ * dy_;

        /*
          double x0 = tr[0] + (height_) * tr[2]; // minx
          double y0 = tr[3] + (height_) * tr[5]; // miny

          double x1 = tr[0] + (width_) * tr[1]; // maxx
          double y1 = tr[3] + (width_) * tr[4]; // maxy
        */

        extent_.init(x0, y0, x1, y1);
    }

    GDALClose(dataset);

    MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource: Raster Size=" << width_ << "," << height_;
    MAPNIK_LOG_DEBUG(gdal) << "gdal_datasource: Raster Extent=" << extent_;

}
Exemplo n.º 28
0
void gdal_datasource::bind() const
{
    if (is_bound_) return;

    shared_dataset_ = *params_.get<mapnik::boolean>("shared", false);
    band_ = *params_.get<int>("band", -1);

    GDALDataset *dataset = open_dataset();

    nbands_ = dataset->GetRasterCount();
    width_ = dataset->GetRasterXSize();
    height_ = dataset->GetRasterYSize();

    double tr[6];
    bool bbox_override = false;
    boost::optional<std::string> bbox_s = params_.get<std::string>("bbox");
    if (bbox_s)
    {
#ifdef MAPNIK_DEBUG
        std::clog << "GDAL Plugin: bbox parameter=" << *bbox_s << std::endl;
#endif

        bbox_override = extent_.from_string(*bbox_s);
        if (! bbox_override)
        {
            throw datasource_exception("GDAL Plugin: bbox parameter '" + *bbox_s + "' invalid");
        }
    }

    if (bbox_override)
    {
        tr[0] = extent_.minx();
        tr[1] = extent_.width() / (double)width_;
        tr[2] = 0;
        tr[3] = extent_.maxy();
        tr[4] = 0;
        tr[5] = -extent_.height() / (double)height_;
    }
    else
    {
        dataset->GetGeoTransform(tr);
    }

#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: geotransform=" << tr[0] << "," << tr[1] << ","
              << tr[2] << "," << tr[3] << ","
              << tr[4] << "," << tr[5] << std::endl;
#endif

    // TODO - We should throw for true non-north up images, but the check
    // below is clearly too restrictive.
    // https://github.com/mapnik/mapnik/issues/970
    /*
    if (tr[2] != 0 || tr[4] != 0)
    {
        throw datasource_exception("GDAL Plugin: only 'north up' images are supported");
    }
    */

    dx_ = tr[1];
    dy_ = tr[5];

    if (! bbox_override)
    {
        double x0 = tr[0];
        double y0 = tr[3];
        double x1 = tr[0] + width_ * dx_ + height_ *tr[2];
        double y1 = tr[3] + width_ *tr[4] + height_ * dy_;

        /*
          double x0 = tr[0] + (height_) * tr[2]; // minx
          double y0 = tr[3] + (height_) * tr[5]; // miny

          double x1 = tr[0] + (width_) * tr[1]; // maxx
          double y1 = tr[3] + (width_) * tr[4]; // maxy
        */

        extent_.init(x0, y0, x1, y1);
    }

    GDALClose(dataset);

#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: Raster Size=" << width_ << "," << height_ << std::endl;
    std::clog << "GDAL Plugin: Raster Extent=" << extent_ << std::endl;
#endif

    is_bound_ = true;
}
Exemplo n.º 29
0
void clsRasterData::ReadFromGDAL(string filename)
{
	GDALDataset  *poDataset = (GDALDataset *) GDALOpen( filename.c_str(), GA_ReadOnly );
	if( poDataset == NULL )
	{
		cerr << "Open file " + filename + " failed.\n";
		return;
	}

	GDALRasterBand  *poBand= poDataset->GetRasterBand(1);
	m_headers["NCOLS"] = poBand->GetXSize();
	m_headers["NROWS"] = poBand->GetYSize();
	m_headers["NODATA_VALUE"] = (float)poBand->GetNoDataValue();
	double adfGeoTransform[6];
	poDataset->GetGeoTransform(adfGeoTransform);
	m_headers["CELLSIZE"] = adfGeoTransform[1];
	//m_headers["DY"] = -adfGeoTransform[5];
	m_headers["XLLCENTER"] = adfGeoTransform[0] + 0.5f*m_headers["CELLSIZE"];
	m_headers["YLLCENTER"] = adfGeoTransform[3] + (m_headers["NROWS"] - 0.5f)*m_headers["CELLSIZE"];

	int nRows = (int)m_headers["NROWS"];
	int nCols = (int)m_headers["NCOLS"];

	vector<float> values;
	vector<int> positionRows;
	vector<int> positionCols;
	//get all valid values
	float tempFloat = m_headers["NODATA_VALUE"];

	GDALDataType dataType = poBand->GetRasterDataType();
	if (dataType == GDT_Float32)
	{
		float *pData = (float *) CPLMalloc(sizeof(float)*nCols*nRows);
		poBand->RasterIO(GF_Read, 0, 0, nCols, nRows, pData, nCols, nRows, GDT_Float32, 0, 0);
		for (int i = 0; i < nRows; ++i)
		{
			for (int j = 0; j < nCols; ++j)
			{
				int index = i*nCols + j;
				if(FloatEqual(pData[index], m_headers["NODATA_VALUE"]) )
					continue;
				values.push_back(pData[index]);
				positionRows.push_back(i);
				positionCols.push_back(j);
			}
		}
		CPLFree(pData);
	}
	else if (dataType == GDT_Int32)
	{
		int *pData = (int *) CPLMalloc(sizeof(int)*nCols*nRows);
		poBand->RasterIO(GF_Read, 0, 0, nCols, nRows, pData, nCols, nRows, GDT_Int32, 0, 0);
		for (int i = 0; i < nRows; ++i)
		{
			for (int j = 0; j < nCols; ++j)
			{
				int index = i*nCols + j;
				if(FloatEqual(pData[index], m_headers["NODATA_VALUE"]) )
					continue;
				values.push_back(pData[index]);
				positionRows.push_back(i);
				positionCols.push_back(j);
			}
		}
		CPLFree(pData);
	}
	else
	{
		throw ModelException("clsRasterData","ReadFromGDAL","The dataype of " + filename + " is neither GDT_Float32 nor GDT_Int32.");
	}

	GDALClose(poDataset);

	//create float array
	m_nRows = values.size();
	m_rasterData = new float[m_nRows];
	m_rasterPositionData = new float*[m_nRows];
	for (int i = 0; i < m_nRows; ++i)
	{
		m_rasterData[i] = values.at(i);
		m_rasterPositionData[i] = new float[2];
		m_rasterPositionData[i][0] = float(positionRows.at(i));
		m_rasterPositionData[i][1] = float(positionCols.at(i));
	}
}
Exemplo n.º 30
0
	//virtual method that will be executed                                                                                                           
	void executeAlgorithm(AlgorithmData& data, AlgorithmContext& context) 
	{		
		
		//****define algorithm here****
		//open native message block	
		std::string nativeHdr="\n*************************NATIVE_OUTPUT*************************\n"; 
		std::cout<<nativeHdr<<std::endl;
		
		//open image files
		// input/output directory names specified in configuration file
		Dataset* input = data.getInputDataset("imagesIn");
		Dataset* output = data.getOutputDataset("imagesOut");
		
		//get keyspace elements (files in directory by dimension)
		Keyspace keyspace = data.getKeyspace();
		std::vector<DataKeyElement> names = keyspace.getKeyspaceDimension(DataKeyDimension("NAME")).getElements();
			
		
		//... iterate through keys and do work ...
		for ( std::vector<DataKeyElement>::iterator n=names.begin(); n != names.end(); n++ )
		{
			//print dimension name to stdout
			std::cout<<*n<<std::endl;
			
			//get multispectral data
			DataKey skyKey = *n;
			DataFile* skyFile = input->getDataFile(skyKey);
			
			//unique name for an in-memory GDAL file
			std::string inputFileName = skyKey.toName("__")+"_input";
		
			//get gdal dataset
			GDALMemoryFile inputMemFile(inputFileName, *skyFile);
			GDALDataset * skyDataset = inputMemFile.getGDALDataset();
			
			//get gdal bands
			GDALRasterBand * blueBand = skyDataset->GetRasterBand(1);
			GDALRasterBand * greenBand = skyDataset->GetRasterBand(2);
			GDALRasterBand * redBand = skyDataset->GetRasterBand(3);
			GDALRasterBand * nirBand = skyDataset->GetRasterBand(4);
				
			//create memory buffers to hold bands
			int nXSize = redBand->GetXSize();
			int nYSize = redBand->GetYSize();
			uint16_t * bufferBlue = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize);
			uint16_t * bufferGreen = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize);
			uint16_t * bufferRed = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize);
			uint16_t * bufferNIR = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize);
			//output
			uint16_t * bufferClass = (uint16_t *) CPLMalloc(sizeof(uint16_t)*nXSize*nYSize);
			
			//gdal read bands into buffer
			blueBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			              bufferBlue, nXSize , nYSize, GDT_UInt16, 0, 0 );
			greenBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			              bufferGreen, nXSize , nYSize, GDT_UInt16, 0, 0 );
			redBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			              bufferRed, nXSize , nYSize, GDT_UInt16, 0, 0 );
			nirBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, 
			              bufferNIR, nXSize , nYSize, GDT_UInt16, 0, 0 );
	
			
			//classify pixels
			for (int i=0 ; i < nXSize*nYSize ; i++ )
			{				
				//unclassified
				uint16_t pixelClass = 0;
				if (bufferBlue[i]>0 && bufferGreen[i]>0 && bufferRed[i]>0 && bufferNIR[i]>0 )
				{
					//ground
					pixelClass = 1;
					
					//classify pixels
					double ndvi = ((double)bufferNIR[i]-(double)bufferRed[i])/((double)bufferNIR[i]+(double)bufferRed[i]);
					double water = ((double)bufferBlue[i]-(double)bufferRed[i])/(double)(bufferRed[i]+(double)bufferBlue[i]);
					
					if ( ndvi>0.1 )
					{
						//vegetation
						pixelClass = 128;
					}
					else if (water > 0.1 )
					{
						//water
						pixelClass = 256;
					}
				}
				//write to buffer
				bufferClass[i]=pixelClass;
						
			}
			
			// create in memory storage for GDAL output file
			std::string outputFileName = skyKey.toName("__")+"_output";
			GDALMemoryFile outMemFile(outputFileName);
		
			// create the output dataset
			GDALDataset* outDataset = newGDALDataset(
				outMemFile.getPath(),
				"Gtiff",
				nXSize,
				nYSize,
				1, // 1 band
				GDT_UInt16
			);
			outMemFile.setGDALDataset(outDataset);
			
			// Write results into a band
			GDALRasterBand * gBand = outDataset->GetRasterBand(1);
			gBand->RasterIO( GF_Write, 0, 0, nXSize, nYSize,
				bufferClass, nXSize, nYSize, GDT_UInt16,0,0 );
		
			// copy metadata
			double adfGeoTransform[6];
			const char * projection = skyDataset->GetProjectionRef();
			outDataset->SetProjection(projection);
			skyDataset->GetGeoTransform( adfGeoTransform );
			outDataset->SetGeoTransform( adfGeoTransform );
		
			// close the files
			inputMemFile.close();
			outMemFile.close();
			
			// output file in the output folder
			DataKey outKey = DataKey(*n);
			DataFile* fileData = outMemFile.toDataFile("image/tif");
			output->addDataFile(outKey, fileData);
		
			//close message block		
			std::cout<<nativeHdr<<std::endl;
				
			//free buffers
			CPLFree(bufferBlue);
			CPLFree(bufferGreen);
			CPLFree(bufferRed);
			CPLFree(bufferNIR);
			CPLFree(bufferClass);
		}
	}