raster.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. ***************************************************************************
  3. raster.py
  4. ---------------------
  5. Date : February 2013
  6. Copyright : (C) 2013 by Victor Olaya and Alexander Bruy
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya and Alexander Bruy'
  18. __date__ = 'February 2013'
  19. __copyright__ = '(C) 2013, Victor Olaya and Alexander Bruy'
  20. import struct
  21. from osgeo import gdal
  22. from qgis.core import QgsProcessingException
  23. def scanraster(layer, feedback, band_number=1):
  24. filename = str(layer.source())
  25. dataset = gdal.Open(filename, gdal.GA_ReadOnly)
  26. band = dataset.GetRasterBand(band_number)
  27. nodata = band.GetNoDataValue()
  28. bandtype = gdal.GetDataTypeName(band.DataType)
  29. for y in range(band.YSize):
  30. feedback.setProgress(y / float(band.YSize) * 100)
  31. scanline = band.ReadRaster(0, y, band.XSize, 1, band.XSize, 1,
  32. band.DataType)
  33. if bandtype == 'Byte':
  34. values = struct.unpack('B' * band.XSize, scanline)
  35. elif bandtype == 'Int16':
  36. values = struct.unpack('h' * band.XSize, scanline)
  37. elif bandtype == 'UInt16':
  38. values = struct.unpack('H' * band.XSize, scanline)
  39. elif bandtype == 'Int32':
  40. values = struct.unpack('i' * band.XSize, scanline)
  41. elif bandtype == 'UInt32':
  42. values = struct.unpack('I' * band.XSize, scanline)
  43. elif bandtype == 'Float32':
  44. values = struct.unpack('f' * band.XSize, scanline)
  45. elif bandtype == 'Float64':
  46. values = struct.unpack('d' * band.XSize, scanline)
  47. else:
  48. raise QgsProcessingException('Raster format not supported')
  49. for value in values:
  50. if value == nodata:
  51. value = None
  52. yield value
  53. def mapToPixel(mX, mY, geoTransform):
  54. (pX, pY) = gdal.ApplyGeoTransform(
  55. gdal.InvGeoTransform(geoTransform), mX, mY)
  56. return (int(pX), int(pY))
  57. def pixelToMap(pX, pY, geoTransform):
  58. return gdal.ApplyGeoTransform(geoTransform, pX + 0.5, pY + 0.5)