Last active
December 27, 2020 07:39
-
-
Save craftgear/87515c44868aa0f3a44f216c98b01633 to your computer and use it in GitHub Desktop.
A4サイズ以上の雑誌を分割スキャンした後に使う画像結合Pythonスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 使い方 | |
# $ python batch_stitching.py -i 画像のあるディレクトリ | |
# | |
# 結合する画像は重なっている部分が必要です。 | |
# 画像の天地は揃えたほうがよいです。縦横が違うとズレが出ます。 | |
# opencv-contrib-pythonとimutilsを別途インストールする必要があります。 | |
import os | |
import functools | |
import argparse | |
from pathlib import Path | |
import cv2 | |
from imutils import paths | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"-p", | |
"--prefix", | |
type=str, | |
default="stitched_", | |
help="スキャン後の画像に付ける接頭辞、デフォルト 'stitched_'", | |
) | |
parser.add_argument( | |
"-i", | |
"--input_dir", | |
type=str, | |
required=True, | |
help="スキャンした画像がおいてあるディレクトリ名", | |
) | |
parser.add_argument( | |
"-n", | |
"--number", | |
type=int, | |
default=2, | |
help="画像を何枚ごとに結合するか指定、デフォルト 2", | |
) | |
def take_every(count=2): | |
def _(accum, curr): | |
last_element = accum[len(accum) - 1] | |
if len(last_element) < count: | |
last_element.append(curr) | |
else: | |
accum.append([curr]) | |
return accum | |
return _ | |
def main(): | |
args = parser.parse_args() | |
# list up images | |
image_paths = sorted(list(paths.list_images(args.input_dir))) | |
grouped_image_paths = functools.reduce(take_every(args.number), image_paths, [[]]) | |
stitcher = cv2.Stitcher.create(mode=cv2.Stitcher_SCANS) | |
for _i, _p in enumerate(grouped_image_paths): | |
_, ext = os.path.splitext(_p[0]) | |
new_filename = f"{args.input_dir}{args.prefix}{_i + 1:05}{ext}" | |
if Path(new_filename).exists(): | |
print(f"{new_filename}はすでに存在します。{_p}の結合をスキップします。") | |
continue | |
images = list(map(cv2.imread, _p)) | |
print(f"{_p} を結合中...") | |
status, stitched = stitcher.stitch(images) | |
if status == cv2.Stitcher_OK: | |
cv2.imwrite(new_filename, stitched) | |
else: | |
print(f"error: ファイル {_p} の結合に失敗しました ステータス({status})") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment