LoginSignup
0
0

More than 1 year has passed since last update.

【画像整理】グレースケールのような彩度の低い画像を一括で整理するPythonスクリプト

Posted at

動機

画像生成してたら画像が死ぬほど大量に出来てしまったので、
せめて真っ黒画像や白黒画像のようなものは一括で削除したいと思い、自動で分別してくれるコードを作りました。

使い方

以下のコードをコピーして、その新規ファイルを「move_low_saturation_images.py」として保存。
例えばパスが
\○○○○\stable-diffusion-webui\outputs\txt2img-images\なんとか\ほにゃらら.png
の画像ファイルに対してフォルダ分けしたい場合、
\○○○○\stable-diffusion-webui\outputs\txt2img-images\
の直下に move_low_saturation_images.py を配置して、ダブルクリックして実行してください。
ライブラリが無いと言われた場合は、別途

pip install opencv-python numpy

等としてパッケージをインストールしてください。
WindowsだったらコマンドプロンプトかPowerShellで

python -m pip install opencv-python numpy

と入れればインストールできると思います。

こうすることで、彩度の低い画像が
\○○○○\stable-diffusion-webui\outputs\txt2img-images\なんとか\low_saturation_images
のフォルダに自動で整理されます。

move_low_saturation_images.py
import cv2
import numpy as np
import os
import shutil

# 画像の彩度が低いかどうかを判定する関数
def is_low_saturation(image: np.ndarray, threshold: int = 20) -> bool:
    # 画像をBGRからHSVに変換
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    # 画像の彩度の平均値を計算
    mean_saturation = np.mean(hsv[:, :, 1])
    # 平均彩度が閾値未満の場合、Trueを返す
    return mean_saturation < threshold

# サブフォルダを作成する関数
def create_subfolder(folder_path: str, subfolder_name: str) -> str:
    # サブフォルダのパスを作成
    subfolder_path = os.path.join(folder_path, subfolder_name)
    # サブフォルダが存在しない場合、作成
    if not os.path.exists(subfolder_path):
        os.makedirs(subfolder_path)
    return subfolder_path

# カレントディレクトリおよび子ディレクトリ内の彩度が低い画像をサブフォルダに移動する関数
def move_low_saturation_images(current_dir: str, subfolder_name: str, threshold: int = 20) -> None:
    # カレントディレクトリとそのすべての子ディレクトリを再帰的に探索
    for root, dirs, files in os.walk(current_dir):
        # フォルダ名が"low_saturation_images"でない場合のみ処理を実行
        if subfolder_name not in root:
            print(root)
            for file_name in files:
                # PNGファイルのみ処理
                if file_name.endswith(".png"):
                    # 画像のファイルパスを取得
                    file_path = os.path.join(root, file_name)
                    # 画像を読み込み
                    image = cv2.imread(file_path)
                    # 画像の彩度が低いか判定
                    if is_low_saturation(image, threshold):
                        # サブフォルダを作成し、そのパスを取得
                        dest_folder = create_subfolder(root, subfolder_name)
                        # 彩度が低い画像をサブフォルダに移動
                        shutil.move(file_path, os.path.join(dest_folder, file_name))

# カレントディレクトリを取得
current_dir = os.getcwd()
# サブフォルダ名を設定
subfolder_name = "low_saturation_images"
# 閾値を設定
threshold = 20

# 彩度が低い画像をサブフォルダに移動する関数を実行
move_low_saturation_images(current_dir, subfolder_name, threshold)

調整方法・注意

下から4行目の "threshold = 20"の部分の数字を 10~30程度で変動させればフォルダ分け範囲を設定できます。

ただ、髪の毛・服・背景などが白黒などの単調な色だった場合や、日陰の場面の場合には、彩度低めと判定されてしまうことがあります。なので、一つ一つ目視で画像チェックしてから削除するのをオススメします。

余談

このコードは2023年4月時点のGhatGPTのGPT-4モデルに書いてもらいました。やっぱChatGPTすげえや。

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