0

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.axis('off')
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))

fig.canvas.draw()


plt.savefig(r'C:\Users\MRG16-10417\Desktop\New\testspecies.tif',transparent='true',bbox_inches='tight')

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
nrows=252
ncols=386

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
dst_ds.SetGeoTransform(geotransform)

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

# Set projection
dst_ds.SetProjection(dest_wkt)

# 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?

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

0

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.