Пример #1
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);
};
Пример #2
0
static GDALDataset*
createMemDS(int width, int height, double minX, double minY, double maxX, double maxY, const std::string &projection)
{
    //Get the MEM driver
    GDALDriver* memDriver = (GDALDriver*)GDALGetDriverByName("MEM");
    if (!memDriver)
    {
        OE_NOTICE << "[osgEarth::GeoData] Could not get MEM driver" << std::endl;
    }

    //Create the in memory dataset.
    GDALDataset* ds = memDriver->Create("", width, height, 4, GDT_Byte, 0);

    //Initialize the color interpretation
    ds->GetRasterBand(1)->SetColorInterpretation(GCI_RedBand);
    ds->GetRasterBand(2)->SetColorInterpretation(GCI_GreenBand);
    ds->GetRasterBand(3)->SetColorInterpretation(GCI_BlueBand);
    ds->GetRasterBand(4)->SetColorInterpretation(GCI_AlphaBand);

    //Initialize the geotransform
    double geotransform[6];
    double x_units_per_pixel = (maxX - minX) / (double)width;
    double y_units_per_pixel = (maxY - minY) / (double)height;
    geotransform[0] = minX;
    geotransform[1] = x_units_per_pixel;
    geotransform[2] = 0;
    geotransform[3] = maxY;
    geotransform[4] = 0;
    geotransform[5] = -y_units_per_pixel;
    ds->SetGeoTransform(geotransform);
    ds->SetProjection(projection.c_str());

    return ds;
}
bool ncepHrrrSurfInitialization::identify( std::string fileName )
{
    bool identified = true;

    if( fileName.find("nam") != fileName.npos ) {
        identified = false;
        return identified;
    }

    //ID based on 10u band
    GDALDataset *srcDS;
    srcDS = (GDALDataset*)GDALOpenShared( fileName.c_str(), GA_ReadOnly );

    if( srcDS == NULL ) {
        CPLDebug( "ncepHRRRSurfaceInitialization::identify()",
                "Bad forecast file" );
        return false;
    }

    if( srcDS->GetRasterCount() < 8 )
    {
        /* Short circuit */
        GDALClose( (GDALDatasetH)srcDS );
        identified = false;
        return identified;
    }
    GDALRasterBand *poBand = srcDS->GetRasterBand( 33 ); //2010 structure
    const char *gc;
    gc = poBand->GetMetadataItem( "GRIB_COMMENT" );
    std::string bandName( gc );

    if( bandName.find( "u-component of wind [m/s]" ) == bandName.npos ){
        poBand = srcDS->GetRasterBand( 49 ); //files after 2010 have different structure
        gc = poBand->GetMetadataItem( "GRIB_COMMENT" );
        bandName = gc;
        if( bandName.find( "u-component of wind [m/s]" ) == bandName.npos ){
            poBand = srcDS->GetRasterBand( 50 ); //2012 files have different structure
            gc = poBand->GetMetadataItem( "GRIB_COMMENT" );
            bandName = gc;
            if( bandName.find( "u-component of wind [m/s]" ) == bandName.npos ){
                poBand = srcDS->GetRasterBand( 53 ); //2013 files have different structure
                gc = poBand->GetMetadataItem( "GRIB_COMMENT" );
                bandName = gc;
                if( bandName.find( "u-component of wind [m/s]" ) == bandName.npos ){
                    identified = false;
                }
            }
        }
    }
    GDALClose( (GDALDatasetH)srcDS );

    return identified;

}
Пример #4
0
int Raster::Uniform(const char * pOutputRaster, double fValue)
{

    // Open up the Input File
    GDALDataset * pInputDS = (GDALDataset*) GDALOpen(m_sFilePath, GA_ReadOnly);
    if (pInputDS == NULL)
        throw RasterManagerException( INPUT_FILE_ERROR, "Input file could not be opened");

    GDALRasterBand * pRBInput = pInputDS->GetRasterBand(1);

    // Create the output dataset for writing
    GDALDataset * pOutputDS = CreateOutputDS(pOutputRaster, this);
    GDALRasterBand * pOutputRB = pOutputDS->GetRasterBand(1);

    // Assign our buffers
    double * pInputLine = (double*) CPLMalloc(sizeof(double) * GetCols());
    double * pOutputLine = (double*) CPLMalloc(sizeof(double) * GetCols());

    // Loop over rows
    for (int i=0; i < GetRows(); i++)
    {
        // Populate the buffer
        pRBInput->RasterIO(GF_Read, 0,  i, GetCols(), 1, pInputLine, GetCols(), 1, GDT_Float64, 0, 0);

        // Loop over columns
        for (int j=0; j < GetCols(); j++)
        {
            if (pInputLine[j] != GetNoDataValue()){
                pOutputLine[j] = fValue;
            }
            else {
                pOutputLine[j] = GetNoDataValue();
            }

        }
        // Write the row
        pOutputRB->RasterIO(GF_Write, 0, i, GetCols(), 1, pOutputLine, GetCols(), 1, GDT_Float64, 0, 0 );
    }

    CPLFree(pOutputLine);
    CPLFree(pInputLine);

    CalculateStats(pOutputDS->GetRasterBand(1));

    if ( pInputDS != NULL)
        GDALClose(pInputDS);
    if ( pOutputDS != NULL)
        GDALClose(pOutputDS);

    return PROCESS_OK;

}
Raster* import_raster(string raster_filename, int band_number) {
    GDALAllRegister();
    GDALDataset*  poDataset = (GDALDataset *) GDALOpen( raster_filename.c_str(), GA_ReadOnly );
    if( poDataset == NULL ) { 
        cerr << "Error: Could not open raster data file" << endl;
        exit(1); 
    }

    fprintf(stderr, "Driver: %s/%s\n", poDataset->GetDriver()->GetDescription(), poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) );
    fprintf(stderr, "Size is %dx%dx%d\n", poDataset->GetRasterXSize(), poDataset->GetRasterYSize(), poDataset->GetRasterCount() );

    if( poDataset->GetProjectionRef()  != NULL ) cerr << "Projection is `" << poDataset->GetProjectionRef() << "'" << endl;;

    
    GDALRasterBand* poBand = poDataset->GetRasterBand( band_number );
    int nBlockXSize, nBlockYSize;
    poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );
    fprintf(stderr, "Block=%dx%d Type=%s, ColorInterp=%s\n",
            nBlockXSize, nBlockYSize,
            GDALGetDataTypeName(poBand->GetRasterDataType()),
            GDALGetColorInterpretationName( poBand->GetColorInterpretation()) );

    Raster* raster = extract_raster_attributes( poDataset );
    raster->band = poBand;
    return raster;
}
Пример #6
0
/**
*@brief tif图片投影转换
*@param tifPath [in] tif图片路径
*@param toWkt [in] 目标点的wkt字符串
*@param outPath [in] 转换后文件路径
*@return
*/
void GdalProjection::TifProjectionTransformation(const char *tifPath, const char *toWkt,const char *outPath)
{
    GDALDataset *poDataset = gbase.OpenDatasetR(tifPath);
    const char *fromWkt = poDataset->GetProjectionRef();
    //double *adfGeoTransform = (double *)CPLMalloc(sizeof(double) * 6);
    //int x = poDataset->GetRasterXSize();
    //int y = poDataset->GetRasterYSize();
    int bands = poDataset->GetRasterCount();
    double adfGeoTransform[6];
    GDALDataType  gdt = poDataset->GetRasterBand(1)->GetRasterDataType();
    void *hTransformArg;
    //cout<<fromWkt;
    hTransformArg = GDALCreateGenImgProjTransformer(poDataset,fromWkt,NULL,toWkt,FALSE,0,1);
    //cout<<toWkt<<endl;
    int nPixels = 0,nLines = 0;
    CPLErr eErr;
    eErr = GDALSuggestedWarpOutput(poDataset,GDALGenImgProjTransform,hTransformArg,
                                   adfGeoTransform,&nPixels,&nLines);
    //cout<<nPixels<<" : "<<nLines<<endl;


    //创建转换后的投影和坐标系的空图像

    CreateTiff(outPath,gdt,toWkt,adfGeoTransform,nPixels,nLines,bands);

    ////重投影
    TifReProjection(tifPath,outPath);

}
Пример #7
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;
}
Пример #8
0
GDALRasterBand *VRTRasterBand::GetOverview( int iOverview )

{
    if( apoOverviews.size() > 0 )
    {
        if( iOverview < 0 || iOverview >= (int) apoOverviews.size() )
            return NULL;

        if( apoOverviews[iOverview].poBand == NULL 
            && !apoOverviews[iOverview].bTriedToOpen )
        {
            apoOverviews[iOverview].bTriedToOpen = TRUE;

            GDALDataset *poSrcDS = (GDALDataset *)
                GDALOpenShared( apoOverviews[iOverview].osFilename, GA_ReadOnly );
            
            if( poSrcDS == NULL )
                return NULL;

            apoOverviews[iOverview].poBand = poSrcDS->GetRasterBand( 
                apoOverviews[iOverview].nBand );

            if (apoOverviews[iOverview].poBand == NULL)
            {
                GDALClose( (GDALDatasetH)poSrcDS );
            }
        }

        return apoOverviews[iOverview].poBand;
    }
    else
        return GDALRasterBand::GetOverview( iOverview );
}
Пример #9
0
void Raster<T>::OutputGTiff(const char* rasterName)
{
	const char *pszFormat = "GTiff";
	GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);

	char **papszOptions = poDriver->GetMetadata();
	//papszOptions = CSLSetNameValue( papszOptions, "TILED", "YES" );
	//papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "PACKBITS" );
	GDALDataset *poDstDS = poDriver->Create(rasterName, m_nCols, m_nRows, 1, m_dType, papszOptions);
	
	//write the data to new file
	GDALRasterBand  *poDstBand= poDstDS->GetRasterBand(1);
	poDstBand->RasterIO(GF_Write, 0, 0,  m_nCols, m_nRows, m_data,  m_nCols, m_nRows, m_dType, 0, 0);
	poDstBand->SetNoDataValue(m_noDataValue);

	double geoTrans[6];
	geoTrans[0] = m_xMin;
	geoTrans[1] = m_dx;
	geoTrans[2] = 0;
	geoTrans[3] = m_yMax;
	geoTrans[4] = 0;
	geoTrans[5] = -m_dy;
	poDstDS->SetGeoTransform(geoTrans);

	poDstDS->SetProjection(m_proj.c_str());

	GDALClose(poDstDS);
}
Пример #10
0
 virtual CPLErr IRasterIO( GDALRWFlag eRWFlag,
                           int nXOff, int nYOff, int nXSize, int nYSize,
                           void * pData, int nBufXSize, int nBufYSize,
                           GDALDataType eBufType,
                           GSpacing nPixelSpace,
                           GSpacing nLineSpace,
                           GDALRasterIOExtraArg* psExtraArg )
 {
     const CPLErr eErr =
         poSrcDS->GetRasterBand(1)->RasterIO(
             eRWFlag, nXOff, nYOff, nXSize, nYSize,
             pData, nBufXSize, nBufYSize, eBufType,
             nPixelSpace, nLineSpace, psExtraArg ) ;
     if( bInvertValues )
     {
         for( int j = 0; j < nBufYSize; j++ )
         {
             for( int i = 0; i < nBufXSize; i++ )
                 ((GByte*)pData)[j * nLineSpace + i * nPixelSpace] =
                     1 - ((GByte*)pData)[j * nLineSpace +
                                         i * nPixelSpace];
         }
     }
     return eErr;
 }
Пример #11
0
void ECWThread::run()
{
    try{
        GDALDataset *poSrcDS = (GDALDataset *)GDALOpen(TO8F(inputPath),GA_ReadOnly);
        if (poSrcDS==NULL)
            throw tr("Open input file failed!");

        if (poSrcDS->GetRasterBand(1)->GetRasterDataType()!=GDT_Byte)
            throw tr("Data type of input file is not byte!");

        GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName("JP2ECW");
        if (poDriver == NULL)
            throw tr("Data driver of ECW not found!");

        char **papszOptions = NULL;
        papszOptions = CSLSetNameValue( papszOptions, "LARGE_OK", "YES" );
//        papszOptions = CSLSetNameValue( papszOptions, "TARGET", "0" );



        GDALDataset *poDstDS = poDriver->CreateCopy(TO8F(outputPath),poSrcDS,NULL,papszOptions,progress,this);
        if (poDstDS==NULL)
            throw tr("Generate ecw file failed!");
        GDALClose(poSrcDS);
        GDALClose(poDstDS);

        updateProgressBar(100);
    }
    catch (const QString &msg)
    {
        qDebug()<<msg;
    }
}
Пример #12
0
Handle<Value> DatasetBands::get(const Arguments& args)
{
	HandleScope scope;

	Handle<Object> parent = args.This()->GetHiddenValue(String::NewSymbol("parent_"))->ToObject();
	Dataset *ds = ObjectWrap::Unwrap<Dataset>(parent);
	
	if (ds->uses_ogr){
		OGRDataSource* raw = ds->getDatasource();
		if (!raw) {
			return NODE_THROW("Dataset object has already been destroyed");
		}
		return Null();
	} else {
		GDALDataset* raw = ds->getDataset();
		if (!raw) {
			return NODE_THROW("Dataset object has already been destroyed");
		}
		int band_id;
		NODE_ARG_INT(0, "band id", band_id);
	
		GDALRasterBand *band = raw->GetRasterBand(band_id);

		return scope.Close(RasterBand::New(band));
	}
}
Пример #13
0
// Read from a RAM Tiff. This is rather generic
CPLErr DecompressTIF(buf_mgr &dst, buf_mgr &src, const ILImage &img)
{
    CPLString fname = uniq_memfname("mrf_tif_read");
    VSILFILE *fp = VSIFileFromMemBuffer(fname, (GByte *)(src.buffer), src.size, false);
    // Comes back opened, but we can't use it
    if (fp)
	VSIFCloseL(fp);
    else {
	CPLError(CE_Failure,CPLE_AppDefined,
	    CPLString().Printf("MRF: TIFF, can't open %s as a temp file", fname.c_str()));
        return CE_Failure;
    }
    GDALDataset *poTiff = reinterpret_cast<GDALDataset*>(GDALOpen(fname, GA_ReadOnly));
    if (!fp) {
	CPLError(CE_Failure,CPLE_AppDefined,
	    CPLString().Printf("MRF: TIFF, can't open page as a Tiff"));
        return CE_Failure;
    }

    CPLErr ret;
    // Bypass the GDAL caching
    if (img.pagesize.c == 1) {
	ret = poTiff->GetRasterBand(1)->ReadBlock(0,0,dst.buffer);
    } else {
	ret = poTiff->RasterIO(GF_Read,0,0,img.pagesize.x,img.pagesize.y, 
	    dst.buffer, img.pagesize.x, img.pagesize.y, img.dt, img.pagesize.c, 
	    NULL, 0,0,0);
    }
    GDALClose(poTiff);
    if (CE_None != ret)
	return ret;

    VSIUnlink(fname);
    return CE_None;
}
Пример #14
0
int PDSDataset::ParseCompressedImage()

