Skip to content

Instantly share code, notes, and snippets.

@ypsilon-takai
Last active June 28, 2023 10:35
Show Gist options
  • Save ypsilon-takai/b9d5447f57c887d817a9e7f0edc5bd8b to your computer and use it in GitHub Desktop.
Save ypsilon-takai/b9d5447f57c887d817a9e7f0edc5bd8b to your computer and use it in GitHub Desktop.
画像を結合して分割
import cv2
import pathlib
# 画像をnこずつ結合してm個に分割
n = 2
m = 3
infolder = pathlib.Path('INFOLDER')
inimgs = infolder.glob('*')
inimgs = sorted(inimgs, key=lambda x: x.stem)
for topidx in range(0, len(inimgs), n):
# nとばしでインデックスを取る
# nファイル読み込む
image_list = []
for fidx in range(0, n):
img = cv2.imread(str(inimgs[fidx]))
image_list.append(img)
print(image_list)
# 縦に結合の場合g
image_v = cv2.vconcat(image_list)
# 横に結合の場合
# image_h = cv2.hconcat(image_list)
# サイズ取得
h, w = image_v.shape[:2]
# 縦に分割するときの画素数
dx = int(h/m)
# データをmこに分割する。
new_imgs = [image_v[dx * i:dx * (i+1), :] for i in range(m)]
# できたやつを出力
for count, new_img in enumerate(new_imgs):
cv2.imwrite(f'OUTFOLDER/outfile_{topidx}_{topidx+n-1}_{count}.jpg', new_img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment