Ejemplo n.º 1
0
bool getRawValuesFromFile(string fname,vector<vector<float>>& vecs)
{
   
   //vector<float> temp = vector<float>()
   GDALDataset *poDataset;
   GDALAllRegister();
   poDataset= (GDALDataset*) GDALOpen(fname.c_str(),GA_ReadOnly);
   if(poDataset == NULL)
   {
      cout << "OUCH!" << endl;
      return false;
   }
   cout << "Data size: " << GDALGetRasterXSize(poDataset) << " " << GDALGetRasterYSize(poDataset) << endl;

   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);
   int width = poBand->GetXSize(); 
   int height = poBand->GetYSize();
   int bands = poDataset->GetRasterCount();
   float *pafScanline;
   std::cout << "Before allocation" << adfMinMax[0] << " " << adfMinMax[1] << endl;
   int dsize = 256;
   pafScanline = (float *) CPLMalloc(sizeof(float)*width*height);
   vector<vector<float>> out = vector<vector<float>>(height,vector<float> (width,0));
   poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,width,height,GDT_Float32,0,0);
   cout << "After allocation" << endl;
   for(int i = 0; i < height; i++)
   {
    for(int j = 0; j < width; j++)
    {
      //cout << i << j << endl << pafS;
      out[i][j] = pafScanline[i*width+j];
    }
   }
   CPLFree(pafScanline);
   //for(auto i : out)
   //for(auto j : i)
   //		cout << j << endl;
  cout << "After allocation" << endl;
  vecs = out;
   return true;
}
Ejemplo n.º 2
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;
	}


}
Ejemplo n.º 3
0
void HypSpecImage::bounds(int band, float *min, float *max)
{
    GDALRasterBand *raster = m_data->GetRasterBand(band);
    int bGotMin, bGotMax;
    *min = raster->GetMinimum(&bGotMin);
    *max = raster->GetMaximum(&bGotMax);
    if(!(bGotMin && bGotMax)) {
        double adfMinMax[2];
        GDALComputeRasterMinMax((GDALRasterBandH) raster, TRUE, adfMinMax);
        *min = adfMinMax[0];
        *max = adfMinMax[1];
    }
}
Ejemplo n.º 4
0
SEXP
RGDAL_GetBandMaximum(SEXP sxpRasterBand) {

  SEXP ans;

  GDALRasterBand *pRasterBand = getGDALRasterPtr(sxpRasterBand);
  PROTECT(ans = NEW_NUMERIC(1));

  installErrorHandler();
  NUMERIC_POINTER(ans)[0] = (double) pRasterBand->GetMaximum();
  uninstallErrorHandlerAndTriggerError();

  UNPROTECT(1);
  return(ans);
}
Ejemplo n.º 5
0
bool Slic::_InitData()
{
    // Check the params
    if (_poSrcDS == NULL|| _poDstDS == NULL)
    {
        std::cerr<<"Input image or output image invalid !"<<std::endl;
        return false;
    }

    if (_regionSize<0 || _regularizer<0)
    {
        std::cerr<<"Parameter regionSize and regularizer must bigger than 0!"<<std::endl;
        return false;
    }

    // Init some vars
    _M = static_cast<int> (static_cast<double>(_width)  / _regionSize + 0.5);
    _N = static_cast<int> (static_cast<double>(_height) / _regionSize + 0.5);

    // Init normalization params
    for (int k=0;k<_bandCount;++k)
    {
        GDALRasterBand* poBand =  _poSrcDS->GetRasterBand(k+1);
        int     bGotMin, bGotMax;
        double  adfMinMax[2];
        adfMinMax[0] = poBand->GetMinimum( &bGotMin );
        adfMinMax[1] = poBand->GetMaximum( &bGotMax );
        if( ! (bGotMin && bGotMax) )
            GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
        std::vector<double>  adfNormalizationParam(2);
        adfNormalizationParam[0] = 1./(adfMinMax[1]-adfMinMax[0]);
        adfNormalizationParam[1] = adfMinMax[0]/(adfMinMax[1]-adfMinMax[0]);
        _normalizationParam.push_back(adfNormalizationParam);
    }

    // Init centers
    for (int i=_regionSize/2;i<_height ;i+=_regionSize)
    {
        for (int j=_regionSize/2;j<_width ;j += _regionSize)
        {
            FeatureVector featureVec;
            _InitCenterFeature(i,j,featureVec);
            _centerVector.push_back(featureVec);
        }
    }

    return true;
}
Ejemplo n.º 6
0
void Create8BitImage(const char *srcfile,const char *dstfile)
{
	GDALAllRegister();
	CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO");
	GDALDataset *pDataset=(GDALDataset *) GDALOpen( srcfile, GA_ReadOnly );
	int bandNum=pDataset->GetRasterCount();

	GDALDriver *pDriver=GetGDALDriverManager()->GetDriverByName("GTiff");
	GDALDataset *dstDataset=pDriver->Create(dstfile,800,800,3,GDT_Byte,NULL);
	GDALRasterBand *pBand;
	GDALRasterBand *dstBand;
	//写入光栅数据
	ushort *sbuf= new ushort[800*800];
	uchar *cbuf=new uchar[800*800];
	for (int i=bandNum,j=1;i>=2;i--,j++)
	{
		pBand=pDataset->GetRasterBand(i);
		pBand->RasterIO(GF_Read,0,0,800,800,sbuf,800,800,GDT_UInt16,0,0);
		int bGotMin, bGotMax;
		double adfMinMax[2];
		adfMinMax[0] = pBand->GetMinimum( &bGotMin );
		adfMinMax[1] = pBand->GetMaximum( &bGotMax );
		if( ! (bGotMin && bGotMax) )
			GDALComputeRasterMinMax((GDALRasterBandH)pBand, TRUE, adfMinMax);
		MinMaxStretch(sbuf,cbuf,800,800,adfMinMax[0],adfMinMax[1]);
		/*double min,max;
		HistogramAccumlateMinMax16S(sbuf,800,800,&min,&max);
		MinMaxStretchNew(sbuf,cbuf,800,800,min,max);*/
		dstBand=dstDataset->GetRasterBand(j);
		dstBand->RasterIO(GF_Write,0,0,800,800,cbuf,800,800,GDT_Byte,0,0);
	}
	delete []cbuf;
	delete []sbuf;
	GDALClose(pDataset);
	GDALClose(dstDataset);
}
Ejemplo n.º 7
0
bool GdalAdapter::loadImage(const QString& fn)
{
    if (alreadyLoaded(fn))
        return true;

    QFileInfo fi(fn);
    GdalImage img;
    QRectF bbox;

    poDataset = (GDALDataset *) GDALOpen( QDir::toNativeSeparators(fi.absoluteFilePath()).toUtf8().constData(), GA_ReadOnly );
    if( poDataset == NULL )
    {
        qDebug() <<  "GDAL Open failed: " << fn;
        return false;
    }

    bool hasGeo = false;
    QDir dir(fi.absoluteDir());
    QString f = fi.baseName();
    QStringList wldFilter;
    wldFilter <<  f+".tfw" << f+".tifw" << f+".tiffw" << f+".wld";
    QFileInfoList fil = dir.entryInfoList(wldFilter);
    if (fil.count()) {
        QFile wld(fil[0].absoluteFilePath());
        if (wld.open(QIODevice::ReadOnly)) {
            int i;
            for (i=0; i<6; ++i) {
                if (wld.atEnd())
                    break;
                QString l = wld.readLine();
                bool ok;
                double d = l.toDouble(&ok);
                if (!ok)
                    break;
                switch (i) {
                case 0:
                    img.adfGeoTransform[1] = d;
                    break;
                case 1:
                    img.adfGeoTransform[4] = d;
                    break;
                case 2:
                    img.adfGeoTransform[2] = d;
                    break;
                case 3:
                    img.adfGeoTransform[5] = d;
                    break;
                case 4:
                    img.adfGeoTransform[0] = d;
                    break;
                case 5:
                    img.adfGeoTransform[3] = d;
                    break;
                }

            }
            if (i == 6)
                hasGeo = true;
        }
    }
    if(!hasGeo)
        if ( poDataset->GetGeoTransform( img.adfGeoTransform ) != CE_None ) {
            GDALClose((GDALDatasetH)poDataset);
            return false;
        }

    qDebug( "Origin = (%.6f,%.6f)\n",
            img.adfGeoTransform[0], img.adfGeoTransform[3] );

    qDebug( "Pixel Size = (%.6f,%.6f)\n",
            img.adfGeoTransform[1], img.adfGeoTransform[5] );

    bbox.setTopLeft(QPointF(img.adfGeoTransform[0], img.adfGeoTransform[3]));
    bbox.setWidth(img.adfGeoTransform[1]*poDataset->GetRasterXSize());
    bbox.setHeight(img.adfGeoTransform[5]*poDataset->GetRasterYSize());

    isLatLon = false;
    if( strlen(poDataset->GetProjectionRef()) != 0 ) {
        qDebug( "Projection is `%s'\n", poDataset->GetProjectionRef() );
        OGRSpatialReference* theSrs = new OGRSpatialReference(poDataset->GetProjectionRef());
        if (theSrs && theSrs->Validate() == OGRERR_NONE) {
            theSrs->morphFromESRI();
            char* theProj4;
            if (theSrs->exportToProj4(&theProj4) == OGRERR_NONE) {
                qDebug() << "GDAL: to proj4 : " << theProj4;
            } else {
                qDebug() << "GDAL: to proj4 error: " << CPLGetLastErrorMsg();
                GDALClose((GDALDatasetH)poDataset);
                return false;
            }
            QString srsProj = QString(theProj4);
            if (!srsProj.isEmpty() && theProjection != srsProj) {
                cleanup();
                theProjection = srsProj;
            }
            isLatLon = (theSrs->IsGeographic() == TRUE);
        }
    }
    if (theProjection.isEmpty()) {
        theProjection = ProjectionChooser::getProjection(QCoreApplication::translate("ImportExportGdal", "Unable to set projection; please specify one"));
        if (theProjection.isEmpty()) {
            GDALClose((GDALDatasetH)poDataset);
            return false;
        }
    }

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

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

    GdalAdapter::ImgType theType = GdalAdapter::Unknown;
    int bandCount = poDataset->GetRasterCount();
    int ixA = -1;
    int ixR, ixG, ixB;
    int ixH, ixS, ixL;
    int ixC, ixM, ixY, ixK;
    int ixYuvY, ixYuvU, ixYuvV;
    double adfMinMax[2];
    double UnknownUnit;
    GDALColorTable* colTable = NULL;
    for (int i=0; i<bandCount; ++i) {
        GDALRasterBand  *poBand = poDataset->GetRasterBand( i+1 );
        GDALColorInterp bandtype = poBand->GetColorInterpretation();
        qDebug() << "Band " << i+1 << " Color: " <<  GDALGetColorInterpretationName(poBand->GetColorInterpretation());

        switch (bandtype)
        {
        case GCI_Undefined:
            theType = GdalAdapter::Unknown;
            int             bGotMin, bGotMax;
            adfMinMax[0] = poBand->GetMinimum( &bGotMin );
            adfMinMax[1] = poBand->GetMaximum( &bGotMax );
            if( ! (bGotMin && bGotMax) )
                GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
            UnknownUnit = (adfMinMax[1] - adfMinMax[0]) / 256;
            break;
        case GCI_GrayIndex:
            theType = GdalAdapter::GrayScale;
            break;
        case GCI_RedBand:
            theType = GdalAdapter::Rgb;
            ixR = i;
            break;
        case GCI_GreenBand:
            theType = GdalAdapter::Rgb;
            ixG = i;
            break;
        case GCI_BlueBand :
            theType = GdalAdapter::Rgb;
            ixB = i;
            break;
        case GCI_HueBand:
            theType = GdalAdapter::Hsl;
            ixH = i;
            break;
        case GCI_SaturationBand:
            theType = GdalAdapter::Hsl;
            ixS = i;
            break;
        case GCI_LightnessBand:
            theType = GdalAdapter::Hsl;
            ixL = i;
            break;
        case GCI_CyanBand:
            theType = GdalAdapter::Cmyk;
            ixC = i;
            break;
        case GCI_MagentaBand:
            theType = GdalAdapter::Cmyk;
            ixM = i;
            break;
        case GCI_YellowBand:
            theType = GdalAdapter::Cmyk;
            ixY = i;
            break;
        case GCI_BlackBand:
            theType = GdalAdapter::Cmyk;
            ixK = i;
            break;
        case GCI_YCbCr_YBand:
            theType = GdalAdapter::YUV;
            ixYuvY = i;
            break;
        case GCI_YCbCr_CbBand:
            theType = GdalAdapter::YUV;
            ixYuvU = i;
            break;
        case GCI_YCbCr_CrBand:
            theType = GdalAdapter::YUV;
            ixYuvV = i;
            break;
        case GCI_AlphaBand:
            ixA = i;
            break;
        case GCI_PaletteIndex:
            colTable = poBand->GetColorTable();
            switch (colTable->GetPaletteInterpretation())
            {
            case GPI_Gray :
                theType = GdalAdapter::Palette_Gray;
                break;
            case GPI_RGB :
                theType = GdalAdapter::Palette_RGBA;
                break;
            case GPI_CMYK :
                theType = GdalAdapter::Palette_CMYK;
                break;
            case GPI_HLS :
                theType = GdalAdapter::Palette_HLS;
                break;
            }
            break;
        }
    }

    QSize theImgSize(poDataset->GetRasterXSize(), poDataset->GetRasterYSize());
    QImage theImg = QImage(theImgSize, QImage::Format_ARGB32);

    // Make sure that lineBuf holds one whole line of data.
    float *lineBuf;
    lineBuf = (float *) CPLMalloc(theImgSize.width() * bandCount * sizeof(float));

    int px, py;
    //every row loop
    for (int row = 0; row < theImgSize.height(); row++) {
        py = row;
        poDataset->RasterIO( GF_Read, 0, row, theImgSize.width(), 1, lineBuf, theImgSize.width(), 1, GDT_Float32,
                            bandCount, NULL, sizeof(float) * bandCount, 0, sizeof(float) );
        // every pixel in row.
        for (int col = 0; col < theImgSize.width(); col++){
            px = col;
            switch (theType)
            {
            case GdalAdapter::Unknown:
            {
                float* v = lineBuf + (col*bandCount);
                float val = (*v - adfMinMax[0]) / UnknownUnit;
                theImg.setPixel(px, py, qRgb(val, val, val));
                break;
            }
            case GdalAdapter::GrayScale:
            {
                float* v = lineBuf + (col*bandCount);
                theImg.setPixel(px, py, qRgb(*v, *v, *v));
                break;
            }
            case GdalAdapter::Rgb:
            {
                float* r = lineBuf + (col*bandCount) + ixR;
                float* g = lineBuf + (col*bandCount) + ixG;
                float* b = lineBuf + (col*bandCount) + ixB;
                int a = 255;
                if (ixA != -1) {
                    float* fa = lineBuf + (col*bandCount) + ixA;
                    a = *fa;
                }
                theImg.setPixel(px, py, qRgba(*r, *g, *b, a));
                break;
            }
#if QT_VERSION >= 0x040600
            case GdalAdapter::Hsl:
            {
                float* h = lineBuf + (col*bandCount) + ixH;
                float* s = lineBuf + (col*bandCount) + ixS;
                float* l = lineBuf + (col*bandCount) + ixL;
                int a = 255;
                if (ixA != -1) {
                    float* fa = lineBuf + (col*bandCount) + ixA;
                    a = *fa;
                }
                QColor C = QColor::fromHsl(*h, *s, *l, a);
                theImg.setPixel(px, py, C.rgba());
                break;
            }
#endif
            case GdalAdapter::Cmyk:
            {
                float* c = lineBuf + (col*bandCount) + ixC;
                float* m = lineBuf + (col*bandCount) + ixM;
                float* y = lineBuf + (col*bandCount) + ixY;
                float* k = lineBuf + (col*bandCount) + ixK;
                int a = 255;
                if (ixA != -1) {
                    float* fa = lineBuf + (col*bandCount) + ixA;
                    a = *fa;
                }
                QColor C = QColor::fromCmyk(*c, *m, *y, *k, a);
                theImg.setPixel(px, py, C.rgba());
                break;
            }
            case GdalAdapter::YUV:
            {
                // From http://www.fourcc.org/fccyvrgb.php
                float* y = lineBuf + (col*bandCount) + ixYuvY;
                float* u = lineBuf + (col*bandCount) + ixYuvU;
                float* v = lineBuf + (col*bandCount) + ixYuvV;
                int a = 255;
                if (ixA != -1) {
                    float* fa = lineBuf + (col*bandCount) + ixA;
                    a = *fa;
                }
                float R = 1.164*(*y - 16) + 1.596*(*v - 128);
                float G = 1.164*(*y - 16) - 0.813*(*v - 128) - 0.391*(*u - 128);
                float B = 1.164*(*y - 16) + 2.018*(*u - 128);

                theImg.setPixel(px, py, qRgba(R, G, B, a));
                break;
            }
            case GdalAdapter::Palette_Gray:
            {
                float* ix = (lineBuf + (col*bandCount));
                const GDALColorEntry* color = colTable->GetColorEntry(*ix);
                theImg.setPixel(px, py, qRgb(color->c1, color->c1, color->c1));
                break;
            }
            case GdalAdapter::Palette_RGBA:
            {
                float* ix = (lineBuf + (col*bandCount));
                const GDALColorEntry* color = colTable->GetColorEntry(*ix);
                theImg.setPixel(px, py, qRgba(color->c1, color->c2, color->c3, color->c4));
                break;
            }
#if QT_VERSION >= 0x040600
            case GdalAdapter::Palette_HLS:
            {
                float* ix = (lineBuf + (col*bandCount));
                const GDALColorEntry* color = colTable->GetColorEntry(*ix);
                QColor C = QColor::fromHsl(color->c1, color->c2, color->c3, color->c4);
                theImg.setPixel(px, py, C.rgba());
                break;
            }
#endif
            case GdalAdapter::Palette_CMYK:
            {
                float* ix = (lineBuf + (col*bandCount));
                const GDALColorEntry* color = colTable->GetColorEntry(*ix);
                QColor C = QColor::fromCmyk(color->c1, color->c2, color->c3, color->c4);
                theImg.setPixel(px, py, C.rgba());
                break;
            }
            }
        }
        QCoreApplication::processEvents();
    }

    img.theFilename = fn;
    img.theImg = QPixmap::fromImage(theImg);
    theImages.push_back(img);
    theBbox = theBbox.united(bbox);

    GDALClose((GDALDatasetH)poDataset);
    return true;
}
Ejemplo n.º 8
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));
}
bool GDALImageFileType::read(      Image       *OSG_GDAL_ARG(pImage), 
                             const Char8       *OSG_GDAL_ARG(fileName)) 
{
#ifdef OSG_WITH_GDAL
    bool returnValue = false;

    GDALDataset *pDataset;

    pDataset = static_cast<GDALDataset *>(GDALOpen(fileName, GA_ReadOnly));

    if(pDataset != NULL)
    {
        GeoReferenceAttachmentUnrecPtr pGeoRef = 
            GeoReferenceAttachment::create();

        pImage->addAttachment(pGeoRef);

        double        adfGeoTransform[6];
        
        if(pDataset->GetGeoTransform(adfGeoTransform) == CE_None)
        {
            pGeoRef->editOrigin().setValues(adfGeoTransform[0], 
                                            adfGeoTransform[3]);

            pGeoRef->editPixelSize().setValues(adfGeoTransform[1], 
                                               adfGeoTransform[5]);

            if(GDALGetProjectionRef(pDataset) != NULL)
            {
                OGRSpatialReferenceH  hSRS;

                Char8 *szProjection = 
                    const_cast<char *>(GDALGetProjectionRef(pDataset));
        
                hSRS = OSRNewSpatialReference(NULL);

                if(OSRImportFromWkt(hSRS, &szProjection) == CE_None)
                {
                    pGeoRef->editEllipsoidAxis().setValues(
                        OSRGetSemiMajor(hSRS, NULL),
                        OSRGetSemiMinor(hSRS, NULL));

                    const Char8 *szDatum = OSRGetAttrValue(hSRS, "DATUM", 0);

                    if(szDatum != NULL && 0 == strcmp(szDatum, "WGS_1984"))
                    {
                        pGeoRef->editDatum() = 
                            GeoReferenceAttachment::WGS84;
                    }
                    else
                    {
                        fprintf(stderr, "Unknow datum %s\n",
                                szDatum);

                        pGeoRef->editDatum() = 
                            GeoReferenceAttachment::UnknownDatum;
                    }
                }            

                OSRDestroySpatialReference(hSRS);
            }
        }

        GDALRasterBand *pBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];
        
        pBand = pDataset->GetRasterBand( 1 );
        pBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

        adfMinMax[0] = pBand->GetMinimum( &bGotMin );
        adfMinMax[1] = pBand->GetMaximum( &bGotMax );

        if(!(bGotMin && bGotMax))
            GDALComputeRasterMinMax(GDALRasterBandH(pBand), TRUE, adfMinMax);

        pBand = pDataset->GetRasterBand(1);

        if(pBand != NULL)
        {
            Image::PixelFormat ePF = Image::OSG_INVALID_PF;

            switch(pDataset->GetRasterCount())
            {
                case 1:
                    ePF = Image::OSG_L_PF;
                    break;
                case 2:
                    ePF = Image::OSG_LA_PF;
                    break;
                case 3:
                    ePF = Image::OSG_RGB_PF;
                    break;
                case 4:
                    ePF = Image::OSG_RGBA_PF;
                    break;
            }

            Image::Type eDT = Image::OSG_INVALID_IMAGEDATATYPE;

            switch(pBand->GetRasterDataType())
            {
                case GDT_Byte:
                    eDT = Image::OSG_UINT8_IMAGEDATA;
                    break;

                case GDT_UInt16:
                    eDT = Image::OSG_UINT16_IMAGEDATA;
                    break;

                case GDT_Int16:
                    eDT = Image::OSG_INT16_IMAGEDATA;
                    break;

                case GDT_UInt32:
                    eDT = Image::OSG_UINT32_IMAGEDATA;
                    break;

                case GDT_Int32:
                    eDT = Image::OSG_INT32_IMAGEDATA;
                    break;

                case GDT_Float32: 
                    eDT = Image::OSG_FLOAT32_IMAGEDATA;
                    break;

                case GDT_Float64:
                case GDT_CInt16: 
                case GDT_CInt32:
                case GDT_CFloat32:
                case GDT_CFloat64:
                default:
                    GDALClose(pDataset);
                    return returnValue;
                    break;
        
            }

            pImage->set(ePF,             
                        pDataset->GetRasterXSize(), 
                        pDataset->GetRasterYSize(),
                        1,
                        1,
                        1,
                        0.0,
                        NULL,
                        eDT);
            
            UChar8 *dst = pImage->editData();

            pBand->RasterIO(GF_Read,
                            0, 
                            0,
                            pDataset->GetRasterXSize(), 
                            pDataset->GetRasterYSize(),
                            dst,
                            pDataset->GetRasterXSize(), 
                            pDataset->GetRasterYSize(),
                            pBand->GetRasterDataType(),
                            0,
                            0);

            pGeoRef->setNoDataValue(pBand->GetNoDataValue());

            returnValue = true;
        }

        GDALClose(pDataset);
    }

    return returnValue;

