2

I have a raster with 6 bands and I need to calculate the mean for all bands in the raster without value 0

I have this script but it works for one band only:

import os
from osgeo import gdal
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import ogr 

raster = gdal.Open("D:/script/NDVI2015.tif")
bands = raster.RasterCount
bands
6

geotransform = raster.GetGeoTransform()
proj= raster.GetProjection()
data = raster.GetRasterBand(2).ReadAsArray().astype('float')
meandata(2) = np.mean(data[data != 0])#calcul mean without value 0

I'm very new with Python and GDAL.

1

Building on @Luke's comment, incorporate the band number into a for loop using range():

import gdal
import numpy as np

raster = gdal.Open(r'/path/to/your/image.tif')
bands = raster.RasterCount

for band in range(1, bands+1):
    data = raster.GetRasterBand(band).ReadAsArray().astype('float')
    mean = np.mean(data[data != 0]) #calculate mean without value 0
    print("Band %s: Mean = %s" % (band, round(mean, 2)))
  • what is 2 in last line print("Band %s: Mean = %s" % (band, round(mean, 2))) ? ( mean,2) – Majda El yacouby Jan 16 at 15:47
  • @MajdaElyacouby I am just rounding to 2 decimal places using the Python function round(). – Aaron Jan 16 at 15:49
  • your code is fonction for me and i have this result: Band 1: Mean = 1712.83 Band 2: Mean = 1803.14 Band 3: Mean = 1662.33 Band 4: Mean = 1868.77 Band 5: Mean = 1900.97 Band 6: Mean = 2031.13 thank you , but please how can i save the value of mean for all bands in dataframe ? – Majda El yacouby Jan 16 at 15:58
  • Could you please provide an example of your desired output? – Aaron Jan 16 at 16:04
  • i need the value of mean for all bands next i want to save the value in dataframe for each bands$date and after i plot the datarame like timesseries with date in X and mean of values for NDVI in axis y ! – Majda El yacouby Jan 16 at 16:13

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.