Plot on an image using Python Matplotlib.pyplot


The result is:

Plot on an image using Python Matplotlib.pyplot

This page shows how to plot data on an image.
plt.plot and plt.scatter is used in this page as an example.
You can plot by mapping function that convert the point of the plotting data to that of the image.

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
In [2]:
img = Image.open("./lena_color.gif")
The original image is:
In [3]:
img
Out[3]:
and the type and the shape of the image is follows:
In [4]:
type(img)
Out[4]:
PIL.GifImagePlugin.GifImageFile
In [5]:
img.size # returns (x, y) of the image
Out[5]:
(512, 512)
if plt.imshow() is used as drawing function:
In [6]:
plt.imshow(img)
Out[6]:
<matplotlib.image.AxesImage at 0x291f726c198>
you can hide the axis by adding six lines:
In [7]:
fig, ax = plt.subplots()
ax.imshow(img)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.show()
You can also rewrite the ticklabels by using the mapping function. For example:
In [8]:
xy2imgxy = lambda x,y: (img.size[0] * x / np.max(ticklx),\
                        img.size[1] * (np.max(tickly) - y) / np.max(tickly))
In [9]:
ticklx = np.linspace(0,100,6)
tickly = np.linspace(0,100,6)
tickpx,tickpy = xy2imgxy(ticklx,tickly)
In [10]:
fig,ax = plt.subplots()
ax.imshow(img)

# Rewrite x,y ticks
ax.set_xticks(tickpx)
ax.set_yticks(tickpy)
ax.set_xticklabels(ticklx.astype('int'))
ax.set_yticklabels(tickly.astype('int'))
plt.show()
You can draw plot or scatter plot on the image by converting the point of the data using mapping function. For example:
In [11]:
fig,ax = plt.subplots()
ax.imshow(img)

# Rewrite x,y ticks
ax.set_xticks(tickpx)
ax.set_yticks(tickpy)
ax.set_xticklabels(ticklx.astype('int'))
ax.set_yticklabels(tickly.astype('int'))

# Add scatter point on the image.
px,py = 20,20
imgx,imgy = xy2imgxy(px,py)
ax.scatter(imgx,imgy,s=100,lw=5,facecolor="none",edgecolor="yellow")

# Add plot on the image.
px = np.linspace(0,100,500)
py = 10*np.abs(np.sin(2*np.pi*0.02*px))
imgx,imgy = xy2imgxy(px,py)
ax.plot(imgx,imgy,color="yellow",lw=3)

# Adjust the axis.
ax.set_xlim(0,tickpx.max())
ax.set_ylim(tickpy.max(),0)

# Save figure.
plt.savefig("lena_color_mod.png",bbox_inches="tight",pad_inches=0.02,dpi=250)
plt.show()