Skip to content

Instantly share code, notes, and snippets.

@letmaik
Created September 12, 2014 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save letmaik/ec1d11172d4edf8221af to your computer and use it in GitHub Desktop.
Save letmaik/ec1d11172d4edf8221af to your computer and use it in GitHub Desktop.
Draw things naturally onto an image using matplotlib
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
def loadFigImage(path):
im = mpimg.imread(path)
h,w = im.shape[0], im.shape[1]
dpi = 80
fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
ax = plt.Axes(fig, [0, 0, 1, 1])
ax.set_xlim(0, w)
ax.set_ylim(0, h)
ax.invert_yaxis()
ax.set_axis_off()
fig.add_axes(ax)
fig.figimage(im)
return fig, ax
def saveFigImage(path, fig):
fig.savefig(path, dpi=80)
plt.close(fig)
if __name__ == '__main__':
import numpy as np
fig, ax = loadFigImage('image.png')
# plot using image coordinates, (0,0) = top left
x = range(0, 2000, 50)
y = np.random.randint(0,1000, len(x))
ax.plot(x,y, c='red')
saveFigImage('image2.png', fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment