Python >> Tutoriel Python >  >> Python Tag >> NumPy

Charger complètement le raster dans un tableau numpy ?

si vous avez des liaisons python-gdal :

import numpy as np
from osgeo import gdal
ds = gdal.Open("mypic.tif")
myarray = np.array(ds.GetRasterBand(1).ReadAsArray())

Et vous avez terminé :

myarray.shape
(2610,4583)
myarray.size
11961630
myarray
array([[        nan,         nan,         nan, ...,  0.38068664,
     0.37952521,  0.14506227],
   [        nan,         nan,         nan, ...,  0.39791253,
            nan,         nan],
   [        nan,         nan,         nan, ...,         nan,
            nan,         nan],
   ..., 
   [ 0.33243281,  0.33221543,  0.33273876, ...,         nan,
            nan,         nan],
   [ 0.33308044,  0.3337177 ,  0.33416209, ...,         nan,
            nan,         nan],
   [ 0.09213851,  0.09242494,  0.09267616, ...,         nan,
            nan,         nan]], dtype=float32)

Vous pouvez utiliser rasterio pour s'interfacer avec les tableaux NumPy. Pour lire un raster dans un tableau :

import rasterio

with rasterio.open('/path/to/raster.tif', 'r') as ds:
    arr = ds.read()  # read all raster values

print(arr.shape)  # this is a 3D numpy array, with dimensions [band, row, col]

Cela lira tout dans un tableau numpy 3D arr , de cotes [band, row, col] .

Voici un exemple avancé pour lire, modifier un pixel, puis le réenregistrer dans le raster :

with rasterio.open('/path/to/raster.tif', 'r+') as ds:
    arr = ds.read()  # read all raster values
    arr[0, 10, 20] = 3  # change a pixel value on band 1, row 11, column 21
    ds.write(arr)

Le raster sera écrit et fermé à la fin de l'instruction "with".


Certes, je lis une ancienne image png ordinaire, mais cela fonctionne avec scipy (imsave utilise PIL cependant):

>>> import scipy
>>> import numpy
>>> img = scipy.misc.imread("/home/chad/logo.png")
>>> img.shape
(81, 90, 4)
>>> array = numpy.array(img)
>>> len(array)
81
>>> scipy.misc.imsave('/home/chad/logo.png', array)

Mon png résultant est également de 81 x 90 pixels.