PLCLine *PLCContext::getOutputLine(int line) { CPLAssert( outputDS != NULL ); int i, width = outputDS->GetRasterXSize(); PLCLine *lineObj = new PLCLine(width); for( i=0; i < outputDS->GetRasterCount(); i++ ) { CPLErr eErr; GDALRasterBand *band = outputDS->GetRasterBand(i+1); if( band->GetColorInterpretation() == GCI_AlphaBand ) eErr = band->RasterIO(GF_Read, 0, line, width, 1, lineObj->getAlpha(), width, 1, GDT_Byte, 0, 0); else eErr = band->RasterIO(GF_Read, 0, line, width, 1, lineObj->getBand(i), width, 1, GDT_Int16, 0, 0); if( eErr != CE_None ) exit(1); } return lineObj; }
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; } }
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; }
DataType ImgReader<DataType>::getValue(const UTMCoordinateType& xCoord, const UTMCoordinateType& yCoord, size_t band) const { GDALRasterBand* rasterBand = dataset->GetRasterBand(band); const size_t pixel = static_cast<size_t> ((xCoord - geoTransform[0]) / geoTransform[1]); const size_t line = static_cast<size_t> ((yCoord - geoTransform[3]) / geoTransform[5]); // XXX maybe do some error checking here to see if xCoord and yCoord are // even in the image; GDAL might do this already though DataType data; // The memory we'll read into CPLErr rasterIOError = rasterBand->RasterIO(GF_Read, pixel, line, 1, 1, // read just a single pixel &data, 1, 1, GDALDataTypeTraits<DataType>::dataType, 0, 1); // XXX do something in case there's an error return data; }
void CreateFile(const char *srcfile,const char *dstfile) { GDALAllRegister(); CPLSetConfigOption("GDAL_FILENAME_IS_UTF8","NO"); GDALDataset *pDataset=(GDALDataset *) GDALOpen( srcfile, GA_ReadOnly ); int bandNum=pDataset->GetRasterCount(); GDALRasterBand *pBand=pDataset->GetRasterBand(1); GDALDataType dataType=pBand->GetRasterDataType(); GDALDriver *pDriver=GetGDALDriverManager()->GetDriverByName("GTiff"); GDALDataset *dstDataset=pDriver->Create(dstfile,800,800,bandNum,dataType,NULL); GDALRasterBand *dstBand; //写入光栅数据 ushort *buf= new ushort[800*800]; for (int i=1;i<=bandNum;i++) { pBand=pDataset->GetRasterBand(i); pBand->RasterIO(GF_Read,3388,2204,800,800,buf,800,800,dataType,0,0); dstBand=dstDataset->GetRasterBand(i); dstBand->RasterIO(GF_Write,0,0,800,800,buf,800,800,dataType,0,0); } delete []buf; GDALClose(pDataset); GDALClose(dstDataset); }
CPLErr RawDataset::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int *panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace ) { const char* pszInterleave; /* The default GDALDataset::IRasterIO() implementation would go to */ /* BlockBasedRasterIO if the dataset is interleaved. However if the */ /* access pattern is compatible with DirectIO() we don't want to go */ /* BlockBasedRasterIO, but rather used our optimized path in RawRasterBand::IRasterIO() */ if (nXSize == nBufXSize && nYSize == nBufYSize && nBandCount > 1 && (pszInterleave = GetMetadataItem("INTERLEAVE", "IMAGE_STRUCTURE")) != NULL && EQUAL(pszInterleave, "PIXEL")) { int iBandIndex; for(iBandIndex = 0; iBandIndex < nBandCount; iBandIndex ++ ) { RawRasterBand* poBand = (RawRasterBand*) GetRasterBand(panBandMap[iBandIndex]); if( !poBand->CanUseDirectIO(nXOff, nYOff, nXSize, nYSize, eBufType ) ) { break; } } if( iBandIndex == nBandCount ) { CPLErr eErr = CE_None; for( iBandIndex = 0; iBandIndex < nBandCount && eErr == CE_None; iBandIndex++ ) { GDALRasterBand *poBand = GetRasterBand(panBandMap[iBandIndex]); GByte *pabyBandData; if (poBand == NULL) { eErr = CE_Failure; break; } pabyBandData = ((GByte *) pData) + iBandIndex * nBandSpace; eErr = poBand->RasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, (void *) pabyBandData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace ); } return eErr; } } return GDALDataset::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace ); }
void HypSpecImage::spectrum(double x, double y, double *spectrum) { int bands = m_data->GetRasterCount(); float *line = (float *) CPLMalloc(sizeof(float)); for (int b = 0; b < bands; b++) { GDALRasterBand *rb = m_data->GetRasterBand(b + 1); int i0 = floor(x); int i1 = i0 + 1; int j0 = floor(y); int j1 = j0 + 1; rb->RasterIO( GF_Read, i0, j0, 1, 1, line, 1, 1, GDT_Float32, 0, 0 ); float v00 = line[0]; rb->RasterIO( GF_Read, i1, j0, 1, 1, line, 1, 1, GDT_Float32, 0, 0 ); float v10 = line[0]; rb->RasterIO( GF_Read, i0, j1, 1, 1, line, 1, 1, GDT_Float32, 0, 0 ); float v01 = line[0]; rb->RasterIO( GF_Read, i1, j1, 1, 1, line, 1, 1, GDT_Float32, 0, 0 ); float v11 = line[0]; float id = x - i0; float jd = y - j0; float vi0 = id * v00 + (1 - id) * v10; float vi1 = id * v01 + (1 - id) * v11; float v = jd * vi0 + (1 - jd) * vi1; spectrum[b] = v; } CPLFree(line); }
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; }
void HazePerfection::invertImage(GDALDataset *pDataset, GDALDataset *dstDataset, float a) { GDALRasterBand *band = pDataset->GetRasterBand(1); GDALDataType dataType = band->GetRasterDataType(); float *pixelData = new float[nXSize*nYSize]; band->RasterIO(GF_Read, 0, 0, nXSize, nYSize, pixelData, nXSize, nYSize, GDT_Float32, 0, 0); GDALRasterBand *dstBand = dstDataset->GetRasterBand(1); for (int j = 0; j < nYSize; j++) { for (int i = 0; i < nXSize; i++) { pixelData[j*nXSize + i] = a - pixelData[j*nXSize + i]; } } dstBand->RasterIO(GF_Write, 0, 0, nXSize, nYSize, pixelData, nXSize, nYSize, GDT_Float32, 0, 0); delete[]pixelData; }
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; }
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(); }
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; }
void HazePerfection::createMark(float b) { const char *pszFormat = "GTiff"; const char *markfile = m_markfilename.c_str(); GDALDriver *poDriver = (GDALDriver*)GDALGetDriverByName(pszFormat); markDataset = poDriver->Create(markfile, nXSize, nYSize, 1, GDT_Float32, NULL); markDataset->SetGeoTransform(sGeoTrans); markDataset->SetProjection(hotDataset->GetProjectionRef()); float *pixelData = new float[nXSize*nYSize]; GDALRasterBand *maskBand = maskDataset->GetRasterBand(1); maskBand->RasterIO(GF_Read, 0, 0, nXSize, nYSize, pixelData, nXSize, nYSize, GDT_Float32, 0, 0); for (int i = 1; i < nYSize-1; i++) { for (int j = 1; j < nXSize - 1; j++) pixelData[i*nXSize + j] = b; } GDALRasterBand *markBand = markDataset->GetRasterBand(1); markBand->RasterIO(GF_Write, 0, 0, nXSize, nYSize, pixelData, nXSize, nYSize, GDT_Float32, 0, 0); delete[]pixelData; }
void PLCContext::writeOutputLine(int line, PLCLine *lineObj) { CPLAssert( outputDS != NULL ); int i, width = outputDS->GetRasterXSize(); for( i=0; i < outputDS->GetRasterCount(); i++ ) { CPLErr eErr; GDALRasterBand *band = outputDS->GetRasterBand(i+1); if( band->GetColorInterpretation() == GCI_AlphaBand ) eErr = band->RasterIO(GF_Write, 0, line, width, 1, lineObj->getAlpha(), width, 1, GDT_Byte, 0, 0); else eErr = band->RasterIO(GF_Write, 0, line, width, 1, lineObj->getBand(i), width, 1, GDT_Int16, 0, 0); if( eErr != CE_None ) exit(1); if( sourceTraceDS != NULL ) { eErr = sourceTraceDS->GetRasterBand(1)-> RasterIO(GF_Write, 0, line, width, 1, lineObj->getSource(), width, 1, GDT_UInt16, 0, 0); } if( qualityDS != NULL ) { eErr = qualityDS->GetRasterBand(1)-> RasterIO(GF_Write, 0, line, width, 1, lineObj->getQuality(), width, 1, GDT_Float32, 0, 0); } } }
int NBHeightMapper::loadTiff(const std::string& file) { #ifdef HAVE_GDAL GDALAllRegister(); GDALDataset* poDataset = (GDALDataset*)GDALOpen(file.c_str(), GA_ReadOnly); if (poDataset == 0) { WRITE_ERROR("Cannot load GeoTIFF file."); return 0; } const int xSize = poDataset->GetRasterXSize(); const int ySize = poDataset->GetRasterYSize(); double adfGeoTransform[6]; if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) { Position topLeft(adfGeoTransform[0], adfGeoTransform[3]); mySizeOfPixel.set(adfGeoTransform[1], adfGeoTransform[5]); const double horizontalSize = xSize * mySizeOfPixel.x(); const double verticalSize = ySize * mySizeOfPixel.y(); myBoundary.add(topLeft); myBoundary.add(topLeft.x() + horizontalSize, topLeft.y() + verticalSize); } else { WRITE_ERROR("Could not parse geo information from " + file + "."); return 0; } const int picSize = xSize * ySize; myRaster = (int16_t*)CPLMalloc(sizeof(int16_t) * picSize); for (int i = 1; i <= poDataset->GetRasterCount(); i++) { GDALRasterBand* poBand = poDataset->GetRasterBand(i); if (poBand->GetColorInterpretation() != GCI_GrayIndex) { WRITE_ERROR("Unknown color band in " + file + "."); clearData(); break; } if (poBand->GetRasterDataType() != GDT_Int16) { WRITE_ERROR("Unknown data type in " + file + "."); clearData(); break; } assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize()); if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, myRaster, xSize, ySize, GDT_Int16, 0, 0) == CE_Failure) { WRITE_ERROR("Failure in reading " + file + "."); clearData(); break; } } GDALClose(poDataset); return picSize; #else UNUSED_PARAMETER(file); WRITE_ERROR("Cannot load GeoTIFF file since SUMO was compiled without GDAL support."); return 0; #endif }
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 ) { return poUnderlyingBand->RasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace, psExtraArg ) ; }
void write_map(fs::path file_path, GDALDataType data_type, boost::shared_ptr<Map_Matrix<DataFormat> > data, std::string WKTprojection, GeoTransform transform, std::string driverName) throw(std::runtime_error) { 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. const char *pszFormat = driverName.c_str(); GDALDriver * poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat); if (poDriver == NULL) { throw std::runtime_error("No driver for file tyle found"); } char ** papszMetadata = poDriver->GetMetadata(); if (!(CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, FALSE))) { throw std::runtime_error("Driver does not support raster creation"); } char **papszOptions = NULL; papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "LZW"); GDALDataset *poDstDS = poDriver->Create(file_path.string().c_str(), (int)data->NCols(), (int)data->NRows(), 1, data_type, papszOptions); double adfGeoTransform[6] = {1, 1, 1, 1, 1, 1}; adfGeoTransform[0] = transform.x_origin; adfGeoTransform[1] = transform.pixel_width; adfGeoTransform[2] = transform.x_line_space; adfGeoTransform[3] = transform.y_origin; adfGeoTransform[4] = transform.pixel_height; adfGeoTransform[5] = transform.y_line_space; const char * psz_WKT = WKTprojection.c_str(); poDstDS->SetGeoTransform(adfGeoTransform); poDstDS->SetProjection(psz_WKT); DataFormat * pafScanline = new DataFormat[data->NCols() * data->NRows()]; int pafIterator = 0; for (int i = 0; i < data->NRows(); i++) { for (int j = 0; j < data->NCols(); j++) { pafScanline[pafIterator] = data->Get(i, j); pafIterator++; } } GDALRasterBand * poBand = poDstDS->GetRasterBand(1); poBand->SetNoDataValue(data->NoDataValue()); poBand->RasterIO(GF_Write, 0, 0, (int) data->NCols(), (int) data->NRows(), pafScanline, (int) data->NCols(), (int) data->NRows(), data_type, 0, 0); GDALClose( (GDALDatasetH) poDstDS); }
feature_ptr gdal_featureset::get_feature_at_point(mapnik::coord2d const& pt) { CPLErr raster_io_error = CE_None; if (band_ > 0) { unsigned raster_xsize = dataset_.GetRasterXSize(); unsigned raster_ysize = dataset_.GetRasterYSize(); double gt[6]; dataset_.GetGeoTransform(gt); double det = gt[1] * gt[5] - gt[2] * gt[4]; // subtract half a pixel width & height because gdal coord reference // is the top-left corner of a pixel, not the center. double X = pt.x - gt[0] - gt[1]/2; double Y = pt.y - gt[3] - gt[5]/2; double det1 = gt[1]*Y + gt[4]*X; double det2 = gt[2]*Y + gt[5]*X; unsigned x = static_cast<unsigned>(det2/det); unsigned y = static_cast<unsigned>(det1/det); if (x < raster_xsize && y < raster_ysize) { MAPNIK_LOG_DEBUG(gdal) << "gdal_featureset: pt.x=" << pt.x << " pt.y=" << pt.y; MAPNIK_LOG_DEBUG(gdal) << "gdal_featureset: x=" << x << " y=" << y; GDALRasterBand* band = dataset_.GetRasterBand(band_); int raster_has_nodata; double nodata = band->GetNoDataValue(&raster_has_nodata); double value; raster_io_error = band->RasterIO(GF_Read, x, y, 1, 1, &value, 1, 1, GDT_Float64, 0, 0); if (raster_io_error == CE_Failure) { throw datasource_exception(CPLGetLastErrorMsg()); } if (! raster_has_nodata || value != nodata) { // construct feature feature_ptr feature = feature_factory::create(ctx_,1); feature->set_geometry(mapnik::geometry::point<double>(pt.x,pt.y)); feature->put_new("value",value); if (raster_has_nodata) { feature->put_new("nodata",nodata); } return feature; } } } return feature_ptr(); }
TerrainTile * ctb::TerrainTiler::createTile(const TileCoordinate &coord) const { // Get a terrain tile represented by the tile coordinate TerrainTile *terrainTile = new TerrainTile(coord); GDALTile *rasterTile = createRasterTile(coord); // the raster associated with this tile coordinate GDALRasterBand *heightsBand = rasterTile->dataset->GetRasterBand(1); // Copy the raster data into an array float rasterHeights[TerrainTile::TILE_CELL_SIZE]; if (heightsBand->RasterIO(GF_Read, 0, 0, TILE_SIZE, TILE_SIZE, (void *) rasterHeights, TILE_SIZE, TILE_SIZE, GDT_Float32, 0, 0) != CE_None) { throw CTBException("Could not read heights from raster"); } delete rasterTile; // Convert the raster data into the terrain tile heights. This assumes the // input raster data represents meters above sea level. Each terrain height // value is the number of 1/5 meter units above -1000 meters. // TODO: try doing this using a VRT derived band: // (http://www.gdal.org/gdal_vrttut.html) for (unsigned short int i = 0; i < TerrainTile::TILE_CELL_SIZE; i++) { terrainTile->mHeights[i] = (i_terrain_height) ((rasterHeights[i] + 1000) * 5); } // If we are not at the maximum zoom level we need to set child flags on the // tile where child tiles overlap the dataset bounds. if (coord.zoom != maxZoomLevel()) { CRSBounds tileBounds = mGrid.tileBounds(coord); if (! (bounds().overlaps(tileBounds))) { terrainTile->setAllChildren(false); } else { if (bounds().overlaps(tileBounds.getSW())) { terrainTile->setChildSW(); } if (bounds().overlaps(tileBounds.getNW())) { terrainTile->setChildNW(); } if (bounds().overlaps(tileBounds.getNE())) { terrainTile->setChildNE(); } if (bounds().overlaps(tileBounds.getSE())) { terrainTile->setChildSE(); } } } return terrainTile; }
ERMsg C20thReanalysisProject::ReadData( CGDALDatasetEx& dataset, int x, int y, vector<float>& data) { ERMsg msg; int nbDays = dataset->GetRasterCount(); data.resize(nbDays); for(int jd=0; jd<nbDays; jd++) { GDALRasterBand* pBand = dataset->GetRasterBand(jd+1); pBand->RasterIO(GF_Read,x,y,1, 1, &(data[jd]),1, 1, GDT_Float32,0,0); } return msg; }
int GDAL_EDBFile::WriteBlock( int channel, int block_index, void *buffer) { GDALRasterBand *poBand = poDS->GetRasterBand(channel); int nBlockXSize, nBlockYSize; int nBlockX, nBlockY; int nWinXSize, nWinYSize; int nWidthInBlocks; 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; /* -------------------------------------------------------------------- */ /* 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 + nBlockXSize > poBand->GetXSize() ) nWinXSize = poBand->GetXSize() - nBlockX * nBlockXSize; else nWinXSize = nBlockXSize; if( nBlockY * nBlockYSize + nBlockYSize > poBand->GetYSize() ) nWinYSize = poBand->GetYSize() - nBlockY * nBlockYSize; else nWinYSize = nBlockYSize; CPLErr eErr = poBand->RasterIO( GF_Write, nBlockX * nBlockXSize, nBlockY * nBlockYSize, nWinXSize, nWinYSize, buffer, nWinXSize, nWinYSize, poBand->GetRasterDataType(), 0, 0, NULL ); if( eErr != CE_None ) { ThrowPCIDSKException( "%s", CPLGetLastErrorMsg() ); } return 1; }
// write image bool WriteImageGDAL( char *pDstImgFileName, unsigned char *pImageData, int width, int height, int nChannels, double trans[6]) { GDALAllRegister(); char *GType = NULL; GType = findImageTypeGDAL(pDstImgFileName); if (GType == NULL) { return false; } GDALDriver *pMemDriver = NULL; pMemDriver = GetGDALDriverManager()->GetDriverByName("MEM"); if( pMemDriver == NULL ) { return false; } GDALDataset *pMemDataSet = pMemDriver->Create("", width, height, nChannels, GDT_Byte, NULL); GDALRasterBand *pBand = NULL; int nLineCount = width * nChannels; unsigned char *ptr1 = (unsigned char *)pImageData; for (int i = 1; i <= nChannels; i++) { pBand = pMemDataSet->GetRasterBand(nChannels - i + 1); pBand->RasterIO(GF_Write, 0, 0, width, height, ptr1 + i - 1 , width, height, GDT_Byte, nChannels, nLineCount); } //Write the generated data set to the target file GDALDriver *pDstDriver = NULL; pDstDriver = (GDALDriver *)GDALGetDriverByName(GType); if (pDstDriver == NULL) { return false; } //Write to the geographic reference information pMemDataSet->SetGeoTransform( trans ); GDALDataset *poDstDS; poDstDS = pDstDriver->CreateCopy(pDstImgFileName, pMemDataSet, FALSE, NULL, NULL, NULL); if( poDstDS != NULL ) delete poDstDS; GDALClose(pMemDataSet); return true; }
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); }
feature_ptr gdal_featureset::get_feature_at_point(mapnik::coord2d const& pt) { if (band_ > 0) { unsigned raster_xsize = dataset_.GetRasterXSize(); unsigned raster_ysize = dataset_.GetRasterYSize(); double gt[6]; dataset_.GetGeoTransform(gt); double det = gt[1] * gt[5] - gt[2] * gt[4]; // subtract half a pixel width & height because gdal coord reference // is the top-left corner of a pixel, not the center. double X = pt.x - gt[0] - gt[1]/2; double Y = pt.y - gt[3] - gt[5]/2; double det1 = gt[1]*Y + gt[4]*X; double det2 = gt[2]*Y + gt[5]*X; unsigned x = static_cast<unsigned>(det2/det); unsigned y = static_cast<unsigned>(det1/det); if (x < raster_xsize && y < raster_ysize) { MAPNIK_LOG_DEBUG(gdal) << "gdal_featureset: pt.x=" << pt.x << " pt.y=" << pt.y; MAPNIK_LOG_DEBUG(gdal) << "gdal_featureset: x=" << x << " y=" << y; GDALRasterBand* band = dataset_.GetRasterBand(band_); int raster_has_nodata; double nodata = band->GetNoDataValue(&raster_has_nodata); double value; band->RasterIO(GF_Read, x, y, 1, 1, &value, 1, 1, GDT_Float64, 0, 0); if (! raster_has_nodata || value != nodata) { // construct feature feature_ptr feature = feature_factory::create(ctx_,1); std::unique_ptr<geometry_type> point = std::make_unique<geometry_type>(mapnik::geometry_type::types::Point); point->move_to(pt.x, pt.y); feature->add_geometry(point.release()); feature->put_new("value",value); if (raster_has_nodata) { feature->put_new("nodata",nodata); } return feature; } } } return feature_ptr(); }
void saveGDAL(const std::string &filename, const std::string &template_name, int xoffset, int yoffset){ GDALDataset *fintempl = (GDALDataset*)GDALOpen(template_name.c_str(), GA_ReadOnly); assert(fintempl!=NULL); //TODO: Error handle GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName("GTiff"); assert(poDriver!=NULL); //TODO: Error handle GDALDataset *fout = poDriver->Create(filename.c_str(), viewWidth(), viewHeight(), 1, myGDALType(), NULL); assert(fout!=NULL); //TODO: Error handle GDALRasterBand *oband = fout->GetRasterBand(1); oband->SetNoDataValue(no_data); //The geotransform maps each grid cell to a point in an affine-transformed //projection of the actual terrain. The geostransform is specified as follows: // Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2) // Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5) //In case of north up images, the GT(2) and GT(4) coefficients are zero, and //the GT(1) is pixel width, and GT(5) is pixel height. The (GT(0),GT(3)) //position is the top left corner of the top left pixel of the raster. double geotrans[6]; fintempl->GetGeoTransform(geotrans); //We shift the top-left pixel of hte image eastward to the appropriate //coordinate geotrans[0] += xoffset*geotrans[1]; //We shift the top-left pixel of the image southward to the appropriate //coordinate geotrans[3] += yoffset*geotrans[5]; #ifdef DEBUG std::cerr<<"Filename: "<<std::setw(20)<<filename<<" Xoffset: "<<std::setw(6)<<xoffset<<" Yoffset: "<<std::setw(6)<<yoffset<<" Geotrans0: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[0]<<" Geotrans3: "<<std::setw(10)<<std::setprecision(10)<<std::fixed<<geotrans[3]<< std::endl; #endif fout->SetGeoTransform(geotrans); const char* projection_string=fintempl->GetProjectionRef(); fout->SetProjection(projection_string); GDALClose(fintempl); for(int y=0;y<view_height;y++) oband->RasterIO(GF_Write, 0, y, viewWidth(), 1, data[y].data(), viewWidth(), 1, myGDALType(), 0, 0); GDALClose(fout); }
feature_ptr gdal_featureset::get_feature_at_point(mapnik::coord2d const& pt) { if (band_ > 0) { unsigned raster_xsize = dataset_.GetRasterXSize(); unsigned raster_ysize = dataset_.GetRasterYSize(); double gt[6]; dataset_.GetGeoTransform(gt); double det = gt[1] * gt[5] - gt[2] * gt[4]; // subtract half a pixel width & height because gdal coord reference // is the top-left corner of a pixel, not the center. double X = pt.x - gt[0] - gt[1]/2; double Y = pt.y - gt[3] - gt[5]/2; double det1 = gt[1]*Y + gt[4]*X; double det2 = gt[2]*Y + gt[5]*X; unsigned x = det2/det, y = det1/det; if (x < raster_xsize && y < raster_ysize) { #ifdef MAPNIK_DEBUG std::clog << boost::format("GDAL Plugin: pt.x=%f pt.y=%f") % pt.x % pt.y << std::endl; std::clog << boost::format("GDAL Plugin: x=%f y=%f") % x % y << std::endl; #endif GDALRasterBand* band = dataset_.GetRasterBand(band_); int hasNoData; double nodata = band->GetNoDataValue(&hasNoData); double value; band->RasterIO(GF_Read, x, y, 1, 1, &value, 1, 1, GDT_Float64, 0, 0); if (! hasNoData || value != nodata) { // construct feature feature_ptr feature(new Feature(1)); geometry_type * point = new geometry_type(mapnik::Point); point->move_to(pt.x, pt.y); feature->add_geometry(point); (*feature)["value"] = value; return feature; } } } return feature_ptr(); }
bool ImageTIF::OpenImage(std::string filename) { GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( filename.c_str(), GA_ReadOnly ); ///On initialise toutes les caractèristiques à l'aide des données de l'image Geotif. _ySize = poDataset->GetRasterYSize(); _xSize = poDataset->GetRasterXSize(); _bandCount = 12; GDALRasterBand *bands; _data.resize(_ySize*_xSize*(_bandCount)); if( poDataset != NULL ) { /// Pour chaque bande on lit une ligne, puis on parcourt les colonnes for (unsigned int b = 1; b <= _bandCount+1; ++b ) { bands = poDataset->GetRasterBand(b); // iterate over image row by row for (unsigned int row = 0; row < _ySize; ++row ) { float *scanline; scanline = (float *) CPLMalloc( sizeof( float ) * _xSize ); bands->RasterIO( GF_Read, 0, row, _xSize, 1, scanline, _xSize, 1, GDT_Float32, 0, 0 ); for (unsigned int col = 0; col < _xSize; ++col) { // get value in (row, col) from band r if(b<11) { _data[b-1+_bandCount*row+col*_bandCount*_ySize] = scanline[col]; } else if(b>11) { _data[b-2+_bandCount*row+col*_bandCount*_ySize] = scanline[col]; } } } } GDALClose(poDataset); return true; } return false; }
void HypSpecImage::band(int band, FloatImage *raster) { GDALRasterBand *rb = m_data->GetRasterBand(band); int width = m_data->GetRasterXSize(); int height = m_data->GetRasterYSize(); int lineSize = rb->GetXSize(); float *line = (float *) CPLMalloc(sizeof(float)*lineSize); for (int i = 0; i < height; i++) { rb->RasterIO(GF_Read, 0, i, lineSize, 1, line, lineSize, 1, GDT_Float32, 0, 0); for (int j = 0; j < width; j++) { raster->set(j, i, 0, line[j]); } } CPLFree(line); }
static GDALDataset* createDataSetFromImage(const osg::Image* image, double minX, double minY, double maxX, double maxY, const std::string &projection) { //Clone the incoming image osg::ref_ptr<osg::Image> clonedImage = new osg::Image(*image); //Flip the image clonedImage->flipVertical(); GDALDataset* srcDS = createMemDS(image->s(), image->t(), minX, minY, maxX, maxY, projection); //Write the image data into the memory dataset //If the image is already RGBA, just read all 4 bands in one call if (image->getPixelFormat() == GL_RGBA) { srcDS->RasterIO(GF_Write, 0, 0, clonedImage->s(), clonedImage->t(), (void*)clonedImage->data(), clonedImage->s(), clonedImage->t(), GDT_Byte, 4, NULL, 4, 4 * image->s(), 1); } else if (image->getPixelFormat() == GL_RGB) { //OE_NOTICE << "[osgEarth::GeoData] Reprojecting RGB " << std::endl; //Read the read, green and blue bands srcDS->RasterIO(GF_Write, 0, 0, clonedImage->s(), clonedImage->t(), (void*)clonedImage->data(), clonedImage->s(), clonedImage->t(), GDT_Byte, 3, NULL, 3, 3 * image->s(), 1); //Initialize the alpha values to 255. unsigned char *alpha = new unsigned char[clonedImage->s() * clonedImage->t()]; memset(alpha, 255, clonedImage->s() * clonedImage->t()); GDALRasterBand* alphaBand = srcDS->GetRasterBand(4); alphaBand->RasterIO(GF_Write, 0, 0, clonedImage->s(), clonedImage->t(), alpha, clonedImage->s(),clonedImage->t(), GDT_Byte, 0, 0); delete[] alpha; } else { OE_WARN << LC << "createDataSetFromImage: unsupported pixel format " << std::hex << image->getPixelFormat() << std::endl; } srcDS->FlushCache(); return srcDS; }
Dataset::ElevationDataPtr Dataset::convertToElevationData() const { if ( 0x0 == _data ) return 0x0; GDALRasterBand* band ( _data->GetRasterBand ( 1 ) ); if ( 0x0 == band ) return 0x0; // Get the width and height. const int width ( _data->GetRasterXSize() ); const int height ( _data->GetRasterYSize() ); // Read the values. const int size ( width * height ); std::vector<IElevationData::ValueType> bytes ( size, 0 ); if ( CE_None == band->RasterIO ( GF_Read, 0, 0, width, height, &bytes[0], width, height, GDT_Float32, 0, 0 ) ) { Minerva::Core::ElevationData::RefPtr elevationData ( new Minerva::Core::ElevationData ( width, height ) ); // The no data value. const double noDataValue ( band->GetNoDataValue() ); elevationData->noDataValue ( static_cast<IElevationData::ValueType> ( noDataValue ) ); for ( int row = 0; row < height; ++row ) { for ( int column = 0; column < width; ++column ) { const unsigned int index ( column + ( row * width ) ); elevationData->value ( column, ( height - row - 1 ), bytes.at ( index ) ); } } return ElevationDataPtr ( elevationData ); } return 0x0; }