1

I want the code to read 1st pixel from a bunch of rasters (for eg. 1st pixel from 6 different rasters (having same extent and same number of pixels) and convert it into array followed by reading 2nd pixel from each raster and so on till the last pixel so that the value can be stored and finally be used to make graphs and plots for each/same pixel number in various different images in one folder.

Here is an example python code that I have written.

for file in os.listdir(path):
    if(files[23:27]=='NDVI'): #image name has NDVI in it
        gdal.UseExceptions()
        img = gdal.Open(path_str+"\\"+file)
        img_array = np.array(img.GetRasterBand(1).ReadAsArray())
swiss_knight
  • 10,309
  • 9
  • 45
  • 117
surdeep
  • 51
  • 5
  • https://gis.stackexchange.com/questions/32995/fully-load-raster-into-a-numpy-array – GBG Sep 08 '22 at 15:09

1 Answers1

1

List all rasters, convert them to arrays, stack them into one array, slice it:

import os
import numpy as np
from osgeo import gdal_array

rasterfolder = r'/home/bera/GIS/Diverse_GIS/random_rasters/' #The folder where you keep the rasters, adjust rasters = [] #A list to hold filenames for root, folder, files in os.walk(rasterfolder): #Find all files in rasterfolder for file in files: if 'NDVI' in file and file.endswith('.tif'): #If the filename contain NDVI and ends with .tif print(file) rasters.append(os.path.join(root, file)) #Append the full path and filename to the list arrays = [gdal_array.LoadFile(r) for r in sorted(rasters)] #Create a list of arrays

stack = np.dstack(arrays) #Create a stacked array of all arrays print(stack.shape) #Check its dimensions #(14, 16, 4) #14 rows, 16 columns, 4 dimensions/arrays with my test data

first_pixels = stack[0][0][:stack.shape[2]] #First row, first column in all dimensions/rasters #array([6, 4, 9, 5], dtype=int16)

BERA
  • 72,339
  • 13
  • 72
  • 161