Created
September 12, 2014 14:42
-
-
Save letmaik/ec1d11172d4edf8221af to your computer and use it in GitHub Desktop.
Draw things naturally onto an image using matplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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