#else

    SWARNING << getMimeType()
             << " read is not compiled into the current binary "
             << std::endl;
    return false;

#endif // OSG_WITH_GDAL
}
Ejemplo n.º 10
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 );
  }
}
Ejemplo n.º 11
0
CC_FILE_ERROR RasterGridFilter::loadFile(QString filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/)
{
	GDALAllRegister();
	ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount());

	GDALDataset* poDataset = static_cast<GDALDataset*>(GDALOpen( qPrintable(filename), GA_ReadOnly ));

	if( poDataset != NULL )
	{
		ccLog::Print(QString("Raster file: '%1'").arg(filename));
		ccLog::Print( "Driver: %s/%s",
			poDataset->GetDriver()->GetDescription(), 
			poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );

		int rasterCount = poDataset->GetRasterCount();
		int rasterX = poDataset->GetRasterXSize();
		int rasterY = poDataset->GetRasterYSize();
		ccLog::Print( "Size is %dx%dx%d", rasterX, rasterY, rasterCount );

		ccPointCloud* pc = new ccPointCloud();
		if (!pc->reserve(static_cast<unsigned>(rasterX * rasterY)))
		{
			delete pc;
			return CC_FERR_NOT_ENOUGH_MEMORY;
		}

		if( poDataset->GetProjectionRef() != NULL )
			ccLog::Print( "Projection is `%s'", poDataset->GetProjectionRef() );

		double adfGeoTransform[6] = {	 0, //top left x
										 1, //w-e pixel resolution (can be negative)
										 0, //0
										 0, //top left y
										 0, //0
										 1  //n-s pixel resolution (can be negative)
		};

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

		if (adfGeoTransform[1] == 0 || adfGeoTransform[5] == 0)
		{
			ccLog::Warning("Invalid pixel size! Forcing it to (1,1)");
			adfGeoTransform[1] = adfGeoTransform[5] = 1;
		}

		CCVector3d origin( adfGeoTransform[0], adfGeoTransform[3], 0.0 );
		CCVector3d Pshift(0,0,0);
		//check for 'big' coordinates
		{
			bool shiftAlreadyEnabled = (coordinatesShiftEnabled && *coordinatesShiftEnabled && coordinatesShift);
			if (shiftAlreadyEnabled)
				Pshift = *coordinatesShift;
			bool applyAll = false;
			if (	sizeof(PointCoordinateType) < 8
				&&	ccCoordinatesShiftManager::Handle(origin,0,alwaysDisplayLoadDialog,shiftAlreadyEnabled,Pshift,0,&applyAll))
			{
				pc->setGlobalShift(Pshift);
				ccLog::Warning("[RasterFilter::loadFile] Raster has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z);

				//we save coordinates shift information
				if (applyAll && coordinatesShiftEnabled && coordinatesShift)
				{
					*coordinatesShiftEnabled = true;
					*coordinatesShift = Pshift;
				}
			}
		}

		//create blank raster 'grid'
		{
			double z = 0.0 /*+ Pshift.z*/;
			for (int j=0; j<rasterY; ++j)
			{
				double y = adfGeoTransform[3] + static_cast<double>(j) * adfGeoTransform[5] + Pshift.y;
				CCVector3 P(	0,
								static_cast<PointCoordinateType>(y),
								static_cast<PointCoordinateType>(z));
				for (int i=0; i<rasterX; ++i)
				{
					double x = adfGeoTransform[0] + static_cast<double>(i) * adfGeoTransform[1] + Pshift.x;

					P.x = static_cast<PointCoordinateType>(x);
					pc->addPoint(P);
				}
			}

			QVariant xVar = QVariant::fromValue<int>(rasterX);
			QVariant yVar = QVariant::fromValue<int>(rasterY);
			pc->setMetaData("raster_width",xVar);
			pc->setMetaData("raster_height",yVar);
		}

		//fetch raster bands
		bool zRasterProcessed = false;
		unsigned zInvalid = 0;
		double zMinMax[2] = {0, 0};

		for (int i=1; i<=rasterCount; ++i)
		{
			ccLog::Print( "Reading band #%i", i);
			GDALRasterBand* poBand = poDataset->GetRasterBand(i);

			GDALColorInterp colorInterp = poBand->GetColorInterpretation();
			GDALDataType bandType = poBand->GetRasterDataType();

			int nBlockXSize, nBlockYSize;
			poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
			ccLog::Print( "Block=%dx%d Type=%s, ColorInterp=%s", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(colorInterp) );

			//fetching raster scan-line
			int nXSize = poBand->GetXSize();
			int nYSize = poBand->GetYSize();
			assert(nXSize == rasterX);
			assert(nYSize == rasterY);
			
			int bGotMin, bGotMax;
			double adfMinMax[2] = {0, 0};
			adfMinMax[0] = poBand->GetMinimum( &bGotMin );
			adfMinMax[1] = poBand->GetMaximum( &bGotMax );
			if (!bGotMin || !bGotMax )
				//DGM FIXME: if the file is corrupted (e.g. ASCII ArcGrid with missing rows) this method will enter in a infinite loop!
				GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
			ccLog::Print( "Min=%.3fd, Max=%.3f", adfMinMax[0], adfMinMax[1] );

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

			if( poBand->GetOverviewCount() > 0 )
				printf( "Band has %d overviews", poBand->GetOverviewCount() );

			if (colorInterp == GCI_Undefined && !zRasterProcessed/*&& !colTable*/) //probably heights?
			{
				zRasterProcessed = true;
				zMinMax[0] = adfMinMax[0];
				zMinMax[1] = adfMinMax[1];

				double* scanline = (double*) CPLMalloc(sizeof(double)*nXSize);
				//double* scanline = new double[nXSize];
				memset(scanline,0,sizeof(double)*nXSize);

				for (int j=0; j<nYSize; ++j)
				{
					if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/scanline, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
					{
						delete pc;
						CPLFree(scanline);
						GDALClose(poDataset);
						return CC_FERR_READING;
					}

					for (int k=0; k<nXSize; ++k)
					{
						double z = static_cast<double>(scanline[k]) + Pshift[2];
						unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
						if (pointIndex <= pc->size())
						{
							if (z < zMinMax[0] || z > zMinMax[1])
							{
								z = zMinMax[0] - 1.0;
								++zInvalid;
							}
							const_cast<CCVector3*>(pc->getPoint(pointIndex))->z = static_cast<PointCoordinateType>(z);
						}
					}
				}

				//update bounding-box
				pc->invalidateBoundingBox();

				if (scanline)
					CPLFree(scanline);
				scanline = 0;
			}
			else //colors
			{
				bool isRGB = false;
				bool isScalar = false;
				bool isPalette = false;
				
				switch(colorInterp)
				{
				case GCI_Undefined:
					isScalar = true;
					break;
				case GCI_PaletteIndex:
					isPalette = true;
					break;
				case GCI_RedBand:
				case GCI_GreenBand:
				case GCI_BlueBand:
					isRGB = true;
					break;
				case GCI_AlphaBand:
					if (adfMinMax[0] != adfMinMax[1])
						isScalar = true;
					else
						ccLog::Warning(QString("Alpha band ignored as it has a unique value (%1)").arg(adfMinMax[0]));
					break;
				default:
					isScalar = true;
					break;
				}


				if (isRGB || isPalette)
				{
					//first check that a palette exists if the band is a palette index
					if (isPalette && !colTable)
					{
						ccLog::Warning(QString("Band is declared as a '%1' but no palette is associated!").arg(GDALGetColorInterpretationName(colorInterp)));
						isPalette = false;
					}
					else
					{
						//instantiate memory for RBG colors if necessary
						if (!pc->hasColors() && !pc->setRGBColor(MAX_COLOR_COMP,MAX_COLOR_COMP,MAX_COLOR_COMP))
						{
							ccLog::Warning(QString("Failed to instantiate memory for storing color band '%1'!").arg(GDALGetColorInterpretationName(colorInterp)));
						}
						else
						{
							assert(bandType <= GDT_Int32);

							int* colIndexes = (int*) CPLMalloc(sizeof(int)*nXSize);
							//double* scanline = new double[nXSize];
							memset(colIndexes,0,sizeof(int)*nXSize);

							for (int j=0; j<nYSize; ++j)
							{
								if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colIndexes, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Int32, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
								{
									CPLFree(colIndexes);
									delete pc;
									return CC_FERR_READING;
								}

								for (int k=0; k<nXSize; ++k)
								{
									unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
									if (pointIndex <= pc->size())
									{
										colorType* C = const_cast<colorType*>(pc->getPointColor(pointIndex));

										switch(colorInterp)
										{
										case GCI_PaletteIndex:
											assert(colTable);
											{
												GDALColorEntry col;
												colTable->GetColorEntryAsRGB(colIndexes[k],&col);
												C[0] = static_cast<colorType>(col.c1 & MAX_COLOR_COMP);
												C[1] = static_cast<colorType>(col.c2 & MAX_COLOR_COMP);
												C[2] = static_cast<colorType>(col.c3 & MAX_COLOR_COMP);
											}
											break;

										case GCI_RedBand:
											C[0] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;
										case GCI_GreenBand:
											C[1] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;
										case GCI_BlueBand:
											C[2] = static_cast<colorType>(colIndexes[k] & MAX_COLOR_COMP);
											break;

										default:
											assert(false);
											break;
										}
									}
								}
							}

							if (colIndexes)
								CPLFree(colIndexes);
							colIndexes = 0;

							pc->showColors(true);
						}
					}
				}
				else if (isScalar)
				{
					ccScalarField* sf = new ccScalarField(GDALGetColorInterpretationName(colorInterp));
					if (!sf->resize(pc->size(),true,NAN_VALUE))
					{
						ccLog::Warning(QString("Failed to instantiate memory for storing '%1' as a scalar field!").arg(sf->getName()));
						sf->release();
						sf = 0;
					}
					else
					{
						double* colValues = (double*) CPLMalloc(sizeof(double)*nXSize);
						//double* scanline = new double[nXSize];
						memset(colValues,0,sizeof(double)*nXSize);

						for (int j=0; j<nYSize; ++j)
						{
							if (poBand->RasterIO( GF_Read, /*xOffset=*/0, /*yOffset=*/j, /*xSize=*/nXSize, /*ySize=*/1, /*buffer=*/colValues, /*bufferSizeX=*/nXSize, /*bufferSizeY=*/1, /*bufferType=*/GDT_Float64, /*x_offset=*/0, /*y_offset=*/0 ) != CE_None)
							{
								CPLFree(colValues);
								delete pc;
								return CC_FERR_READING;
							}

							for (int k=0; k<nXSize; ++k)
							{
								unsigned pointIndex = static_cast<unsigned>(k + j * rasterX);
								if (pointIndex <= pc->size())
								{
									ScalarType s = static_cast<ScalarType>(colValues[k]);
									sf->setValue(pointIndex,s);
								}
							}
						}

						if (colValues)
							CPLFree(colValues);
						colValues = 0;

						sf->computeMinAndMax();
						pc->addScalarField(sf);
						if (pc->getNumberOfScalarFields() == 1)
							pc->setCurrentDisplayedScalarField(0);
						pc->showSF(true);
					}
				}
			}
		}

		if (pc)
		{
			if (!zRasterProcessed)
			{
				ccLog::Warning("Raster has no height (Z) information: you can convert one of its scalar fields to Z with 'Edit > Scalar Fields > Set SF as coordinate(s)'");
			}
			else if (zInvalid != 0 && zInvalid < pc->size())
			{
				//shall we remove the points with invalid heights?
				if (QMessageBox::question(0,"Remove NaN points?","This raster has pixels with invalid heights. Shall we remove them?",QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
				{
					CCLib::ReferenceCloud validPoints(pc);
					unsigned count = pc->size();
					bool error = true;
					if (validPoints.reserve(count-zInvalid))
					{
						for (unsigned i=0; i<count; ++i)
						{
							if (pc->getPoint(i)->z >= zMinMax[0])
								validPoints.addPointIndex(i);
						}

						if (validPoints.size() > 0)
						{
							validPoints.resize(validPoints.size());
							ccPointCloud* newPC = pc->partialClone(&validPoints);
							if (newPC)
							{
								delete pc;
								pc = newPC;
								error = false;
							}
						}
						else
						{
							assert(false);
						}
					}

					if (error)
					{
						ccLog::Error("Not enough memory to remove the points with invalid heights!");
					}
				}
			}
			container.addChild(pc);
		}

		GDALClose(poDataset);
	}
	else
	{
		return CC_FERR_UNKNOWN_FILE;
	}

	return CC_FERR_NO_ERROR;
}
Ejemplo n.º 12
0
void generateTexture(string fname, GLuint& tex, int bandnum)
{
   if(bandnum <= 0 )
   {
     bandnum = 1;
   }
   GDALDataset *poDataset;
   GDALAllRegister();
   poDataset= (GDALDataset*) GDALOpen(fname.c_str(),GA_ReadOnly);
   if(poDataset == NULL)
   {
      cout << "OUCH!" << endl;
      //exit(0);
      return;
   }
   cout << "Data size: " << GDALGetRasterXSize(poDataset) << " " << GDALGetRasterYSize(poDataset) << endl;

   GDALRasterBand  *poBand;
   int             nBlockXSize, nBlockYSize;
   int             bGotMin, bGotMax;
   double          adfMinMax[2];
  int bands = poDataset->GetRasterCount();
   bandnum = bandnum % bands + 1;
   if(bandnum > bands)
   {
      bandnum = 1;
   }
   poBand = poDataset->GetRasterBand( bandnum );
   poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
   printf( "Block=%dx%d Type=%s, ColorInterp=%s\n",
            nBlockXSize, nBlockYSize,
            GDALGetDataTypeName(poBand->GetRasterDataType()),
            GDALGetColorInterpretationName(
            poBand->GetColorInterpretation()) );

   float max = adfMinMax[0] = poBand->GetMinimum( &bGotMin );
   float min = adfMinMax[1] = poBand->GetMaximum( &bGotMax );
   if( ! (bGotMin && bGotMax) )
      GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
   int width = poBand->GetXSize(); 
   int height = poBand->GetYSize();

   float *pafScanline;
   std::cout << "Before allocation" << adfMinMax[0] << " " << adfMinMax[1] << endl;
   min = adfMinMax[0];
   max = adfMinMax[1];
   int dsize = 256;
   pafScanline = (float *) CPLMalloc(sizeof(float)*512*512);
   vector<vector<float>> out = vector<vector<float>>(height,vector<float> (width,0));
   //vector<vector<unsigned char>> texs = vector<vector<unsigned char>>(height,vector<unsigned char> (width,0));
   unsigned char texs[512*512];
   poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,512,512,GDT_Float32,0,0);
   float no = poBand->GetNoDataValue();
   cout << "After allocation" << endl;
   for(int i = 0; i < 512; i++)
   {
    for(int j = 0; j < 512; j++)
    {
      //cout << i << j << endl << pafS;
      if(pafScanline[i*width+j] != no)
      {
        // set tex val
        texs[i*512+j] = (unsigned char)(255*((pafScanline[i*512+j] - min)/(max-min)));
        //if((int)texs[i*width] < 0)
        //cout << (int)texs[i*512 +j] << " " << pafScanline[i*512+j] << " " << no << " " << fname << " " << min << " " << max << endl;
      }
      else
      {
        // Set zero val
        texs[i*512+j] = 0;
        //cout << (int)texs[i*512 +j] << fname << endl;
      }
      //texs[i*512+j] = 255;

      //ut[i][j] = pafScanline[i*width+j];
    }
   }
   CPLFree(pafScanline);
   //exit(0);
   // Create a texture
   glGenTextures(1,&tex);
   glBindTexture(GL_TEXTURE_2D,tex);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512,512, 0, GL_RED, GL_UNSIGNED_BYTE,texs);
   GDALClose( (GDALDatasetH) poDataset);
   return;
} 
Ejemplo n.º 13
0
static GDALDataset *FITCreateCopy(const char * pszFilename,
                                  GDALDataset *poSrcDS,
                                  int bStrict, char ** papszOptions,
                                  GDALProgressFunc pfnProgress,
                                  void * pProgressData )
{
    CPLDebug("FIT", "CreateCopy %s - %i", pszFilename, bStrict);

    int nBands = poSrcDS->GetRasterCount();
    if (nBands == 0)
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "FIT driver does not support source dataset with zero band.\n");
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Create the dataset.                                             */
/* -------------------------------------------------------------------- */
    if( !pfnProgress( 0.0, nullptr, pProgressData ) )
    {
        CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
        return nullptr;
    }

    VSILFILE *fpImage = VSIFOpenL( pszFilename, "wb" );
    if( fpImage == nullptr )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "FIT - unable to create file %s.\n",
                  pszFilename );
        return nullptr;
    }

