LoginSignup
11
11

More than 5 years have passed since last update.

[Python3.6]画像を任意の枚数に分割する

Last updated at Posted at 2018-06-27

一枚の画像を任意の枚数に分割するコードです。
縦、横の分割枚数、どんなサイズで分割させるかを指定します。

sample.py
from PIL import Image
import os
import sys

from datetime import datetime

def ImgSplit(im):
    # 読み込んだ画像を200*200のサイズで54枚に分割する
    height = 200
    width = 200

    buff = []
    # 縦の分割枚数
    for h1 in range(6):
        # 横の分割枚数
        for w1 in range(9):
            w2 = w1 * height
            h2 = h1 * width
            print(w2, h2, width + w2, height + h2)
            c = im.crop((w2, h2, width + w2, height + h2))
            buff.append(c)
    return buff



if __name__ == '__main__':
    # 画像の読み込み
    im = Image.open('./test/IMG_0025.JPG')
    for ig in ImgSplit(im):
        # 保存先フォルダの指定
        ig.save("./test2/test" + datetime.now().strftime("%Y%m%d_%H%M%S%f_") +".jpg", "JPEG")

追記

コメントでジェネレータを利用して、使用メモリ節約するコードを教えていただきました。

今回ジェネレータというのを初めて聞いたのですが、「return文をyieldに置き換えたもの」のようです。
(参考:Pythonのジェネレーターってなんのためにあるのかをなるべく分かりやすく説明しようと試みた

from PIL import Image
import os
import sys

from datetime import datetime

def ImgSplit(im):
    # 読み込んだ画像を200*200のサイズで54枚に分割する
    height = 200
    width = 200

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

if __name__ == '__main__':
    # 画像の読み込み
    im = Image.open('./test/IMG_0025.JPG')
    for ig in ImgSplit(im):
        # 保存先フォルダの指定
        ig.save("./test2/test" + datetime.now().strftime("%Y%m%d_%H%M%S%f_") +".jpg", "JPEG")
11
11
5

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
11
11