I was trying to georeference a .tif file generated from a matplotlib output using GDAL's python bindings and it seems to be off-scale. My objective was to create a geotiff file from the output of a contourf function. Code samples are pasted below.

fig = plt.figure()
plt.contour(land_reference,levels=[-9999],origin='upper', cmap='gray',extent=(77.53,81.05,28.65,31.49))
plt.contourf(Z, levels=levels,origin='upper', cmap='RdYlGn',extent=(77.53,81.05,28.65,31.49))



Then I use GDAL as follows,

from osgeo import gdal, osr
import numpy as np

src_filename ='C:/Users/MRG16-10417/Desktop/New/testspecies.tif'
dst_filename = 'C:/Users/MRG16-10417/Desktop/New/newspecies.tif'

#The row and column values of the tif file was used here

src_ds = gdal.Open(src_filename)
format = "GTiff"
driver = gdal.GetDriverByName(format)

xmin = 77.5000000002060005
xmax = 81.0833333335421997
ymin = 28.6666666666176049
ymax = 31.4999999999532037

# Open destination dataset
dst_ds = driver.CreateCopy(dst_filename, src_ds, 0)

xres = (xmax-xmin)/float(ncols)
yres = (ymax-ymin)/float(nrows)
geotransform=(xmin,xres,0,ymax,0, -yres)  

# Set location

# Get raster projection
epsg = 4326
srs = osr.SpatialReference()
dest_wkt = srs.ExportToWkt()

# Set projection

# Close files
dst_ds = None
src_ds = None

The resultant image on QGIS,enter image description here As you can see the image is slightly off scale and isn't exactly overlapping on the reference .shp file of the same geographic extents and projection.

What could be the reason for this?

Is it because the source image that is incorrect, as matplotlib could be scaling down the image?


I eventually figured out that matplotlib by default interpolates and I was losing a bunch rows/columns, saving that as an image further reduced the overall quality. Setting interpolation to none and dpi at 300, with a little fix to the lat-longs (extend the bbox) helped me overlay the imagery perfectly.

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.