{
    CPLString osFileName = GetKeyword( "COMPRESSED_FILE.FILE_NAME", "" );
    CleanString( osFileName );

    CPLString osPath = CPLGetPath(GetDescription());
    CPLString osFullFileName = CPLFormFilename( osPath, osFileName, NULL );
    int iBand;

    poCompressedDS = (GDALDataset*) GDALOpen( osFullFileName, GA_ReadOnly );
    
    if( poCompressedDS == NULL )
        return FALSE;

    nRasterXSize = poCompressedDS->GetRasterXSize();
    nRasterYSize = poCompressedDS->GetRasterYSize();

    for( iBand = 0; iBand < poCompressedDS->GetRasterCount(); iBand++ )
    {
        SetBand( iBand+1, new PDSWrapperRasterBand( poCompressedDS->GetRasterBand( iBand+1 ) ) );
    }
    
    return TRUE;
}
Пример #15
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;
    }
}
Пример #16
0
int GDALOverviewBand::GetOverviewCount()
{
    GDALOverviewDataset* poOvrDS = (GDALOverviewDataset*)poDS;
    if( poOvrDS->bThisLevelOnly )
        return 0;
    GDALDataset* poMainDS = poOvrDS->poMainDS;
    return poMainDS->GetRasterBand(nBand)->GetOverviewCount() - poOvrDS->nOvrLevel - 1;
}
Пример #17
0
GDALRasterBand *GDALOverviewBand::GetOverview(int iOvr)
{
    if( iOvr < 0 || iOvr >= GetOverviewCount() )
        return NULL;
    GDALOverviewDataset* poOvrDS = (GDALOverviewDataset*)poDS;
    GDALDataset* poMainDS = poOvrDS->poMainDS;
    return poMainDS->GetRasterBand(nBand)->GetOverview(iOvr + poOvrDS->nOvrLevel + 1);
}
Пример #18
0
GDALRasterBand* GDALProxyPoolRasterBand::RefUnderlyingRasterBand()
{
    GDALDataset* poUnderlyingDataset = ((GDALProxyPoolDataset*)poDS)->RefUnderlyingDataset();
    if (poUnderlyingDataset == NULL)
        return NULL;

    return poUnderlyingDataset->GetRasterBand(nBand);
}
Пример #19
0
/**
 * @brief Get an overview dataset which best matches a transformation
 *
 * Try and get an overview from the source dataset that corresponds more closely
 * to the resolution belonging to any output of the transformation.  This will
 * make downsampling operations much quicker and work around integer overflow
 * errors that can occur if downsampling very high resolution source datasets to
 * small scale (low zoom level) tiles.
 *
 * This code is adapted from that found in `gdalwarp.cpp` implementing the
 * `gdalwarp -ovr` option.
 */
