[Python and OpenCV] Overlay a Transparent Matplotlib Plot on an Image

Python
higashi
higashi

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!

 

Sponsored Links

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.

 

Sponsored Links

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.

 

Sponsored Links

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.

 

Sponsored Links

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.

 

Sponsored Links

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.

複雑な画像を合成した結果

higashi
higashi

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

 

Thanks for reading!

 

コメント