0
1

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.

Python 画像の縦横幅をチェックする簡易ツール

Last updated at Posted at 2019-07-09

前書き

以下のような画像群がありました。

スクリーンショット 2019-07-09 20.07.52.png

ここから画像サイズに誤りあるもの(赤い画像)を検出しないといけない。

普通にGUIで見たらこんな感じです。
スクリーンショット 2019-07-09 20.51.19.png

赤い画像がサイズ違いの画像。
実際の画像は全て違うデザインなので、これだけでは画像の判別がつかないです。

こういうのを見れるGUIツールはいくらでもありそうですが、
画像の数が多いので、GUIツールが重かったり見にくかったり。

何がしたいのか

なるだけラクにチェックしたいです。

何をやるのか

簡単な処理で対処してしまおう、と思いました。

やったこと

Python で対処しました。
Pythonの画像処理ライブラリPillowを使ってます。
pip などで簡単にインストールできます。
https://pillow.readthedocs.io/en/stable/

import glob
from PIL import Image

# 処理
def main(x, y, type_str, path, file_type):
    files = glob.glob(path + file_type)
    ng_cnt = 0
    ok_cnt = 0

    for file in files:
        sample = Image.open(file)
        sizestr = str(sample.size)
        chkstr_yoko = '(' + str(x) + ', ' + str(y) + ')'
        chkstr_tate = '(' + str(y) + ', ' + str(x) + ')'

        if sizestr != chkstr_yoko and sizestr != chkstr_tate:
            print('NG:' + file)
            ng_cnt = ng_cnt + 1
        else:
            ok_cnt = ok_cnt + 1
        #    print('OK:' + file)
        # print(chkstr)

    print()
    print(type_str)
    print('Tate: W = ' + str(y) + ', H = ' + str(x) +
          ' / Yoko: W = ' + str(x) + ', H = ' + str(y))
    print('OK:' + str(ok_cnt))
    print('NG:' + str(ng_cnt))

# チェックする画像サイズを定義
x = 150
y = 100
path = '/Users/sawai/images/'
file_type = '/*.png'
type_str = '# Test_Image'

# 処理呼び出し
main(x, y, type_str, path, file_type)

画像サイズやパスはロジック内に書きましたが、
別ファイル定義やコマンドライン引数にしても良いと思います。

実行結果

こんな感じでサイズが違う画像をピックアップできました。
処理速度も苦にならず、数秒で完了します。
スクリーンショット 2019-07-09 20.52.49.png

まとめ

自身は業務上PHPを書く機会が多いのですが、
ちょっとしたタイミングで、ちょっとしたことを、ちょっと理由作って、
興味ある言語で書いてみる機会を作るのも大事かも。
(じゃないと実務で使う機会ってあまりないんですよねぇ・・・)

もちろん、
他タスクのリソースを食いつぶすまで熱入れしない程度にですけども。
まぁロジック書くことは楽しいことだと思いますから(笑)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?