static
GDALDatasetH
getOverviewDataset(GDALDatasetH hSrcDS, GDALTransformerFunc pfnTransformer, void *hTransformerArg) {
  GDALDataset* poSrcDS = static_cast<GDALDataset*>(hSrcDS);
  GDALDataset* poSrcOvrDS = NULL;
  int nOvLevel = -2;
  int nOvCount = poSrcDS->GetRasterBand(1)->GetOverviewCount();
  if( nOvCount > 0 )
    {
      double adfSuggestedGeoTransform[6];
      double adfExtent[4];
      int    nPixels, nLines;
      /* Compute what the "natural" output resolution (in pixels) would be for this */
      /* input dataset */
      if( GDALSuggestedWarpOutput2(hSrcDS, pfnTransformer, hTransformerArg,
                                   adfSuggestedGeoTransform, &nPixels, &nLines,
                                   adfExtent, 0) == CE_None)
        {
          double dfTargetRatio = 1.0 / adfSuggestedGeoTransform[1];
          if( dfTargetRatio > 1.0 )
            {
              int iOvr;
              for( iOvr = -1; iOvr < nOvCount-1; iOvr++ )
                {
                  double dfOvrRatio = (iOvr < 0) ? 1.0 : (double)poSrcDS->GetRasterXSize() /
                    poSrcDS->GetRasterBand(1)->GetOverview(iOvr)->GetXSize();
                  double dfNextOvrRatio = (double)poSrcDS->GetRasterXSize() /
                    poSrcDS->GetRasterBand(1)->GetOverview(iOvr+1)->GetXSize();
                  if( dfOvrRatio < dfTargetRatio && dfNextOvrRatio > dfTargetRatio )
                    break;
                  if( fabs(dfOvrRatio - dfTargetRatio) < 1e-1 )
                    break;
                }
              iOvr += (nOvLevel+2);
              if( iOvr >= 0 )
                {
                  //std::cout << "CTB WARPING: Selecting overview level " << iOvr << " for output dataset " << nPixels << "x" << nLines << std::endl;
                  poSrcOvrDS = GDALCreateOverviewDataset( poSrcDS, iOvr, FALSE, FALSE );
                }
            }
        }
    }

  return static_cast<GDALDatasetH>(poSrcOvrDS);
}
Пример #20
0
int GDAL_EDBFile::GetBlockHeight( int nChannel ) const

{
    int nWidth, nHeight;

    poDS->GetRasterBand(nChannel)->GetBlockSize( &nWidth, &nHeight );

    return nHeight;
}
Пример #21
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;
}
Пример #22
0
bool rgb_image::read_image()
{
    int fd;
    int i;
    unsigned char header[16];
    unsigned char jfif[] = {
        0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46,
        0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01
    };
    GDALDataset *df;
    GDALRasterBand *bd;
    int bands;

    fd = open ( pathname.c_str(), O_RDWR );
    if ( fd < 0 ) {
        fprintf(stderr,"Could not open %s to patch jpeg header\n",
                pathname.c_str() );
        return false;
    }
    read ( fd, header, 16 );
    if ( bcmp(header,jfif,4) != 0 ) {
        fprintf(stderr,"Apparently %s is not a jpeg file\n",
                pathname.c_str() );
        return false;
    }
    if ( bcmp(header,jfif,16) != 0 ) {
        lseek ( fd, (off_t)0, SEEK_SET );
        write ( fd, jfif, 16 );
    }
    close ( fd );

    df = (GDALDataset *) GDALOpen( pathname.c_str(), GA_ReadOnly );
    if( df == NULL ) {
        fprintf(stderr,"Could not open %s\n", pathname.c_str() );
        exit(1);
    }

    rows = df->GetRasterYSize();
    cols = df->GetRasterXSize();
    bands = df->GetRasterCount();
    //create_image(rows,cols);

    if ( bands < 3 ) {
        fprintf(stderr,"%s does not have 3 bands\n",
                pathname.c_str() );
        delete df;
        return false;
    }

    for ( i = 0; i < 3; i++ ) {
        bd = df->GetRasterBand(i+1);
        bd->RasterIO ( GF_Read, 0,0, cols, rows, img[i].data, cols, rows,
                       GDT_Byte, 0,0);
    }
    delete df;
}
Пример #23
0
Handle<Value> DatasetBands::create(const Arguments& args)
{
	HandleScope scope;

	Handle<Object> parent = args.This()->GetHiddenValue(String::NewSymbol("parent_"))->ToObject();
	Dataset *ds = ObjectWrap::Unwrap<Dataset>(parent);
	
	if (ds->uses_ogr){
		return NODE_THROW("Dataset does not support getting creating bands");
	} 

	GDALDataset* raw = ds->getDataset();
	if (!raw) {
		return NODE_THROW("Dataset object has already been destroyed");
	}

	GDALDataType type;
	Handle<Array> band_options = Array::New(0);
	char **options = NULL;
	std::string *options_str = NULL;

	//NODE_ARG_ENUM(0, "data type", GDALDataType, type);
	if(args.Length() < 1) {
		return NODE_THROW("data type argument needed");
	}
	if(args[0]->IsString()){
		std::string type_name = TOSTR(args[0]);
		type = GDALGetDataTypeByName(type_name.c_str());
	} else if (args[0]->IsNull() || args[0]->IsUndefined()) {
		type = GDT_Unknown;
	} else {
		return NODE_THROW("data type must be string or undefined");
	}

	NODE_ARG_ARRAY_OPT(1, "band creation options", band_options);

	if (band_options->Length() > 0) {
		options     = new char* [band_options->Length()];
		options_str = new std::string [band_options->Length()];
		for (unsigned int i = 0; i < band_options->Length(); ++i) {
			options_str[i] = TOSTR(band_options->Get(i));
			options[i] = (char*) options_str[i].c_str();
		}
	}

	CPLErr err = raw->AddBand(type, options);

	if(options)	    delete [] options;
	if(options_str)	delete [] options_str;

	if (err) {
		return NODE_THROW_CPLERR(err);
	}

	return scope.Close(RasterBand::New(raw->GetRasterBand(raw->GetRasterCount()), raw));
}
Пример #24
0
//
// Uses GDAL to create a temporary TIF file, using the band create options
// copies the content to the destination buffer then erases the temp TIF
//
static CPLErr CompressTIF(buf_mgr &dst, buf_mgr &src, const ILImage &img, char **papszOptions)
{
    CPLErr ret;
    GDALDriver *poTiffDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
    VSIStatBufL statb;
    CPLString fname = uniq_memfname("mrf_tif_write");

    GDALDataset *poTiff = poTiffDriver->Create(fname, img.pagesize.x, img.pagesize.y,
                                               img.pagesize.c, img.dt, papszOptions );

    // Read directly to avoid double caching in GDAL
    // Unfortunately not possible for multiple bands
    if (img.pagesize.c == 1) {
        ret = poTiff->GetRasterBand(1)->WriteBlock(0,0,src.buffer);
    } else {
        ret = poTiff->RasterIO(GF_Write, 0,0,img.pagesize.x,img.pagesize.y,
            src.buffer, img.pagesize.x, img.pagesize.y, img.dt, img.pagesize.c,
            NULL, 0,0,0
#if GDAL_VERSION_MAJOR >= 2
            ,NULL
#endif
            );
    }
    if (CE_None != ret) return ret;
    GDALClose(poTiff);

    // Check that we can read the file
    if (VSIStatL(fname, &statb))
    {
        CPLError(CE_Failure,CPLE_AppDefined,
            "MRF: TIFF, can't stat %s", fname.c_str());
        return CE_Failure;
    }

    if (size_t(statb.st_size) > dst.size)
    {
        CPLError(CE_Failure,CPLE_AppDefined,
            "MRF: TIFF, Tiff generated is too large");
        return CE_Failure;
    }

    VSILFILE *pf = VSIFOpenL(fname,"rb");
    if (pf == NULL)
    {
        CPLError(CE_Failure,CPLE_AppDefined,
            "MRF: TIFF, can't open %s", fname.c_str());
        return CE_Failure;
    }

    VSIFReadL(dst.buffer, static_cast<size_t>(statb.st_size), 1, pf);
    dst.size = static_cast<size_t>(statb.st_size);
    VSIFCloseL(pf);
    VSIUnlink(fname);

    return CE_None;
}
Пример #25
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;
	}


}
Пример #26
0
 CALSWrapperSrcBand(GDALDataset* poSrcDSIn)
 {
     this->poSrcDS = poSrcDSIn;
     SetMetadataItem("NBITS", "1", "IMAGE_STRUCTURE");
     poSrcDS->GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
     eDataType = GDT_Byte;
     bInvertValues = TRUE;
     GDALColorTable* poCT = poSrcDS->GetRasterBand(1)->GetColorTable();
     if( poCT != NULL && poCT->GetColorEntryCount() >= 2 )
     {
         const GDALColorEntry* psEntry1 = poCT->GetColorEntry(0);
         const GDALColorEntry* psEntry2 = poCT->GetColorEntry(1);
         if( psEntry1->c1 == 255 && psEntry1->c2 == 255 && psEntry1->c3 == 255 &&
             psEntry2->c1 == 0 && psEntry2->c2 == 0 && psEntry2->c3 == 0 )
         {
             bInvertValues = FALSE;
         }
     }
 }
