Last active
August 22, 2024 08:16
-
-
Save secsilm/79c7e9ab32b9d966ab04a98c084d66a7 to your computer and use it in GitHub Desktop.
合并米家摄像头监控视频,生成以天为单位的视频文件。
This file contains 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
import argparse | |
import subprocess | |
from pathlib import Path | |
from loguru import logger | |
parser = argparse.ArgumentParser(description='合并米家摄像头视频,以天为单位。') | |
parser.add_argument('indir', help='原米家摄像头视频目录。') | |
parser.add_argument('--outdir', default='./', help='合并后视频存放目录,目录不存在会被创建。默认当前目录。') | |
args = parser.parse_args() | |
def merge_vids(vidlist_file: str, tofile: str): | |
"""执行 ffmpeg 命令合并视频。""" | |
# 需要对音频重新编码,否则会报错: | |
# Could not find tag for codec pcm_alaw in stream #1, codec not currently supported in container when concatenating 2 files using ffmpeg | |
cmd = f"ffmpeg -f concat -safe 0 -i {vidlist_file} -c:v copy -c:a flac -strict -2 {tofile}" | |
subprocess.run(cmd) | |
def merge_dirs(indir: str, outdir: str): | |
"""合并目录下的监控文件,在当前目录生成以天为单位的视频。 | |
indir 结构: | |
indir | |
2021051001 | |
2021051002 | |
2021051003 | |
... | |
即,子目录结构为:年月日时。 | |
""" | |
if not Path(outdir).exists(): | |
logger.info(f'{outdir} 不存在,即将被创建') | |
Path(outdir).mkdir(parents=True) | |
date_dict = {} | |
for d in Path(indir).iterdir(): | |
if not d.is_dir(): | |
continue | |
date = d.stem[:8] | |
if date not in date_dict: | |
date_dict[date] = [] | |
date_dict[date].append(d) | |
for date, ds in date_dict.items(): | |
videos = [] | |
for d in ds: | |
videos.extend(list(Path(d).glob("*.mp4"))) | |
logger.info(f"{date}, {len(videos)} videos") | |
if not videos: | |
continue | |
videos = sorted(videos, key=lambda f: int(f.stem.split("_")[-1])) | |
videos = [ | |
"file " + str(f.resolve(strict=True)).replace("\\", "/") for f in videos | |
] | |
Path("vidslist.txt").write_text("\n".join(videos), encoding="utf8") | |
merge_vids("vidslist.txt", Path(outdir).joinpath(f"{date}.mp4")) | |
if __name__ == "__main__": | |
merge_dirs(args.indir, args.outdir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment