Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flamingbear/8f3e081c31fbb428fe60afe71729d5ec to your computer and use it in GitHub Desktop.
Save flamingbear/8f3e081c31fbb428fe60afe71729d5ec to your computer and use it in GitHub Desktop.
Sample binary grid and code to demonstrate imshow vs scipy problem.
# Read a grid in the native projection and display with matplotlib and scipy.
import scipy.misc
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def make_image():
dpi = 100.
fig = plt.figure(figsize=(600/dpi, 900/dpi), dpi=dpi, edgecolor='none')
image_axes = fig.add_axes([0, 0, 1, 1])
landmask = 'resampled-mask.600x900.bin'
grid = np.fromfile(landmask, dtype=np.uint8).reshape((900, 600))
grid[grid == 101] = 0 # reset permanent ice to land
ct_cmap, ct_norm = mpl.colors.from_levels_and_colors(
[0, 50, 256], ['#000000', '#FFFFFF']
)
image_axes.set_axis_off()
image_axes.imshow(grid, origin='upper', interpolation='nearest',
cmap=ct_cmap, norm=ct_norm)
fig.savefig('imshow.png', dpi=dpi, facecolor=fig.get_facecolor(),
edgecolor='none', pad_inches=0.0)
plt.close(fig)
# Now the same grid with scipy imsave but also as an RGBA image.
rgba = np.zeros((900, 600, 4))
rgba[:, :, 0] = grid
rgba[:, :, 1] = grid
rgba[:, :, 2] = grid
rgba[:, :, 3] = 255
scipy.misc.imsave('scipyimsave.png', rgba)
if __name__ == '__main__':
make_image()
#!/bin/bash
set -xe
python imshowwhy.py
convert imshow.png scipyimsave.png diff.gif
# Sample code and data for describing data issue in imshow
## Problem: imshow seems to move some of the data around in it's axes.
When I try to us axes.imshow in matplotlib with a grid of known size and shape,
and then later read the png data, the image's data changes compared to the
input gridded data.
I've included a script `make-gif.sh` that reads a sample 900x600 image and then
writes that to a file using matplotlib's imshow, as well as with scipy's
savefig. The two png images are then fused (with imagemagick's convert) and
you can see flicking where the two different outputs show differences.
Examining the bands in the output PNGS, the data saved with scipy's
savefig are exactly aligned with the input data while there is a shift in three
quadrants of the data saved with imshow.
I would guess I'm missing some flag, but I have been unable to find something
to prevent this undesired shift.
Can someone help me out here?
Python 3.5.2:
```
matplotlib 1.5.3 np111py35_3 conda-forge/channel/main
scipy 0.18.1 np111py35_blas_openblas_201 [blas_openblas] conda-forge/channel/main
```
Thanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment