컴퓨터/Python

python 동영상 가로세로 비율 조정 코드

풍경소리^^ 2025. 9. 23. 17:39
pip install ffmpeg-python

 

import ffmpeg
import os

def resize_video_width(input_path, output_path, width_scale=1.0):
    """
    동영상의 가로 크기를 조정합니다.
    
    Parameters:
    input_path (str): 입력 동영상 파일 경로
    output_path (str): 출력 동영상 파일 경로  
    width_scale (float): 가로 크기 배율 (1.0=원본, 0.5=반으로, 2.0=두배로)
    """
    try:
        # 입력 파일 정보 확인
        probe = ffmpeg.probe(input_path)
        video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
        
        original_width = int(video_info['width'])
        original_height = int(video_info['height'])
        
        # 새로운 가로 크기 계산 (짝수로 맞춤)
        new_width = int(original_width * width_scale)
        if new_width % 2 != 0:
            new_width += 1
            
        print(f"원본 크기: {original_width}x{original_height}")
        print(f"변경 크기: {new_width}x{original_height}")
        
        # ffmpeg로 크기 조정
        stream = ffmpeg.input(input_path)
        stream = ffmpeg.filter(stream, 'scale', new_width, original_height)
        stream = ffmpeg.output(stream, output_path)
        
        # 기존 파일이 있으면 덮어쓰기
        ffmpeg.run(stream, overwrite_output=True)
        
        print(f"변환 완료: {output_path}")
        
    except Exception as e:
        print(f"오류 발생: {e}")

def restore_original_aspect_ratio(input_path, output_path, target_width=None, target_height=None):
    """
    찌그러진 동영상을 원본 비율로 복원합니다.
    
    Parameters:
    input_path (str): 입력 동영상 파일 경로
    output_path (str): 출력 동영상 파일 경로
    target_width (int): 목표 가로 크기 (None이면 자동 계산)
    target_height (int): 목표 세로 크기 (None이면 자동 계산)
    """
    try:
        probe = ffmpeg.probe(input_path)
        video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
        
        current_width = int(video_info['width'])
        current_height = int(video_info['height'])
        
        # 휴대폰 세로 영상의 일반적인 비율 (9:16)
        if target_width is None and target_height is None:
            # 현재 높이를 기준으로 9:16 비율 계산
            target_width = int(current_height * 9 / 16)
            target_height = current_height
        elif target_width is None:
            target_width = int(target_height * 9 / 16)
        elif target_height is None:
            target_height = int(target_width * 16 / 9)
            
        # 짝수로 맞춤
        if target_width % 2 != 0:
            target_width += 1
        if target_height % 2 != 0:
            target_height += 1
            
        print(f"현재 크기: {current_width}x{current_height}")
        print(f"복원 크기: {target_width}x{target_height}")
        
        stream = ffmpeg.input(input_path)
        stream = ffmpeg.filter(stream, 'scale', target_width, target_height)
        stream = ffmpeg.output(stream, output_path)
        
        ffmpeg.run(stream, overwrite_output=True)
        
        print(f"복원 완료: {output_path}")
        
    except Exception as e:
        print(f"오류 발생: {e}")

def batch_process_videos(input_folder, output_folder, width_scale=1.0):
    """
    폴더 내 모든 동영상 파일을 일괄 처리합니다.
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv']
    
    for filename in os.listdir(input_folder):
        if any(filename.lower().endswith(ext) for ext in video_extensions):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, f"resized_{filename}")
            
            print(f"처리 중: {filename}")
            resize_video_width(input_path, output_path, width_scale)

# 사용 예시
if __name__ == "__main__":
    # 1. 단일 파일 처리 - 가로 크기를 원본의 60%로 줄이기
    input_file = "input_video.mp4"
    output_file = "output_narrow.mp4"
    resize_video_width(input_file, output_file, width_scale=0.6)
    
    # 2. 찌그러진 영상을 원본 세로 비율로 복원
    distorted_file = "stretched_video.mp4"  
    restored_file = "restored_vertical.mp4"
    restore_original_aspect_ratio(distorted_file, restored_file)
    
    # 3. 폴더 내 모든 동영상 일괄 처리
    # batch_process_videos("input_folder", "output_folder", width_scale=0.7)

 

주요 기능:

  1. resize_video_width(): 가로 크기만 조정 (세로는 유지)
  2. restore_original_aspect_ratio(): 찌그러진 영상을 원본 세로 비율(9:16)로 복원
  3. batch_process_videos(): 폴더 내 모든 동영상 일괄 처리

사용법:

 
 
python
# 찌그러진 영상을 원본 세로 비율로 복원
restore_original_aspect_ratio("stretched_video.mp4", "restored_video.mp4")

# 또는 가로 크기를 직접 조정 (60%로 줄이기)
resize_video_width("input.mp4", "output.mp4", width_scale=0.6)

주의사항:

  • ffmpeg가 시스템에 설치되어 있어야 합니다
  • 동영상 크기는 항상 짝수로 맞춰집니다 (인코딩 호환성)
  • 기존 파일이 있으면 자동으로 덮어씁니다