LoginSignup
12
6

More than 3 years have passed since last update.

Pythonのmatplotlibで一刻も早く画像を並べて表示したいという人へ

Posted at

ソースコード

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

image.png

shownumber = 10

image.png

なぜこの記事を書いたか

  • 画像表示をする度に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の数だけ、imshowaxis('off')で画像表示
  • imgsが尽きるまでループを回し続ける

 コードの構成上、最終的には確実に範囲外参照エラーを起こすので注意。一応脱出処理をコメントで書いてます。

12
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6