LoginSignup
0
0

【データセット作成用】一括正方形リサイズツール

Last updated at Posted at 2024-04-28

概要

ディレクトリ内の画像を一括で正方形にクロップして、任意の解像度にリサイズできるツールを作りました。
YOLOなどのデータセット作成の歳に個人的に使っていたものですが、同じ機能を必要としている方がいるかと思い、共有させていただきます。

既出だったらごめんなさい。

データセット作成の前処理などにお使いください

Requirements

実行にあたって、以下のコマンドを入力し、必要なモジュールをインストールしてください。

install.sh
pip install Pillow

コード

コードはGithubにも同様のものをアップしています。

crop.py
from PIL import Image
import glob
import os
from concurrent import futures

FileTypes = ['/*.jpg','/*.png','/*.JPG','/*.PNG']

def crop_center(pil_img, crop_width, crop_height):
    img_width, img_height = pil_img.size
    return pil_img.crop(((img_width - crop_width) // 2,
                         (img_height - crop_height) // 2,
                         (img_width + crop_width) // 2,
                         (img_height + crop_height) // 2))

#--------------------------------------------------

# 並列化用関数
def task_crop(target_file):
    img = Image.open(target_file)
    filename = os.path.basename(target_file)

    # ----正方形にする---
    img = crop_center(img,min(img.size),min(img.size))
    img = img.resize((resized_size,resized_size))

    print('Processing: ',target_file)

    # ファイルを保存
    img.save(f'{output_dir}/{filename}')


input_dir = input('Input data path:').replace('\\','/').replace('"','').replace("'",'')
output_dir = input_dir+'/resized'
resized_size = int(input('Input resized size:'))

# 出力先フォルダの作成
os.makedirs(output_dir,exist_ok=True)


# フォルダの中身を確認
for FileType in FileTypes:
    files = glob.glob(input_dir+FileType)
    # クロップ作業
    with futures.ThreadPoolExecutor() as executor:
        for i,file in enumerate(files):
            executor.submit(task_crop,file)

使い方

コードを実行すると、Input data pathresized_sizeを聞かれます。
それぞれ、一括処理したい画像が入ったディレクトリと、リサイズ後のサイズを入力してください。

参考

コードの作成にあたっては、以下のサイトのコードを参考にさせていただきました。

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