3DCG屋さんの活動記録

PROFILE ★★こんな人です

3DCGを活用した映像や没入体験コンテンツの制作をしています。テクノロジーの社会実装に興味があり。テクニカルディレクター。面白いこと新しいことにワクワクする気持ちに『素直』でいつづける。

3DCG屋さんの活動記録

2022年10月20日木曜日

Python自動化:フォルダ内の複数枚の透過PNGを1枚に結合 【Dir2Flipbook】


Dir2Flipbook


今回やったこと

フォルダ内の複数枚の透過PNGを1枚に結合するのを自動化。




WEB上はたくさんの「画像結合ソフト」がある!

ただ、試した見たもののやりたいことと若干ずれてたので

欲しい機能だけに絞ったPython作った。


<機能>

・フォルダ内の画像を1枚に結合

・透明度(アルファ)保持

・解像度に制限なし

・ただし、PNG専用


<使い方>

①Pythonをダウンロードして、3箇所変更する

フォルダパス、横枚数、縦枚数


②実行すると、フォルダ内の「combinedフォルダ」に画像が作成される

以上。

使えない場合は、
Pillowをインストールしてみてください。


Windowsなら

     pip install Pillow


<コード>

# coding: UTF-8
# Dir2Flipbook
#内容:フォルダ内の複数枚の画像を1枚に結合
#条件:png専用。透明度あり(RGBA)。フォルダ内の画像で一番大きなサイズに合わせてタイリング。
#事前準備:Pillowをインストール (windowsなら pip install Pillow)
#
#2022.10.19 v0.0.1
#2024.12.6 v0.0.2
#
#使い方:
#
#連番だけを入れたフォルダを作成する(連番ファイル名の1枚目の末尾は_0000.png or _0001.png推奨)
#本コードのCustomSettingsを記入。連番が入ったフォルダのパスを指定、縦横の数を指定する。
#windowsのコマンドプロンプトで本コードを実行する。
#フォルダ内にcombineフォルダが作成され、その中に結合されたPNGが保存されているので他のフォルダにコピーして下さい。
#
import os
import re
import glob
from PIL import Image
##--------------------------
# Custom Settings
##--------------------------
sourceDir = r"C:\sourceDir" #連番を入れたフォルダパス。
col_num = 16 #横の枚数
row_num = 8 #縦の枚数
#--------------------------
def concat_images(path, n, m):
"""Concatenate n x m images from path into one image."""
# Get a list of all the image files
files = glob.glob(os.path.join(path, '*.png'))
# Load all the images
imgs = [Image.open(f) for f in files]
img_count = len(imgs)
# Create a list of tuples of the form (width, height)
sizes = [(i.width, i.height) for i in imgs]
# Find the max width and height
max_width, max_height = max(sizes, key=lambda s: sum(s))
# Create a new image that's max_width x max_height
new_img = Image.new('RGBA', (n*max_width, m*max_height))
# Paste all the images into the new image
for i in range(m):
for j in range(n):
count = i*n + j
if count < img_count:
img = imgs[i*n + j]
else:
img = Image.new('RGBA', (max_width, max_height), (0,0,0,0))
new_img.paste(img, (j*max_width, i*max_height))
# Save the new imaged
savePath = path+r'\combined'
if not os.path.exists(savePath):
# ディレクトリが存在しない場合、ディレクトリを作成する
os.makedirs(savePath)
new_img.save(os.path.join(savePath,'combine_'+str(n)+'x'+str(m)+'.png'))
#new_img.save(os.path.join(path+"/combine", 'concat.png'))
concat_images(sourceDir, col_num, row_num)
view raw Dir2Flipbook.py hosted with ❤ by GitHub




0 コメント:

コメントを投稿