/* -------------------------------------------------------------------- */
/*      Generate header.                                                */
/* -------------------------------------------------------------------- */
    // XXX - should FIT_PAGE_SIZE be based on file page size ??

    const size_t size = std::max(sizeof(FIThead02), FIT_PAGE_SIZE);
    FIThead02 *head = (FIThead02 *) malloc(size);
    FreeGuard<FIThead02> guardHead( head );

    // clean header so padding (past real header) is all zeros
    memset( head, 0, size );

    memcpy((char *) &head->magic, "IT", 2);
    memcpy((char *) &head->version, "02", 2);

    head->xSize = poSrcDS->GetRasterXSize();
    gst_swapb(head->xSize);
    head->ySize = poSrcDS->GetRasterYSize();
    gst_swapb(head->ySize);
    head->zSize = 1;
    gst_swapb(head->zSize);

    head->cSize = nBands;
    gst_swapb(head->cSize);

    GDALRasterBand *firstBand = poSrcDS->GetRasterBand(1);
    if (! firstBand) {
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }

    head->dtype = fitGetDataType(firstBand->GetRasterDataType());
    if (! head->dtype) {
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }
    gst_swapb(head->dtype);
    head->order = 1; // interleaved - RGBRGB
    gst_swapb(head->order);
    head->space = 1; // upper left
    gst_swapb(head->space);

    // XXX - need to check all bands
    head->cm = fitGetColorModel(firstBand->GetColorInterpretation(), nBands);
    gst_swapb(head->cm);

    int blockX, blockY;
    firstBand->GetBlockSize(&blockX, &blockY);
    blockX = std::min(blockX, poSrcDS->GetRasterXSize());
    blockY = std::min(blockY, poSrcDS->GetRasterYSize());
    int nDTSize = GDALGetDataTypeSizeBytes(firstBand->GetRasterDataType());
    try
    {
        CPL_IGNORE_RET_VAL(
            CPLSM(blockX) * CPLSM(blockY) * CPLSM(nDTSize) * CPLSM(nBands));
        CPLDebug("FIT write", "inherited block size %ix%i", blockX, blockY);
    }
    catch( ... )
    {
        blockX = std::min(256, poSrcDS->GetRasterXSize());
        blockY = std::min(256, poSrcDS->GetRasterYSize());
    }

    if( CSLFetchNameValue(papszOptions,"PAGESIZE") != nullptr )
    {
        const char *str = CSLFetchNameValue(papszOptions,"PAGESIZE");
        int newBlockX, newBlockY;
        sscanf(str, "%i,%i", &newBlockX, &newBlockY);
        if (newBlockX && newBlockY) {
            blockX = newBlockX;
            blockY = newBlockY;
        }
        else {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "FIT - Unable to parse option PAGESIZE values [%s]", str);
        }
    }

    // XXX - need to do lots of checking of block size
    // * provide ability to override block size with options
    // * handle non-square block size (like scanline)
    //   - probably default from non-tiled image - have default block size
    // * handle block size bigger than image size
    // * undesirable block size (non power of 2, others?)
    // * mismatched block sizes for different bands
    // * image that isn't even pages (i.e. partially empty pages at edge)
    CPLDebug("FIT write", "using block size %ix%i", blockX, blockY);

    head->xPageSize = blockX;
    gst_swapb(head->xPageSize);
    head->yPageSize = blockY;
    gst_swapb(head->yPageSize);
    head->zPageSize = 1;
    gst_swapb(head->zPageSize);
    head->cPageSize = nBands;
    gst_swapb(head->cPageSize);

    // XXX - need to check all bands
    head->minValue = firstBand->GetMinimum();
    gst_swapb(head->minValue);
    // XXX - need to check all bands
    head->maxValue = firstBand->GetMaximum();
    gst_swapb(head->maxValue);
    head->dataOffset = static_cast<unsigned int>(size);
    gst_swapb(head->dataOffset);

    CPL_IGNORE_RET_VAL(VSIFWriteL(head, size, 1, fpImage));

