16

How to take cell size per X,Y using simple python or GDAL or RASTERIO?
and hot to count how many pixels have my raster with some packages..

I have find some code but is pyqgis and I don't need this package :

ras  = QgsRasterLayer("C:/Users/myname/raster.tif")
pixelSizeX= ras.rasterUnitsPerPixelX()
pixelSizeY = ras.rasterUnitsPerPixelY()

print pixelSizeX
print pixelSizeY

1 Answer 1

47

With PyQGIS

ras  = QgsRasterLayer("raster.tif")
pixelSizeX= ras.rasterUnitsPerPixelX()
pixelSizeY = ras.rasterUnitsPerPixelY()
print pixelSizeX
2.11668210081
print pixelSizeY
2.11685012701

With GDAL

from osgeo import gdal
raster = gdal.Open('raster.tif')
gt =raster.GetGeoTransform()
print gt
(258012.37107330866, 2.11668210080698, 0.0, 163176.6385398821, 0.0, -2.1168501270110074)
pixelSizeX = gt[1]
pixelSizeY =-gt[5]
print pixelSizeX
2.11668210080698
print pixelSizeY
2.1168501270110074

With Rasterio

import rasterio
raster =  rasterio.open('raster.tif')
gt = raster.affine
print gt
Affine(2.11668210080698, 0.0, 258012.37107330866,
   0.0, -2.1168501270110074, 163176.6385398821)
pixelSizeX = gt[0]
pixelSizeY =-gt[4]
print pixelSizeX
2.11668210080698
print pixelSizeY
2.1168501270110074

Or (from sgillies)

pixelSizeX, pixelSizeY  = raster.res
print pixelSizeX
2.11668210081
print pixelSizeY
2.11685012701
9
  • thank you very much,can I use GDAL or RASTERIO to take complete metadata one by one in specific variables like pixelSizeX,pixelSizeY?Because now I use some algorithms from GDAL and some from RASTERIO in the some function and my app is slowly I thing. Jun 12, 2017 at 17:25
  • 1
    Yes, without problem, look at the Python GDAL/OGR Cookbook for example
    – gene
    Jun 12, 2017 at 18:48
  • 11
    Gene, better to do pxsz, pysz = raster.res with Rasterio.
    – sgillies
    Jun 12, 2017 at 20:06
  • 8
    Using Rasterio 1.0.15, gt = raster.affine should be gt = raster.transform
    – Aaron
    Feb 5, 2019 at 5:03
  • 1
    With the new rasterio version (mine is 1.1.5), there is no raster.affine Instead, we need to use gt = raster.transform
    – beahacker
    Aug 31, 2020 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.