Skip to content

Instantly share code, notes, and snippets.

@seignovert
Last active August 17, 2022 18:57
Show Gist options
  • Save seignovert/848faf586a52f0afafec3606df8384bf to your computer and use it in GitHub Desktop.
Save seignovert/848faf586a52f0afafec3606df8384bf to your computer and use it in GitHub Desktop.
[Python] Wrap image on a sphere

Wrap image on a sphere

Install

conda install basemap matplotlib

Run

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

img = 'Titan_VIMS_ISS.jpg'

map = Basemap(projection='ortho', lat_0=15, lon_0=0)
map.warpimage(img)

plt.savefig('Titan_ortho.jpg', bbox_inches='tight')
plt.show()

or

python wrap_sphere.py

Titan ortho image

Titan globe centered on (0º, 15ºN) with a geographic grid and a red dot a (lat, lon) = (30º, 45º)

Source

Known issue

Install of Basemap from conda does not set the $PROJ_LIB environment variable resulting in the following error:

>>> from mpl_toolkits.basemap import Basemap
KeyError: 'PROJ_LIB'

The issue is known (and should be fixed by now…) but here is a workaround if needed:

set "PROJ_LIB=%CONDA_PREFIX%\Library\share"  # Windows

export PROJ_LIB=$CONDA_PREFIX/share/proj  # Linux and OS X
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# Background image filename
img = 'Titan_VIMS_ISS.jpg'
# Defined the geographic projection
m = Basemap(projection='ortho', lat_0=15, lon_0=0)
# Wrap background image on the sphere
m.warpimage(img)
# Define longitudes and latitudes grid
lons = np.linspace(-180, 180, 13)
lats = np.linspace(-90, 90, 13)
# Draw meridians and parallels
m.drawmeridians(lons, linewidth=.25)
m.drawparallels(lats, linewidth=.25)
m.drawmeridians([0], color='r', dashes=[1, 0])
# Add a red point on the sphere
lon, lat = (45, 30)
plt.plot(*m(lon, lat), 'ro')
# Save the figure in a JPG file
plt.savefig('Titan_ortho.jpg', bbox_inches='tight')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment