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?

AI時代の画像ファイル検索

0
Posted at

導入

AI を使って画像を生成などしていると、
「ファイル名は違うけど、これどの画像ファイルだっけなー?」
なんて思うことないですか?
ボクはたまにあります。

膨大なファイル

ファイルの数は膨大で目検では時間がかかりすぎます。途方も無いです。

そうだツール作ろう

Windows には画像ファイルの中身を比較してくれる機能はありません。
ならばツールを作ればいいじゃない!

make_image_hash.py

import os
from pathlib import Path
from PIL import Image
import imagehash

root_dir = Path(r"D:/IMAGES")

with open("image_hash.csv", "w", encoding="utf-8") as f:
    for file in Path(root_dir).rglob("*.png"):
        try:
            print(file)
            h = imagehash.phash(Image.open(file))
            print(f"{file},{h}", file=f)
        except Exception as e:
            print(f"ERROR {f}: {e}")

検索したい画像ファイル群のハッシュ値を作るプログラムです。おそらくファイル数が膨大ですので、作成には少し時間がかかりますが、目で検索する手間よりは数万倍マシです。

なお、インポートが失敗する場合は適宜 pip でインストールしてください。

$ python make_image_hash.py

ファイルが出来るまで、お茶でも頂きながら優雅にしばらく待ちましょう。

find_image.py

import sys
from PIL import Image
import imagehash

args = sys.argv
if len(args) != 2:
    print("引数を指定してください。")
    sys.exit(0)

img = Image.open(args[1])
h = imagehash.phash(img)

cnt = 0
try:
    with open('./image_hash.csv', 'r', encoding='utf-8') as f:
        for line in f:
            items = line.split(',')
            if imagehash.hex_to_hash(items[1]) == h:
                cnt += 1
                print(f"file={items[0]} hash={items[1]}")
except FileNotFoundError:
    print("ハッシュ値データが見つかりません。")

print(f"{cnt} ファイル見つかりました。")

同じハッシュ値の画像ファイルを検索するプログラムです。
もし同一ハッシュ値の画像ファイルが複数あったら全部表示します。
(たぶん1ファイルしか見つかりません)

$ python find_image.py foo.png

として使います。

おわりに

AI 画像生成はしていなくても、ネットではすぐ同じ画像を見つける事は出来ても、
「どこのフォルダに置いっけなー。忘れちゃったなー」
「うわー。なかなか見つからないよー」
ってことあるじゃないですか?気になって眠れなくなってしまいます。

男ならだれでもそんな時があります(意味深)

画像をダウンロードして用意し、このツールを使えば一発でフォルダを特定できます。
時間節約できた分睡眠時間が増えるよ。やったね!

最後に一言

また1つ、役に立つツールを作ってしまった・・・

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?