LoginSignup
4
1

More than 5 years have passed since last update.

【Python】ファイル内画像を一括して指定ピクセルサイズで分割・保存

Last updated at Posted at 2019-01-07

超初心者です。学生です。初投稿です。お手柔らかにお願いします。
なにかありましたら優しく教えてください💛

機械学習をやる際のテストデータ、教師データを特定ピクセルサイズのパッチに加工しようと思いました。しかし、ググってみても自分の欲しいドンピシャなコードが見つからない…(もしかすると僕のググり力不足かもしれません)
なので、メモ代わりに投稿します。

参考文献
https://qiita.com/kino15/items/ece822ec20ad5e80e382
上記の方のコードをベースに、分割する数を一々割り切れるように調節するのが面倒だったので端を切るようにしたのと、画像ファイル内にある画像に対して一括処理するようにしただけです。

splitimage.py
import os
import glob
import cv2
import numpy as np
import sys
import matplotlib.pyplot as plt
from PIL import Image, ImageChops

# ディレクトリ設定
inputdir = "ここに入力"
outputdir = "ここに入力" # ディレクトリが存在しなくても勝手に作る

# 分割したいパッチのサイズ指定
height = 200
width = 200

# ディレクトリが存在しない場合は作成する
if not os.path.exists(outputdir):
    os.mkdir(outputdir)

# ファイル検索 ※今回はjpegにしてますが、適宜変えてください
pngsearchpath = os.path.join(inputdir, '*.jpg')
pngfiles = glob.glob(pngsearchpath)

# 各ファイルの処理
for file in pngfiles:
    # 画像ファイルを開く
    print(file)
    im = Image.open(file)
    name, ext = os.path.splitext(os.path.basename(file))
    im_height ,im_width =im.size

    a=im_height//height
    b=im_width//width

    def ImgSplit(im):
        # 縦の分割枚数
        for h1 in range(b):
            # 横の分割枚数
            for w1 in range(a):
                w2 = w1 * height
                h2 = h1 * width
                print(w2, h2, width + w2, height + h2)
                yield im.crop((w2, h2, width + w2, height + h2))

            for number, ig in enumerate(ImgSplit(im), 1):
            # 保存先フォルダの指定
                ig.save(outputdir+"/"+name+"-%01d.jpg" %number, "JPEG")


if __name__ == '__main__':
    main()

なんか色々突っ込みどころ満載かと思いますが、適宜書いていただけると嬉しいです。

4
1
3

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