画像処理を行なっていると、処理前の画像と処理後の画像を一目で比較したいなと言う場面に何度も遭遇したので、コピペで使えるように2つの画像を1つにまとめて出力する関数をおいておきます。
目次
適当なグラフを作成
手始めに、適当なグラフを作成してみます。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim(840,1000)
x = [1,4]
y = np.array([850,985])
plt.xlabel('year(s)')
plt.ylabel('TOEIC Score')
plt.bar(x, y)
fig.savefig("img.jpg")
出来上がった画像がこちらです。
![](https://japbros-poco.main.jp/wp-content/uploads/2022/03/s-1.jpg)
関数の作成
上の画像を2枚並べてみたいと思います。
import cv2
import numpy as np
import matplotlib.pyplot as plt
def set_two_imgs(img_1,img_2,output_name):
fig = plt.figure()
img_1 = cv2.cvtColor(cv2.imread(img_1), cv2.COLOR_BGR2RGB)
img_2 = cv2.cvtColor(cv2.imread(img_2), cv2.COLOR_BGR2RGB)
plt.subplot(121),plt.imshow(img_1)
plt.title('img_1'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img_2)
plt.title('img_2'), plt.xticks([]), plt.yticks([])
fig.savefig(str(output_name),dpi=500)
if __name__ == '__main__':
set_two_imgs('img.jpg','img.jpg','img_2.jpg')
無事2個の画像を並べることができました。
![](https://japbros-poco.main.jp/wp-content/uploads/2022/03/p-1024x768.jpg)