/* -------------------------------------------------------------------- */
/*      Loop over image, copying image data.                            */
/* -------------------------------------------------------------------- */
    unsigned long bytesPerPixel = nBands * nDTSize;

    size_t pageBytes = blockX * blockY * bytesPerPixel;
    char *output = (char *) malloc(pageBytes);
    if (! output)
    {
        CPLError(CE_Failure, CPLE_OutOfMemory,
                 "FITRasterBand couldn't allocate %lu bytes",
                 static_cast<unsigned long>(pageBytes));
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage));
        return nullptr;
    }
    FreeGuard<char> guardOutput( output );

    long maxx = (long) ceil(poSrcDS->GetRasterXSize() / (double) blockX);
    long maxy = (long) ceil(poSrcDS->GetRasterYSize() / (double) blockY);
    long maxx_full = (long) floor(poSrcDS->GetRasterXSize() / (double) blockX);
    long maxy_full = (long) floor(poSrcDS->GetRasterYSize() / (double) blockY);

    CPLDebug("FIT", "about to write %ld x %ld blocks", maxx, maxy);

    for(long y=0; y < maxy; y++)
        for(long x=0; x < maxx; x++) {
            long readX = blockX;
            long readY = blockY;
            int do_clean = FALSE;

            // handle cases where image size isn't an exact multiple
            // of page size
            if (x >= maxx_full) {
                readX = poSrcDS->GetRasterXSize() % blockX;
                do_clean = TRUE;
            }
            if (y >= maxy_full) {
                readY = poSrcDS->GetRasterYSize() % blockY;
                do_clean = TRUE;
            }

            // clean out image if only doing partial reads
            if (do_clean)
                memset( output, 0, pageBytes );

            for( int iBand = 0; iBand < nBands; iBand++ ) {
                GDALRasterBand * poBand = poSrcDS->GetRasterBand( iBand+1 );
                CPLErr eErr =
                    poBand->RasterIO( GF_Read, // eRWFlag
                                      static_cast<int>(x * blockX), // nXOff
                                      static_cast<int>(y * blockY), // nYOff
                                      static_cast<int>(readX), // nXSize
                                      static_cast<int>(readY), // nYSize
                                      output + iBand * nDTSize,
                                      // pData
                                      blockX, // nBufXSize
                                      blockY, // nBufYSize
                                      firstBand->GetRasterDataType(),
                                      // eBufType
                                      bytesPerPixel, // nPixelSpace
                                      bytesPerPixel * blockX, nullptr); // nLineSpace
                if (eErr != CE_None)
                {
                    CPLError(CE_Failure, CPLE_FileIO,
                             "FIT write - CreateCopy got read error %i", eErr);
                    CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                    VSIUnlink( pszFilename );
                    return nullptr;
                }
            } // for iBand

#ifdef swapping
            char *p = output;
            unsigned long i;
            switch(nDTSize) {
            case 1:
                // do nothing
                break;
            case 2:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap16(p + i);
                break;
            case 4:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap32(p + i);
                break;
            case 8:
                for(i=0; i < pageBytes; i+= nDTSize)
                    gst_swap64(p + i);
                break;
            default:
                CPLError(CE_Failure, CPLE_NotSupported,
                         "FIT write - unsupported bytesPerPixel %d",
                         nDTSize);
            } // switch
#endif // swapping

            if( VSIFWriteL(output, 1, pageBytes, fpImage) != pageBytes )
            {
                CPLError( CE_Failure, CPLE_FileIO, "Write failed" );
                CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                VSIUnlink( pszFilename );
                return nullptr;
            }

            double perc = ((double) (y * maxx + x)) / (maxx * maxy);
            if( !pfnProgress( perc, nullptr, pProgressData ) )
            {
                CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" );
                //free(output);
                CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));
                VSIUnlink( pszFilename );
                return nullptr;
            }
        } // for x

    //free(output);

    CPL_IGNORE_RET_VAL(VSIFCloseL( fpImage ));

    pfnProgress( 1.0, nullptr, pProgressData );

