LoginSignup
2
2

More than 5 years have passed since last update.

バラバラになった画像を結合するコードを書いてみた

Posted at

はじめに

バラバラになった画像を一つの画像にするコードを書いてみました。

今回は分割画像のサイズが全て同じ状況を考えています。
分割画像には元画像の左上から横に向かって0001.png 0002.png ...のように連番で名前がついていると仮定します。CTFではmd5でハッシュ化されていることが多いです。

コード

from PIL import Image

def concat_horizontal(im, column):
    '''
    画像配列を受け取り,横方向に結合し,結合画像を返す
    '''
    dst = Image.new('RGB', (im[0].width * column, im[0].height))
    for x in range(column):
        dst.paste(im[x], (x * im[0].width, 0))
    return dst

def concat_vertical(im, row):
    '''
    画像配列を受け取り,縦方向に結合し,結合画像を返す
    '''
    dst = Image.new('RGB', (im[0].width, im[0].height * row))
    for y in range(row):
        dst.paste(im[y], (0, y * im[0].height))
    return dst

def concat_tile(im, row, column):
    '''
    2次元の画像配列を受け取り,結合結果を返す
    '''
    dst_h = []

    # 縦方向に結合する場合はhorizontalとverticalを入れ替え
    for i in range(row):
        dst_h.append(concat_horizontal(im[i], column))
    return concat_vertical(dst_h, row)

W,H = 45,45 #分割数に応じて変更

img = [[0]*W for _ in range(H)]
for i in range(W):
    for j in range(H):
        filename = 'picture/pieces/'+'{:04}'.format(W*i+j+1)+'.png'

        # 画像ファイルパスから読み込み
        im1 = Image.open(filename)
        img[i][j] = im1

concat_tile(img, W, H).save('concat_tile.png')
2
2
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
2
2