Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ninjaneural
GitHub Repository: ninjaneural/webui
Path: blob/master/memo/comfyui_anidiff_long/combine.py
3275 views
1
import os
2
import shutil
3
from PIL import Image
4
import subprocess
5
import math
6
import glob
7
8
def blend_images(image1, image2, alpha=0.5):
9
"""두 이미지를 블렌딩합니다."""
10
return Image.blend(image1, image2, alpha)
11
12
def process_images(source_dir, target_dir, max_images, video_output, fps, sound_file):
13
"""지정된 폴더에서 이미지를 처리하고 동영상으로 변환합니다."""
14
if not os.path.exists(target_dir):
15
os.makedirs(target_dir)
16
else:
17
shutil.rmtree(target_dir)
18
os.makedirs(target_dir)
19
20
group_images = []
21
for subdir, _, files in os.walk(source_dir):
22
if subdir != source_dir:
23
images = [os.path.join(subdir, f) for f in sorted(files) if f.lower().endswith(('png', 'jpg', 'jpeg'))]
24
group_images.append((subdir, images))
25
26
image_counter = 0
27
blend_next = []
28
29
for idx, (subdir, images) in enumerate(group_images):
30
print(f"# {subdir}")
31
extra_image_count = len(blend_next)
32
33
if max_images == 0:
34
curr_max_images = math.floor(len(images) / 10) * 10
35
print(f"auto max_images: {curr_max_images}")
36
else:
37
curr_max_images = max_images
38
39
# 현재 하위 목록이 마지막인지 확인
40
is_last_sublist = idx == len(group_images) - 1
41
42
extra_image_count = len(blend_next)
43
for i, image_path in enumerate(images):
44
print(f" - {image_path}")
45
if is_last_sublist or i < curr_max_images:
46
if len(blend_next) > 0:
47
opacity = 1 - (extra_image_count + 1 - len(blend_next))/(extra_image_count+1)
48
with Image.open(image_path) as img1, Image.open(blend_next.pop(0)) as img2:
49
blended = blend_images(img1, img2, opacity)
50
blended.save(os.path.join(target_dir, f"{image_counter+1:07d}.png"))
51
else:
52
#os.rename(image_path, os.path.join(target_dir, f"{image_counter+1:07d}.png"))
53
shutil.copy(image_path, os.path.join(target_dir, f"{image_counter+1:07d}.png"))
54
image_counter += 1
55
else:
56
blend_next.append(image_path)
57
58
# FFmpeg를 사용하여 동영상 생성
59
if video_output:
60
if sound_file and os.path.isfile(sound_file):
61
ffmpeg_command = f"ffmpeg -framerate {fps} -i {target_dir}/%07d.png -i {sound_file} -c:a copy -c:v libx264 -pix_fmt yuv420p -map 0:v -map 1:a {video_output}"
62
else:
63
ffmpeg_command = f"ffmpeg -framerate {fps} -i {target_dir}/%07d.png -c:v libx264 -pix_fmt yuv420p {video_output}"
64
subprocess.run(ffmpeg_command, shell=True)
65
66
# 사용 예
67
source_dir = './extract' # 소스 폴더 경로
68
target_dir = './combine_old' # 타겟 폴더 경로
69
70
video_output = 'output_video.mp4' # 출력 동영상 파일 이름
71
max_images_per_folder = 0 # 폴더당 최대 이미지 수, 0 이면 10의 배수로 자동 설정
72
fps = 30
73
sound_file = "sound.mp4" # 사운드파일 mp3, mp4등
74
75
process_images(source_dir, target_dir, max_images_per_folder, video_output, fps, sound_file)
76
77