0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

opencv-pythonで簡単に次々と画像を表示する方法

Last updated at Posted at 2019-03-01

はじめに

あるディレクトリ内の画像をボタン1つで次々に表示できるコードが欲しくなった.
画像処理プログラムで、正しく動いているか確認したかったためだ.

環境

OS python3 opencv-python
OS X 10.14.3 3.6.5 4.0.0.21

実装

for i in no_list: #no_listは画像No.のリスト
    path = 'img_no{}.png'.format(i)
    #画像があるかの確認 存在しない場合は飛ばす
    if os.path.exists(path): 
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        cv2.imshow('img',resized_img)
        cv2.waitKey()
        cv2.destroyAllWindows()

これは一例で、以下の条件の場合のコードになる.

  • 画像はカレントディレクトリにある
  • 画像の名前はimg_no##.png (##は整数)

if os.path.exists(path):のおかげで、数字の連続が途中で切れてても平気.

for i in no_list:の条件を変えればファイル名に合わせることができる.最悪、dictにファイル名を全部格納すれば何とかなる.

補足: 画像を表示する時のサイズと位置の調節もしたかったので以下のコードを追加した.

    #画像の表示サイズを変更 imshow()の前に記述
    h,w,n = img.shape[0], img.shape[1], 2
    resized_img = cv2.resize(img,(int(w/n), int(h/n)))
    #画像を表示する位置を変更 imshow()の後に記述
    cv2.moveWindow('img', 100, 200)
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?