
Hi, I’m Higashi.
Here’s how to overlay a Matplotlib plot on an image while making the plot’s white background transparent.

The process has four steps:
1. Prepare the base image.
2. Generate the plot image.
3. Set the plot’s size and position on the base image.
4. Run the compositing program.
Let’s get started!
Choose a base image
I’ll use the image below.
This photo shows Yokohama, Japan.

A low-resolution base image can make the overlay look coarse.
Use a high-resolution source if you have one.
Generate the plot image
First, we need a plot to overlay.
The code below generates one with Matplotlib.
import math
import numpy as np
import matplotlib.pyplot as plt
grf_name='grf.jpg'
#make sin data
x=np.linspace(0,2*math.pi,100)
y1=np.sin(x)
#make graph and save image
plt.plot(x,y1,color='red', linestyle='solid', linewidth = 2.0, label='sin(x)')
plt.legend(loc='upper right', fontsize=14)
plt.xlabel('x',color='black',fontsize=14)
plt.ylabel('y',color='black',fontsize=14)
plt.savefig(grf_name, dpi=300)
The plot image is saved in the working directory.

The next step treats white pixels in the plot as transparent before compositing it onto the base image.
Set the plot position and size
The compositing program uses these four values:
mrgh: horizontal offset used to position the plot.
mrgw: vertical offset used to position the plot.
figh: height of the overlay in pixels.
figw: width of the overlay in pixels.
Make sure the resized overlay fits inside the base image at the chosen position.
Sample code for compositing the plot
Here’s the program that combines the two images.
#import library
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
#designate file name
pic_name='sample.jpg'
grf_name='grf.jpg'
fin_name='final.jpg'
#make data for graph image
x=np.linspace(0,2*math.pi,100)
y1=np.sin(x)
#make graph image
plt.plot(x,y1,color='red', linestyle='solid', linewidth = 2.0, label='sin(x)')
plt.legend(loc='upper right', fontsize=14)
plt.xlabel('x',color='black',fontsize=14)
plt.ylabel('y',color='black',fontsize=14)
plt.savefig(grf_name, dpi=300)
#position and size desgnation
mrgh=50
mrgw=500
figh=1000
figw=1500
#process of composite base image and graph image
img=cv2.imread(pic_name,cv2.IMREAD_COLOR)
grf=cv2.imread(grf_name,cv2.IMREAD_COLOR)
grf=cv2.resize(grf,(figw,figh))
#this process conduct the graph transparent
grf[:,:,:]=np.where(grf[:,:,:]>250,img[mrgh:mrgh+figh,mrgw:mrgw+figw,:],grf[:,:,:])
fin=img
fin[mrgh:mrgh+figh,mrgw:mrgw+figw,:]=grf[:,:,:]
#save composite image
cv2.imwrite(fin_name,fin)
The comments walk through the main steps.
Check the result
Let’s run the sample and look at the output.
Here’s the working directory before running the program.

Here it is after the program runs.

The file final.jpg contains the composite shown at the beginning of this article.

The same approach also works for a plot with dotted lines.


That makes it handy for more than one kind of plot.
Thanks for reading!


コメント