Python plot elevation difference between two tiffs – TypeError: Invalid shape (1, 2355, 2676) for image data


I am trying to plot the elevation difference of two tiffs. The following error message occurs: TypeError: Invalid shape (1, 2355, 2676) for image data. It refers to the im = ax.imshow….. line. I don’t really understand the problem or what to do.
Thanks for any help!

# import relevant moduls
from osgeo import gdal
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import iolib, warplib, geolib, timelib, malib

# Specify input files
dem_old = '../data/2007.tif'
dem_new = '../data/2018.tif'
# generate a list of the files
dem_fn_list = [dem_old, dem_new]

# combine dems with warplib and set to extent of intersection
ds_list = warplib.memwarp_multi_fn(dem_fn_list, extent='intersection', res='min', t_srs=dem_new)

# Load datasets to NumPy masked arrays
dem_old, dem_new = [iolib.ds_getma(i) for i in ds_list]

# Calculate elevation difference for each time period
dh_list = [dem_new - dem_old]

# plot elevation difference
print('Plotting DEM difference...')
plt.rcParams.update({'font.size': 15})
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(1,1,1)
im = ax.imshow(dh_list, origin='upper', interpolation='None', cmap='seismic_r', vmin = -40, vmax = 40)
# add colorbar
# add title
plt.title("DSM elevation differences")
# disable xticks
# save figure
# show figure
Asked By: Vilerala



When you are plotting the "image" (dh_list), the dimensions of that array are (1, 2355, 2676), which is then interpreted as an image with height 1, width 2355, and 2676 channels (!). Matplotlib doesn’t know how to handle that, and throws an error.

As specified in their documentation

Supported array shapes are:

  • (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.
  • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

The first two dimensions (M, N) define the rows and columns of the image.

So you will need to reshape your image. In your case, it should be enough to define dh_list as

dh_list = dem_new - dem_old
Answered By: Florent Monin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.