?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
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

 

 

 

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

 

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

 

그럼 맛저 드세요~ ^-^

 

  • ?
    GsusWeb 2020.07.04 14:52
    아니.. 이런 곳이?
    당장은 아니어도 나중에 유용하게 사용할 보물창고 같네요 ㅎ
  • profile
    이니스프리 2020.07.04 15:21
    옙 허접한 소스이지만 마음껏 사용하세요 ^-^
  • ?
    GsusWeb 2020.07.04 15:27
    어딜봐서 허접하다고 하시는 지 모르겠네요. ^^
    대단합니다!

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
78 코드 AWSCLI, in a single file (portable, linux) file Seia 2021.04.10 164
77 코드 [Python-Gnuboard] 파이썬으로 구현한 그누보드 자동 글쓰기 함수 1 file 이니스프리 2021.04.08 1213
76 코드 [Python] 휴일지킴이 약국을 크롤링하여 Folium 지도에 마커로 표시하는 PyQt 윈도우 앱 7 file 이니스프리 2021.03.13 1143
75 코드 도박 중독자를 위한 광고 차단 규칙 file 제르엘 2020.08.21 290
» 코드 [Python] 유튜브 영상을 다운받아 일정 간격으로 캡쳐하여 10장씩 merge하기 3 file 이니스프리 2020.05.27 1045
73 자료 [Autohotkey] 매분 정각에 전체화면을 캡쳐하는 스크립트 4 file 이니스프리 2020.05.22 1100
72 코드 [Python/Telegram] Studyforus 알림봇 (댓글, 스티커 파싱) 7 file 이니스프리 2020.05.15 644
71 코드 [Python] url 주소로부터 IP 주소 알아내기 title: 황금 서버 (30일)humit 2020.02.20 2053
70 코드 [Python] 네이버 실시간 검색어 3 title: 황금 서버 (30일)humit 2020.01.23 1122
69 코드 Koa에서 자동으로 라우팅 채워주기 Seia 2020.01.22 436
68 코드 JavaScript에서 파이썬 문자열 처리 함수 중 하나 (바인딩)를 구현 7 Seia 2020.01.20 462
67 코드 [Python] Google Image Search 결과를 받아오기 file 이니스프리 2019.12.09 947
66 코드 [파이썬] Requests를 사용한 네이버 카페 크롤링 - 일정수 이상의 리플이 달린 게시글만 텔레그램 알림 3 file 이니스프리 2019.11.17 4181
65 코드 [JS] 클라이언트단 GET Parameter Hanam09 2019.11.16 465
64 코드 [Python] 싸이월드 미니홈피 백업 스크립트 1 이니스프리 2019.11.07 2165
63 코드 [Python] PIL을 이용한 Animated GIF의 리사이징 file 이니스프리 2019.11.03 1099
62 코드 [PyQt] sir.kr에서 스크랩한 게시글을 보여주는 윈도우앱 (검색 및 정렬 가능) 7 file 이니스프리 2019.08.09 997
61 코드 [아미나] Dropbox API를 이용한 이미지 호스팅 보드스킨 12 file 이니스프리 2019.07.13 1373
60 코드 [Python] 네이버 모바일 이미지 검색에서의 이미지 파일을 멀티스레드로 다운받고 1개의 파일로 병합 11 file 이니스프리 2019.07.12 1376
59 코드 [PHP/Javascript] 아미나에 자동으로 게시글을 생성하고 Ajax로 전송하여 결과를 표시하기 2 file 이니스프리 2019.07.09 775
Board Pagination Prev 1 2 3 4 Next
/ 4