ソースコード
import matplotlib.pyplot as plt
import cv2
import os
root = "./data" #画像があるフォルダ。適宜変えてください
lsdir = os.listdir(root)
imgs = []
for l in lsdir:
target = os.path.join(root,l)
img = cv2.imread(target)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #pyplotで表示するために色変換
imgs.append(img)
shownumber = 10 #画像を並べる数
showaxis = 1
while(showaxis*showaxis < shownumber):
showaxis += 1
cnt = 0
while(1):
#limit = 30
#if cnt >= limit:
# break
fig,axs = plt.subplots(showaxis,showaxis)
ar = axs.ravel()
for i in range(showaxis*showaxis):
ar[i].axis('off')
if i < shownumber:
ar[i].imshow(imgs[cnt])
cnt += 1
plt.show()
表示結果
shownumber = 9
shownumber = 10
なぜこの記事を書いたか
- 画像表示をする度に
matplotlibについてぐぐっている気がするので、自分の中の定石を定めたかった - rowとcolumnを指定するのが微妙にめんどくさいため、表示数を指定するだけで動作するコードにしたかった
- そのようなソースコードがすぐにヒットするページを作りたかった
コードの説明
- フォルダを指定して
cv2.imreadで読み込み、imgsという配列にする。 - OpenCVはBGR形式で読み込むため、
cv2.cvtColorでRGB形式に変換 - 表示数
shownumberを指定したら、それを満たす最小の二乗数を求めて、1辺をshowaxisとする。
while(showaxis*showaxis < shownumber):
showaxis += 1
-
plt.subplotsで行と列がそれぞれshowaxisの数だけあるグラフを用意 -
axsは縦位置と横位置を指定するのがめんどくさいため、axs.ravel()で一連の配列にする - 1ループごとに
shownumberの数だけ、imshowとaxis('off')で画像表示 -
imgsが尽きるまでループを回し続ける
コードの構成上、最終的には確実に範囲外参照エラーを起こすので注意。一応脱出処理をコメントで書いてます。