/* -------------------------------------------------------------------- */
/*      Re-open dataset, and copy any auxiliary pam information.         */
/* -------------------------------------------------------------------- */
    GDALPamDataset *poDS = (GDALPamDataset *)
        GDALOpen( pszFilename, GA_ReadOnly );

    if( poDS )
        poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT );

    return poDS;
}
Ejemplo n.º 14
0
T* GISToFloatArray(char* fname, int interpWidth, int interpHeight)
{
  // Important note ------ Gdal considers images to be north up
  // the origin of datasets takes place in the upper-left or North-West corner.
  // Now to create a GDAL dataset
  // auto ds = ((GDALDataset*) GDALOpen(fname,GA_ReadOnly));
  GDALDataset* ds = ((GDALDataset*) GDALOpen(fname,GA_ReadOnly));
  if(ds == NULL)
  {
    return NULL;
  }
  
  // Creating a Raster band variable
  // A band represents one whole dataset within a dataset
  // in your case your files have one band.
  GDALRasterBand  *poBand;
  int             nBlockXSize, nBlockYSize;
  int             bGotMin, bGotMax;
  double          adfMinMax[2];
  
  // Assign the band      
  poBand = ds->GetRasterBand( 1 );
  poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

  // find the min and max
  adfMinMax[0] = poBand->GetMinimum( &bGotMin );
  adfMinMax[1] = poBand->GetMaximum( &bGotMax );
  if( ! (bGotMin && bGotMax) )
    GDALComputeRasterMinMax((GDALRasterBandH)poBand, TRUE, adfMinMax);
  int min = adfMinMax[0];
  int max = adfMinMax[1];

  // get the width and height of the band or dataset
  int width = poBand->GetXSize();
  int height = poBand->GetYSize();

  // GDAL can handle files that have multiple datasets jammed witin it
  int bands = ds->GetRasterCount();

  // the float variable to hold the DEM!
  T *pafScanline;
  // std::cout << "Min: " << adfMinMax[0] << " Max: " << adfMinMax[1] << endl;
  int dsize = 256;
  // pafScanline = (T *) CPLMalloc(sizeof(T)*width*height);
  pafScanline = (T *) CPLMalloc(sizeof(T)*interpWidth*interpHeight);

  // Lets acquire the data.  ..... this funciton will interpolate for you
  // poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,width,height,GDT_Float32,0,0);
  poBand->RasterIO(GF_Read,0,0,width,height,pafScanline,interpWidth,interpHeight,GDT_Float32,0,0);
  //        chage these two to interpolate automatically ^      ^

  // The Geotransform gives information on where a dataset is located in the world
  // and the resolution.
  // for more information look at http://www.gdal.org/gdal_datamodel.html
  double geot[6];
  ds->GetGeoTransform(geot);

  // Get the x resolution per pixel(south and west) and y resolution per pixel (north and south)
  // float xres = geot[1];
  // float yres = geot[5];
  // string proj;
  // proj = string(ds->GetProjectionRef());

  // You can get the projection string
  // The projection gives information about the coordinate system a dataset is in
  // This is important to allow other GIS softwares to place datasets into the same
  // coordinate space 
  // char* test = &proj[0];

  // The origin of the dataset 
  // float startx = geot[0]; // east - west coord.
  // float starty = geot[3]; // north - south coord.

  
  // here is some code that I used to push that 1D array into a 2D array
  // I believe this puts everything in the correct order....
  /*for(int i = 0; i < hsize; i++)
  {
    for(int j = 0; j < wsize; j++)
    {
      //cout << i << j << endl << pafS;
      vecs[i][j] = pafScanline[((int)i)*(int)wsize+((int)j)];
      if(vecs[i][j]>0 && vecs[i][j] > max)
      {
          max = vecs[i][j];
      }
      if(vecs[i][j]>0 && vecs[i][j] < min)
      {
          min = vecs[i][j];
      }
    }
   }*/
   //CPLFree(pafScanline);
   return pafScanline;

}
Ejemplo n.º 15
0
	bool DEM::load(const std::string& filename) {
		GDALAllRegister();

		GDALDataset* poDS;
		poDS = (GDALDataset*)GDALOpenEx(filename.c_str(), GDAL_OF_RASTER, NULL, NULL, NULL);
		if (poDS == NULL) return false;

		double adfGeoTransform[6];
		if (poDS->GetGeoTransform(adfGeoTransform) == CE_None) {
			origin.x = adfGeoTransform[0];
			origin.y = adfGeoTransform[3];

			pixelSize.x = adfGeoTransform[1];
			pixelSize.y = abs(adfGeoTransform[5]);
		}

		width = poDS->GetRasterXSize() * pixelSize.x;
		height = poDS->GetRasterYSize() * pixelSize.y;
		data.resize(width * height);
		min_val = std::numeric_limits<float>::max();
		max_val = -std::numeric_limits<float>::max();

		// bandが存在しない場合は、エラー
		if (poDS->GetRasterCount() == 0) return false;

		// 最初のbandのみを読み込む。複数bandは未対応
		GDALRasterBand* poBand = poDS->GetRasterBand(1);

		int nBlockXSize, nBlockYSize;
		poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
		//printf("Block=%dx%d Type=%s, ColorInterp=%s\n", nBlockXSize, nBlockYSize, GDALGetDataTypeName(poBand->GetRasterDataType()), GDALGetColorInterpretationName(poBand->GetColorInterpretation()));

		// 最低、最高の値を取得
		int bGotMin, bGotMax;
		double adfMinMax[2];
		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]);
		min_val = adfMinMax[0];
		max_val = adfMinMax[1];
			
		//int nXSize = poBand->GetXSize();
		//int nYSize = poBand->GetYSize();

		int nXBlocks = (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
		int nYBlocks = (poBand->GetYSize() + nBlockYSize - 1) / nBlockYSize;
		float *pData = (float *)CPLMalloc(sizeof(float*) * nBlockXSize * nBlockYSize);
		for (int iYBlock = 0; iYBlock < nYBlocks; iYBlock++) {
			for (int iXBlock = 0; iXBlock < nXBlocks; iXBlock++) {
				int nXValid, nYValid;

				poBand->ReadBlock(iXBlock, iYBlock, pData);

				// Compute the portion of the block that is valid
				// for partial edge blocks.
				if ((iXBlock + 1) * nBlockXSize > poBand->GetXSize())
					nXValid = poBand->GetXSize() - iXBlock * nBlockXSize;
				else
					nXValid = nBlockXSize;
				if ((iYBlock + 1) * nBlockYSize > poBand->GetYSize())
					nYValid = poBand->GetYSize() - iYBlock * nBlockYSize;
				else
					nYValid = nBlockYSize;

				for (int iY = 0; iY < nYValid; iY++) {
					for (int iX = 0; iX < nXValid; iX++) {
						float val;
						if (pData[iY * nBlockXSize + iX] > max_val) {
							val = max_val;
						}
						else if (pData[iY * nBlockXSize + iX] < min_val) {
							val = min_val;
						}
						else {
							val = pData[iY * nBlockXSize + iX];
						}

						for (int y = 0; y < pixelSize.y; ++y) {
							for (int x = 0; x < pixelSize.x; ++x) {
								data[((iYBlock * nBlockYSize + iY) * pixelSize.y + y) * width + (iXBlock * nBlockXSize + iX) * pixelSize.x + x] = val;
							}
						}
						
					}
				}
			}
		}

		GDALClose(poDS);

		return true;
	}
