1

I try to plot hillshade image processed with GDAL with matplotib basemap coastline, but the resulting projection did not match. Here are my code:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from osgeo import gdal

bounds = [125.25, 131.5, -4.5, -2.5]
dem = gdal.Open('raster.tif')
hillshade = gdal.DEMProcessing('hillshade.tif', dem, 'hillshade',
                               computeEdges = True,
                              multiDirectional = True, zFactor=2)
hillshadeArray = hillshade.GetRasterBand(1).ReadAsArray()
elevArray = dem.GetRasterBand(1).ReadAsArray()

plt.figure(figsize=(40,15))
m = Basemap(epsg = '4326', 
            resolution = 'h', 
            llcrnrlon = bounds[0], 
            llcrnrlat = bounds[2],
            urcrnrlon = bounds[1], 
            urcrnrlat = bounds[3])
m.imshow(hillshadeArray, cmap='gray', origin='upper')
m.imshow(elev, cmap='terrain', alpha=0.33, origin='upper')
m.drawcoastlines(color='black', linewidth=2)
m.drawmeridians(np.arange(125, 132, 0.25), labels=[0,0,0,1])
m.drawparallels(np.arange(-5, -2, 0.25), labels=[1,0,0,0])
plt.colorbar()
plt.show()

and here are the results: enter image description here

What is the issue here and how to fix it?

2
  • 2
    I would say at a guess that your data sources Basemap and raster.tif are in a different coordinate reference systems and have different relative accuracies. How do they look in QGIS? Sorry, I'm not a web developer but been in GIS long enough to have an opinion on your data sources. Commented Mar 31, 2022 at 7:17
  • @user2856 I actually just know that basemap is actually deprecated. Thks going to check cartopy out soon. Commented Apr 1, 2022 at 9:16

1 Answer 1

2

When you read something as array it looses all georeferencing informaton. The position of your maps seems mostly ok, but the stretch in the horizontal direction is not because the cell size in x direction should not be the same as in y direction.

Check raster.tif CRS with gdalinfo raster.tif.

Try using a projected coordinate system e.g. EPSG:3857 for DEM, Hillshade and on basemap.

Another solution might be to read the raster as array, as you did, but with xoff, yoff, xsize, ysize parameters that match the upper left corner of your map extent in pixels, and number of pixels in x and y directons.

2
  • yes, the problem is the extent of the tiff image in x direction. Commented Apr 1, 2022 at 9:17
  • Super, glad I could help.
    – Alešinar
    Commented Apr 1, 2022 at 9: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.