I found the following code for crop classification and I am trying to understand it.

# We have 10 images and 5 bands for each image so we’ll have a total of 50 columns in our data frame
# we’ll sample the 100,000 pixels for each class to avoid overfitting

temp = pd.DataFrame()
final = pd.DataFrame()
for c in top_classes:

    # print('\n Reading for class: {} \n'.format(c))

    #Read image ``img`` and return ``np.array`` of image values Image will be (nband, nrow, ncol)

     for img in images:

        train_ds = gdal.Open(img, gdal.GA_ReadOnly)

        nrow, ncol, nband = train_ds.RasterXSize, train_ds.RasterYSize, train_ds.RasterCount
        dtype = gdal_array.GDALTypeCodeToNumericTypeCode(train_ds.GetRasterBand(1).DataType)

        #print('Image {}:  width= {}, height= {}, number of bands= {}'.format(img, nrow, ncol, nband))

        img_b1 = np.zeros((ncol,nrow,nband),dtype=dtype)

        for b in range(nband):
            img_b1[:, :, b] = train_ds.GetRasterBand(b + 1).ReadAsArray()  

        Xt = img_b1[roi==c, :] 

        Xt1 = pd.DataFrame(Xt)

       # Xt2 = Xt1.sample(n=100000)

       # Xt2.reset_index(drop=True,inplace=True)

       # temp = pd.concat([Xt2,temp],axis=1)

        #temp["class"] = c

    #final = pd.concat([temp,final],axis=0)

   # gc.collect()

Can someone explain why they looped over the number of bands?

 for b in range(nband):
       img_b1[:, :, b] = train_ds.GetRasterBand(b + 1).ReadAsArray()  

1 Answer 1


This image has 5 bands. A simple RGB image has 3 bands, or 4 when it has the alpha band.

So to process, it creates the empty Numpy.Dataset(x,y,z):

img_b1 = np.zeros((ncol,nrow,nband),dtype=dtype)

Then it populates the dataset and has to do it for every band (or z level).

GetRasterBand only return one band each time.

  • does it mean that they grouped all images by band?
    – Rim Sleimi
    Commented May 13, 2020 at 21:48
  • No. They do a loop over the images. for img in images: Commented May 14, 2020 at 1:28
  • Band is the differents color. RGB (Red, Blue and Green). Or CMYK (Cyan, Magenta, Yellow and Black) or any other type. It can have too IR or UV light. And when we work with multi-band images, we have to deal with all band, one at a time. Commented May 14, 2020 at 1:36

Your Answer

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

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