I am doing some analysis on images (original image format is geotiff - .tif and did some calculations on the images and able to output the calculated pixels into csv without issue. However due to matplotlib limitations of using only inches for figure width and height, i am not able to output the new calculated image into a plot. Original map size is about 7.7k pixels by 7.7k pixels and the output image is of 3.3k by 3.3k without color bar. Below is the code i used to generate the plots
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
figure_width_inches = 40
figure_height_inches = 20
img_min = np.nanmin(img)
img_max = np.nanmax(img)
mid = 0
img_fig = plt.figure(figsize=(figure_width_inches, figure_height_inches))
img_ax = img_fig.add_subplot(add_subplot_RPC)
cmap = plt.cm.RdYlGn
img_cax = plt.imshow(img, cmap=cmap, clim=(img_min, img_max))
plt.axis(axis_mode)
img_fig.savefig(img_filename.replace('.jpg', '_notitlenolegend.jpg'), dpi=figure_dpi,
bbox_inches=figure_bbox_inches, pad_inches=plot_pad_inches)
ax.set_title(img_title, fontsize=axis_title_fontsize, fontweight=axis_title_fontweight)
cbar = img_fig.colorbar(cax, orientation=figure_colourbar_orientation, shrink=figure_colourbar_shrink)
img_fig.savefig(img_filename, dpi=figure_dpi, bbox_inches=figure_bbox_inches, pad_inches=plot_pad_inches)
I need the image output to be of similar size as original image (i.e. 7.7k by 7.7k pixels) for post plot processing. My challenge is that my source file is of geotiff and plt.imread is unable to open the file. I am thinking of converting the tif file to jpg to get plt.imread to open the file but i could not convert it.
source = '~/some_map.tif'
import PIL
import PIL.Image, PIL.ImageFile
img = PIL.Image.open(source)
destination = source.replace('.tif', '_destination.tif')
img.save(destination, "JPEG", quality=10, optimize=True, progressive=True)
...
IOError: cannot write mode I as JPEG
i might need to convert the color space of the single band geotiff file for pillow to save the file as jpg. But it seems like a tedious approach to the problem.
- Is there a more pythonic way to resolve the image output size of matplotlib
Edit:
figure_dpi = 100
figure_output_dpi = 1000
img_fig = plt.figure(figsize=(width/float(figure_output_dpi), \
height/float(figure_output_dpi)), dpi=figure_dpi)
ax = plt.Axes(img_fig, [0., 0., 1., 1.])
ax.set_axis_off()
img_fig.add_axes(ax)
i managed to generate the results i want with this i.e. figure is pixel by pixel identical to the image source.