Ejemplo n.º 16
0
int readRaster(const char* pszFilename)
{
    // Set config options for GDAL (needs >= 2.0). Setting GTIFF_VIRTUAL_MEM_IO to "YES" can cause things bleed to
    // swap if enough RAM is not available. Use "IF_ENOUGH_RAM" for safer performance if unsure. NOTE that faster
    // mem io only works with *uncompressed* GeoTIFFs.
    // New in GDAL 2.0, from https://2015.foss4g-na.org/sites/default/files/slides/GDAL%202.0%20overview.pdf
    // GeoTIFF driver (with i7-4700 HQ (8 vCPUs)):with i7-4700 HQ (8 vCPUs)
    //   - Default: time ./testblockcache -ondisk: 7.5s
    //   - GTIFF_DIRECT_IO=YES: short circuit the block cache&libtiff for most RasterIO() operations (restricted to
    //     uncompressed stripped GeoTIFF). time ./testblockcache -ondisk: 2s
    //   - GTIFF_VIRTUAL_MEM_IO=YES: same as above, with tiled GeoTIFF as well. Uses memory-mapped file access. Linux
    //     only for now, 64bit recommended (could be extended to other platforms possible).
    //     time ./testblockcache -ondisk: 0.3s
    //
    CPLSetConfigOption("GTIFF_VIRTUAL_MEM_IO", "YES" );
    // Open the dataset
    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
    {
        GDALRasterBand  *poBand;
        int             nBlockXSize, nBlockYSize;
        int             bGotMin, bGotMax;
        double          adfMinMax[2];

        //  Get raster band and its size
        poBand = poDataset->GetRasterBand(1);
        poBand->GetBlockSize( &nBlockXSize, &nBlockYSize);

        std::cout << "Dataset: " << pszFilename << std::endl;

        std::cout << "Block=" << nBlockXSize << "x" << nBlockYSize << " Type=" <<
                GDALGetDataTypeName(poBand->GetRasterDataType()) << " ColorInterp=" <<
                GDALGetColorInterpretationName(poBand->GetColorInterpretation()) << std::endl;

        // Calculate some stats
        adfMinMax[0] = poBand->GetMinimum(&bGotMin);
        adfMinMax[1] = poBand->GetMaximum(&bGotMax);

        if(!(bGotMin && bGotMax)) {
            GDALComputeRasterMinMax((GDALRasterBandH) poBand, TRUE, adfMinMax);
        }
        std::cout << "Min=" << adfMinMax[0] << " Max=" << adfMinMax[1] << std::endl;

        if(poBand->GetOverviewCount() > 0) {
            std::cout << "Band has " << poBand->GetOverviewCount() << " overviews." << std::endl;
        }
        if( poBand->GetColorTable() != NULL ) {
            std::cout << "Band has a color table with " << poBand->GetColorTable()->GetColorEntryCount() <<
                    " entries." << std::endl;
        }

        // Get the actual data
        float *pafScanline;
        int   nXSize = poBand->GetXSize();
        pafScanline = (float *) CPLMalloc(sizeof(float) * nXSize);

        // RasterIO has a new argument psExtraArg in GDAL > 2.0. NOTE: that  GDALRasterBand::ReadBlock() probably has
        // better performance for reading the whole data at one go.
        #ifdef USE_GDAL_2
            GDALRasterIOExtraArg* arg = NULL;
            poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float3GDALRasterBand::ReadBlock 2,
               0, 0, arg);
        #else
            poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0);
        #endif

        // ... do something with the data ...

        // Free resources
        CPLFree(pafScanline);
        GDALClose((GDALDatasetH) poDataset);
        std::cout << std::endl;
    }
    return 0;
}
Ejemplo n.º 17
0
void Terrain::initTerrainFile()
{
    auto t = map_file.toLatin1();
    dataset = (GDALDataset*) GDALOpen(t.constData(), GA_ReadOnly);

    if(dataset == nullptr) {
        qDebug() << "Unable to get GDAL Dataset for file: " << map_file;
        exit(1);
    }

    GDALRasterBand *raster = dataset->GetRasterBand(1);

    int width = raster->GetXSize();//terrain_img.getWidth();
    int height = raster->GetYSize();//terrain_img.getHeight();

    int gotMin, gotMax;

    float min = raster->GetMinimum(&gotMin);
    float max = raster->GetMaximum(&gotMax);

    double minMax[2] = {min, max};

    if(!(gotMin && gotMax)) {
        GDALComputeRasterMinMax((GDALRasterBandH) raster, TRUE, minMax);

        min = minMax[0];
        max = minMax[1];
    }

    if(engine->getOptions().verbose)
        qDebug() << "terrain: " << map_file << "x: " << width << " y: " << height << "   min: " << min << " max: " << max;

    int woffset = width / 2;
    int hoffset = height / 2;

    Vertex tempVert;
    tempVert.position[1] = 0;

    float maxOffset = max - min;

    float scale = engine->getOptions().map_scalar;
    float *lineData = (float*) CPLMalloc(sizeof(float) * width);
    float *lineData2 = (float*) CPLMalloc(sizeof(float) * width);

    for(int z = -hoffset; z < height - hoffset-1; z++) {
        raster->RasterIO(GF_Read, 0, z + hoffset, width, 1, lineData, width, 1, GDT_Float32, 0, 0);
        raster->RasterIO(GF_Read, 0, z + hoffset + 1, width, 1, lineData2, width, 1, GDT_Float32, 0, 0);

        for(int x = -woffset; x < width - woffset-1; x++) {
            tempVert.position[0] = x*scale;
            tempVert.position[1] = (lineData[x+woffset]-min) / maxOffset;
            tempVert.position[2] = z*scale;

            geometry.push_back(tempVert);

            tempVert.position[0] = (x+1) * scale;
            tempVert.position[1] = (lineData[x+woffset+1]-min) / maxOffset;
            tempVert.position[2] = z*scale;

            geometry.push_back(tempVert);

            tempVert.position[0] = x*scale;
            tempVert.position[1] = (lineData2[x+woffset]-min) / maxOffset;
            tempVert.position[2] = (z+1) * scale;

            geometry.push_back(tempVert);

            // push bottom row of triangles
            tempVert.position[0] = x*scale;
            tempVert.position[1] = (lineData2[x+woffset]-min) / maxOffset;
            tempVert.position[2] = (z+1) * scale;

            geometry.push_back(tempVert);

            tempVert.position[0] = (x+1) * scale;
            tempVert.position[1] = (lineData2[x+woffset+1]-min) / maxOffset;
            tempVert.position[2] = (z+1) * scale;

            geometry.push_back(tempVert);

            tempVert.position[0] = (x+1) * scale;
            tempVert.position[1] = (lineData[x+woffset+1]-min) / maxOffset;
            tempVert.position[2] = z*scale;

            geometry.push_back(tempVert);

        }
    }

    CPLFree(lineData);
    CPLFree(lineData2);
}
Ejemplo n.º 18
0
void Terrain::applyDataset(const QString& file)
{
    auto t = file.toLatin1();
    GDALDataset *dataset_data = (GDALDataset*) GDALOpen(t.constData(), GA_ReadOnly);
    GDALDataset *dataset_mask = dataset;//(GDALDataset*) GDALOpen(map_file.toLatin1()constData(), GA_ReadOnly);

    if(dataset == nullptr) {
        qDebug() << "Unable to get GDAL Dataset for data file: " << file;
        exit(1);
    }

    if(dataset_mask == nullptr) {
        qDebug() << "Unable to get GDAL Dataset for mask file: " << map_file;
        exit(1);
    }

    GDALRasterBand *raster = dataset_data->GetRasterBand(1);
    GDALRasterBand *raster_mask = dataset_mask->GetRasterBand(1);

    int width = raster->GetXSize();//terrain_img.getWidth();
    int height = raster->GetYSize();//terrain_img.getHeight();
    int width_mask = raster_mask->GetXSize();
    //int height_mask = raster_mask->GetYSize();

    int gotMin, gotMax;

    float min = raster->GetMinimum(&gotMin);
    float max = raster->GetMaximum(&gotMax);

    double minMax[2] = {min, max};

    if(!(gotMin && gotMax)) {
        GDALComputeRasterMinMax((GDALRasterBandH) raster, TRUE, minMax);

        min = minMax[0];
        max = minMax[1];
    }

    float min_mask = raster_mask->GetMinimum(&gotMin);
    float max_mask = raster_mask->GetMaximum(&gotMax);

    minMax[0] = min_mask;
    minMax[1] = max_mask;

    if(!(gotMin && gotMax)) {
        GDALComputeRasterMinMax((GDALRasterBandH) raster_mask, TRUE, minMax);

        min_mask = minMax[0];
        max_mask = minMax[1];
    }

    if(engine->getOptions().verbose) {
        qDebug() << "terrain mask: " << map_file << "   min: " << min << " max: " << max;
        qDebug() << "terrain data: " << file << "   min: " << min_mask << " max: " << max_mask;
    }

    int woffset = width / 2;
    int hoffset = height / 2;

    float maxOffset = max - min;
    float maxOffset_mask = max_mask - min_mask;

    float *lineData = (float*) CPLMalloc(sizeof(float) * width);
    float *lineData2 = (float*) CPLMalloc(sizeof(float) * width);
    float *lineData_mask = (float*) CPLMalloc(sizeof(float) * width_mask);
    float *lineData2_mask = (float*) CPLMalloc(sizeof(float) * width_mask);

    int i = 0;
    for(int z = -hoffset; z < height - hoffset-1; z++) {
        raster->RasterIO(GF_Read, 0, z + hoffset, width, 1, lineData, width, 1, GDT_Float32, 0, 0);
        raster->RasterIO(GF_Read, 0, z + hoffset + 1, width, 1, lineData2, width, 1, GDT_Float32, 0, 0);
        raster_mask->RasterIO(GF_Read, 0, z + hoffset, width_mask, 1, lineData_mask, width_mask, 1, GDT_Float32, 0, 0);
        raster_mask->RasterIO(GF_Read, 0, z + hoffset + 1, width_mask, 1, lineData2_mask, width_mask, 1, GDT_Float32, 0, 0);

        for(int x = -woffset; x < width - woffset-1; x++) {

            if((((lineData_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f) && (((lineData_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)
                    && (((lineData2_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f)) {


                geometry[i].dataPoint = (lineData[x+woffset]-min) / maxOffset;
                i++;
                geometry[i].dataPoint = (lineData[x+woffset+1]-min) / maxOffset;
                i++;
                geometry[i].dataPoint = (lineData2[x+woffset]-min) / maxOffset;
                i++;
            }


            if((((lineData2_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f) && (((lineData2_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)
                    && (((lineData_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)) {

                geometry[i].dataPoint = (lineData2[x+woffset]-min) / maxOffset;
                i++;
                geometry[i].dataPoint = (lineData2[x+woffset+1]-min) / maxOffset;
                i++;
                geometry[i].dataPoint = (lineData[x+woffset+1]-min) / maxOffset;
                i++;
            }

        }
    }

    CPLFree(lineData);
    CPLFree(lineData2);
    CPLFree(lineData_mask);
    CPLFree(lineData2_mask);
    //GDALClose((GDALDatasetH) dataset);
    //GDALClose((GDALDatasetH) dataset_mask);
    program = engine->graphics->getShaderProgram("data");
    initGL(false);
}
Ejemplo n.º 19
0
// static functions
QVector<Terrain*> Terrain::createTerrainFromDEMandMask(Engine *engine, const QString& dem, const QString& mask, Terrain *large_dem)
{
    QVector<Terrain*> terrain_vec(2);

    Terrain *dem_t = new Terrain(engine, dem, engine->graphics->getShaderProgram("gray"));
    Terrain *mask_t = new Terrain(engine, mask, engine->graphics->getShaderProgram("color"));

    auto t = dem.toLatin1();
    auto t2 = mask.toLatin1();
    GDALDataset *dataset = (GDALDataset*) GDALOpen(t.constData(), GA_ReadOnly);
    GDALDataset *dataset_mask = (GDALDataset*) GDALOpen(t2.constData(), GA_ReadOnly);

    if(dataset == nullptr) {
        qDebug() << "Unable to get GDAL Dataset for file: " << dem;
        exit(1);
    }

    if(dataset_mask == nullptr) {
        qDebug() << "Unable to get GDAL Dataset for mask file: " << mask;
        exit(1);
    }

    GDALRasterBand *raster = dataset->GetRasterBand(1);
    GDALRasterBand *raster_mask = dataset_mask->GetRasterBand(1);

    int width = raster->GetXSize();//terrain_img.getWidth();
    int height = raster->GetYSize();//terrain_img.getHeight();
    int width_mask = raster_mask->GetXSize();
    //int height_mask = raster_mask->GetYSize();

    int gotMin, gotMax;
    float large_min, large_max;
    float large_max_offset;

    if(large_dem) {
        GDALRasterBand *large_raster = large_dem->dataset->GetRasterBand(1);
        large_min = large_raster->GetMinimum(&gotMin);
        large_max = large_raster->GetMaximum(&gotMax);

        if(!(gotMin && gotMax)) {
            double minMax[2] = {large_min, large_max};
            GDALComputeRasterMinMax((GDALRasterBandH) large_raster, TRUE, minMax);

            large_min = minMax[0];
            large_max = minMax[1];
        }

        large_max_offset = large_max - large_min;
    }

    float min = raster->GetMinimum(&gotMin);
    float max = raster->GetMaximum(&gotMax);

    double minMax[2] = {min, max};

    if(!(gotMin && gotMax)) {
        GDALComputeRasterMinMax((GDALRasterBandH) raster, TRUE, minMax);

        min = minMax[0];
        max = minMax[1];
    }

    float min_mask = raster_mask->GetMinimum(&gotMin);
    float max_mask = raster_mask->GetMaximum(&gotMax);

    minMax[0] = min_mask;
    minMax[1] = max_mask;

    if(!(gotMin && gotMax)) {
        GDALComputeRasterMinMax((GDALRasterBandH) raster_mask, TRUE, minMax);

        min_mask = minMax[0];
        max_mask = minMax[1];
    }

    if(engine->getOptions().verbose) {
        qDebug() << "terrain: " << dem << "   min: " << min << " max: " << max;
        qDebug() << "terrain mask: " << mask << "   min: " << min_mask << " max: " << max_mask;
    }

    int woffset = width / 2;
    int hoffset = height / 2;

    Vertex tempVert;

    float maxOffset = max - min;
    float maxOffset_mask = max_mask - min_mask;

    float scale = engine->getOptions().map_scalar * (2.5f / 10.0f);
    float *lineData = (float*) CPLMalloc(sizeof(float) * width);
    float *lineData2 = (float*) CPLMalloc(sizeof(float) * width);
    float *lineData_mask = (float*) CPLMalloc(sizeof(float) * width_mask);
    float *lineData2_mask = (float*) CPLMalloc(sizeof(float) * width_mask);

    if(!large_dem) {
        large_max_offset = maxOffset;
        large_min = min;
    }

    for(int z = -hoffset; z < height - hoffset-1; z++) {
        raster->RasterIO(GF_Read, 0, z + hoffset, width, 1, lineData, width, 1, GDT_Float32, 0, 0);
        raster->RasterIO(GF_Read, 0, z + hoffset + 1, width, 1, lineData2, width, 1, GDT_Float32, 0, 0);
        raster_mask->RasterIO(GF_Read, 0, z + hoffset, width_mask, 1, lineData_mask, width_mask, 1, GDT_Float32, 0, 0);
        raster_mask->RasterIO(GF_Read, 0, z + hoffset + 1, width_mask, 1, lineData2_mask, width_mask, 1, GDT_Float32, 0, 0);

        for(int x = -woffset; x < width - woffset-1; x++) {

            if((((lineData_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f) && (((lineData_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)
                    && (((lineData2_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f)) {

                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                mask_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                mask_t->geometry.push_back(tempVert);

                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData2[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                mask_t->geometry.push_back(tempVert);
            }

            else {
                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                dem_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                dem_t->geometry.push_back(tempVert);

                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData2[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                dem_t->geometry.push_back(tempVert);
            }

            if((((lineData2_mask[x+woffset]-min_mask) / maxOffset_mask) >= 0.1f) && (((lineData2_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)
                    && (((lineData_mask[x+woffset+1]-min_mask) / maxOffset_mask) >= 0.1f)) {

                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData2[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                mask_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData2[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                mask_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                mask_t->geometry.push_back(tempVert);
            }

            else {
                tempVert.position[0] = x*scale;
                tempVert.position[1] = (lineData2[x+woffset]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                dem_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData2[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = (z+1) * scale;
                dem_t->geometry.push_back(tempVert);

                tempVert.position[0] = (x+1) * scale;
                tempVert.position[1] = (lineData[x+woffset+1]-large_min) / large_max_offset;
                tempVert.position[2] = z*scale;
                dem_t->geometry.push_back(tempVert);
            }

        }
    }

    CPLFree(lineData);
    CPLFree(lineData2);
    CPLFree(lineData_mask);
    CPLFree(lineData2_mask);
    //GDALClose((GDALDatasetH) dataset);
    //GDALClose((GDALDatasetH) dataset_mask);

    dem_t->dataset = dataset;
    mask_t->dataset = dataset_mask;

    dem_t->initGL();
    mask_t->initGL();
    mask_t->textures.push_back(engine->graphics->createTextureFromFile(QString::fromStdString(engine->getOptions().color_map),
        GL_TEXTURE_1D));

    terrain_vec[0] = dem_t;
    terrain_vec[1] = mask_t;

    return terrain_vec;
}