Пример #27
0
/*
     * Initializes the object, assuming that filename, origin, size, etc are already set on the
     * member variables. Makes sure the raster can be opened, sets the block size, NODATA value,
     * pixel size, and the extent of the raster. If not using the full image then makes sure that
     * the subset chosen (based on origin and size) is valid. If using the full image then sets the
     * size and origin is assumed to be 0,0 and is set in the constructor.
     * @param fullImage True if using the full image, False if using a subset.
     */
void Raster::Init(bool bFullImage)
{
    Init();
    GDALDataset * ds = (GDALDataset*) GDALOpen(m_sFilePath, GA_ReadOnly);

    if (ds == NULL)
        throw RasterManagerException(INPUT_FILE_NOT_VALID, CPLGetLastErrorMsg());

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

    double dRMin, dRMax, dRMean, dRStdDev;

    // Get some easy stats that GDAL gives us
    band->GetStatistics( 0 , true, &dRMin, &dRMax, &dRMean, &dRStdDev );
    m_dRasterMax = dRMax;
    m_dRasterMin = dRMin;

    m_dRasterMean = dRMean;
    m_dRasterStdDev = dRStdDev;

    OGRLinearRing ring = OGRLinearRing();
    if (bFullImage)
    {
        SetCols( band->GetXSize() );
        SetRows( band->GetYSize() );

        ring.addPoint(GetLeft(), GetTop());
        ring.addPoint(GetLeft(), GetTop() + (GetCellHeight() * GetRows()));
        ring.addPoint(GetLeft() + (GetCellWidth() * GetCols()), GetTop() + (GetCellHeight() * GetRows()));
        ring.addPoint(GetLeft() + (GetCellWidth() * GetCols()), GetTop());
        ring.closeRings();
    }
    else
    {
        if ((GetLeft() + GetCols() > band->GetXSize()) || (GetTop() + GetRows() > band->GetYSize()))
        {
            QString sErr = QString("Invalid origin ( %1, %2 ) and size ( %5, %6 ) for file: %7")
                    .arg(GetLeft())
                    .arg(GetTop())
                    .arg(GetCols())
                    .arg(GetRows())
                    .arg(FilePath());
            throw RasterManagerException(INPUT_FILE_NOT_VALID, sErr);
        }
        double xMapOrigin = GetLeft() + (GetLeft() * GetCellWidth());
        double yMapOrigin = GetTop() + (GetTop() * GetCellHeight());
        ring.addPoint(xMapOrigin, yMapOrigin);
        ring.addPoint(xMapOrigin, yMapOrigin + (GetCellHeight() * GetRows()));
        ring.addPoint(xMapOrigin + (GetCellWidth() * GetCols()), yMapOrigin + (GetCellHeight() * GetRows()));
        ring.addPoint(xMapOrigin + (GetCellWidth() * GetCols()), yMapOrigin);
        ring.closeRings();
    }
    GDALClose(ds);

}
Пример #28
0
int GDAL_EDBFile::ReadBlock( int channel,
                             int block_index, void *buffer,
                             int win_xoff, int win_yoff,
                             int win_xsize, int win_ysize )

{
    GDALRasterBand *poBand = poDS->GetRasterBand(channel);
    int nBlockXSize, nBlockYSize;
    int nBlockX, nBlockY;
    int nWidthInBlocks;
    int nPixelOffset;
    int nLineOffset;

    if( GetType(channel) == CHN_UNKNOWN )
    {
        ThrowPCIDSKException("%s channel type not supported for PCIDSK access.",
                             GDALGetDataTypeName(poBand->GetRasterDataType()) );
    }

    poBand->GetBlockSize( &nBlockXSize, &nBlockYSize );

    nWidthInBlocks = (poBand->GetXSize() + nBlockXSize - 1) / nBlockXSize;
    
    nBlockX = block_index % nWidthInBlocks;
    nBlockY = block_index / nWidthInBlocks;

    nPixelOffset = GDALGetDataTypeSize(poBand->GetRasterDataType()) / 8;
    nLineOffset = win_xsize * nPixelOffset;

/* -------------------------------------------------------------------- */
/*      Are we reading a partial block at the edge of the database?     */
/*      If so, ensure we don't read off the database.                   */
/* -------------------------------------------------------------------- */
    if( nBlockX * nBlockXSize + win_xoff + win_xsize > poBand->GetXSize() )
        win_xsize = poBand->GetXSize() - nBlockX * nBlockXSize - win_xoff;

    if( nBlockY * nBlockYSize + win_yoff + win_ysize > poBand->GetYSize() )
        win_ysize = poBand->GetYSize() - nBlockY * nBlockYSize - win_yoff;

    CPLErr eErr = poBand->RasterIO( GF_Read, 
                                    nBlockX * nBlockXSize + win_xoff, 
                                    nBlockY * nBlockYSize + win_yoff,
                                    win_xsize, win_ysize, 
                                    buffer, win_xsize, win_ysize, 
                                    poBand->GetRasterDataType(),
                                    nPixelOffset, nLineOffset, NULL );

    if( eErr != CE_None )
    {
        ThrowPCIDSKException( "%s", CPLGetLastErrorMsg() );
    }

    return 1;
}
Пример #29
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();
}
Пример #30
0
void getGDALDimensions(const std::string &filename, int &height, int &width){
  GDALAllRegister();
  GDALDataset *fin = (GDALDataset*)GDALOpen(filename.c_str(), GA_ReadOnly);
  assert(fin!=NULL);

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

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

  GDALClose(fin);
}