4

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
17

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
  • 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. – Chris Papas Jun 12 '17 at 17:25
  • 1
    Yes, without problem, look at the Python GDAL/OGR Cookbook for example – gene Jun 12 '17 at 18:48
  • in page with get raster metadata have only specific I need all – Chris Papas Jun 12 '17 at 18:55
  • 2
    Gene, better to do pxsz, pysz = raster.res with Rasterio. – sgillies Jun 12 '17 at 20:06
  • Just to make things smoother, the command for opening raster in gdal is gdal.Open('raster.tif') (with 'O') – shahryar Mar 1 '18 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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