코드

[Python] 유튜브 영상을 다운받아 일정 간격으로 캡쳐하여 10장씩 merge하기

by 이니스프리 posted May 27, 2020
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄
Extra Form
라이선스 기타(따로 작성)

안녕하세요??

 

몇몇 개발자 커뮤니티에서 유튜브 영상을 리뷰 및 추천하는 사이트를 만들면 좋겠다는 글을 본 적이 있는데요 ^^

 

그런 사이트에서 활용할 수 있도록 유튜브 영상을 다운받아서 일정 간격으로 캡쳐하여 10장씩 merge하는 스크립트를 작성했어요~!

 

progress를 표시하는 것에 중점을 두었네요 :)

 

 

 

from pytube import YouTube
from PIL import Image
from tqdm import tqdm
import cv2, os, pathlib, glob, shutil


### 유튜브 영상을 다운받습니다. ###
def yt_download():
    yt = YouTube('https://www.youtube.com/watch?v=JVlulhg92bU')
    yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
    os.rename(yt.streams.first().default_filename, 'yt_temp.mp4')
    print('Download is finished.')
    return


### 유튜브 영상을 일정 간격으로 캡쳐합니다. ###
def capture_mp4():
    folder = '.\\temp_yt_capture\\'
    cap = cv2.VideoCapture('yt_temp.mp4')
    if not os.path.isdir(folder):
        os.mkdir(folder)
    
    interval = 3 # 몇 초 간격으로 캡쳐를 할지 결정합니다.
    success = True
    count = 0
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = int(frame_count/fps) + 1
    fill_zero = len(str(duration))
    
    progress = ['-', '/', '|', '\\']
    print('Capture :  ', end = '')
    while success:
        success, image = cap.read()
        if count%(interval*fps) == 0 :
            second = str(int(count/fps)).zfill(fill_zero)
            prefix = 'temp_'
            extension = '.jpg'
            filename = prefix + second + extension
            cv2.imwrite(folder + filename, image)
        print('\b' + progress[count % 4], end = '')
        count += 1
    
    list = []
    for path, subdirs, files in os.walk(folder):
        for name in files:
            list.append(os.path.join(path, name))
    
    ext_list = ['.jpg']
    for file in list:
        if os.path.getsize(file) == 0:
            if any(ext.lower() in pathlib.Path(file).suffix.lower() for ext in ext_list):
                print('\nDeleted file(s) : ', file)
                os.remove(file)
    
    cap.release()
    cv2.destroyAllWindows()
    return


### 다운받은 영상을 merge합니다. ###
def img_merge(list_img, number, total_number):
    images = map(Image.open, list_img)
    widths, heights = zip(*(i.size for i in images))
    max_width = max(widths)
    total_height = sum(heights) + (len(list_img) - 1) * 50
    
    new_im = Image.new('RGB', (max_width, total_height), (255, 255, 255))
    images = map(Image.open, list_img)
    y = 0
    for im in images:
        x = int((max_width - im.size[0]) / 2)
        new_im.paste(im, (x, y))
        y += im.size[1] + 50
    new_im.save('result' + str(number).zfill(len(str(total_number))) + '.jpg', quality=95)
    return


### 사진을 10장씩 묶습니다. ###
def divide_by_10():
    list_jpg = glob.glob('.\\temp_yt_capture\\*.jpg')
    list_jpg.sort()
    cuts = len(list_jpg) // 10 + 1 if len(list_jpg) / 10 != len(list_jpg) // 10 else len(list_jpg) // 10
    print('\nMerge : ')
    for i in tqdm(range(0, cuts)):
        temp_list = list_jpg[i * 10 : (i + 1) * 10]
        img_merge(temp_list, i + 1, cuts)
    return


### 임시파일을 삭제합니다. ###
def delete_temp():
    os.remove('yt_temp.mp4')
    shutil.rmtree('.\\temp_yt_capture\\')
    return


if __name__ == '__main__':
    yt_download()
    capture_mp4()
    divide_by_10()
    delete_temp()

 

 

 

progress는 다음과 같이 표시되어요!

 

image 20200527152326.png.jpg

 

 

 

다음과 같은 파일들이 생성되는 것을 확인할 수 있어요 ^^

 

result01.jpg

 

 

 

유튜브를 리뷰하는 사이트를 개설하신 분들께서 잘 활용하시면 좋을 것 같네요 :)

 

허접한 스크립트를 읽어주셔서 감사드립니다!

 

그럼 맛저 드세요~ ^-^

 


Articles

1 2 3 4