?

단축키

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
번호 분류 제목 글쓴이 날짜 조회 수
58 자료 [XE / Rhymix] Bootstrap 패널 위젯 스타일 file title: 은메달도다 2017.08.09 603
57 코드 [PHP] 간단한 캐싱 클래스 3 title: 황금 서버 (30일)humit 2018.12.06 605
56 자료 경험치 현황 위젯 6 file NoYeah 2017.06.28 622
55 코드 [JS]클라이언트에서 Ip를 얻어보자 2 Hanam09 2019.01.21 625
54 자료 [Bootstrap] xeACE 레이아웃 3 title: 은메달도다 2017.09.17 633
53 코드 [아미나] 게시글을 작성하면 ID와 IP로 필터링하여 자동으로 랜덤 댓글을 남기기 (+랜덤 포인트) 7 file 이니스프리 2018.11.18 634
52 자료 Gentelella 레이아웃에 사용가능한 가격 테이블 위젯입니다. 3 file NoYeah 2017.07.03 638
51 코드 브라우저 언어에 따라 다른 폴더를 사용하는 PHP 코드 4 file 네모 2017.10.10 639
50 코드 Cmd 에서 서비스 시작 / 종료하기 1 ProjectSE 2018.02.18 644
49 코드 [PHP] 기상청 중기예보를 캐러셀로 보여주는 위젯 (매우 허접합니다 ㅠㅠ) 10 file 이니스프리 2018.09.28 647
48 자료 AdBlock 접근 방지 애드온 v0.1 3 file 네모 2017.10.05 649
47 코드 [Python/Telegram] Studyforus 알림봇 (댓글, 스티커 파싱) 7 file 이니스프리 2020.05.15 650
46 코드 Git 저장소에서 자동으로 받아 업데이트하는 쉘 스크립트 5 NoYeah 2017.09.16 651
45 코드 html 초보가 만든 자소서 4 title: 대한민국 국기gimmepoint 2018.04.21 652
44 코드 [PHP] 그누보드 자동 게시글 작성 - 일본기상협회의 우리나라 날씨를 크롤링한 후 파파고로 번역하여 글 작성 4 file 이니스프리 2018.11.15 657
43 코드 [아미나] 출석 여부를 나타내는 메인화면 위젯 4 file 이니스프리 2018.12.15 666
42 자료 이게 팔릴까 - Xe/라이믹스 에러페이지 [2017-10-04] 3 file title: 열려라 맛스타의 자물쇠TVJ 2017.10.04 672
41 코드 [JS] http를 https로 리디렉션! 3 Hanam09 2018.12.30 674
40 자료 RBGE - 이쁘고 깔끔한 에러페이지 4 file title: 열려라 맛스타의 자물쇠TVJ 2017.08.08 687
39 코드 엑셀파일 불러서 히스토그램 그려주는 함수 국내산라이츄 2017.08.03 724
Board Pagination Prev 1 2 3 4 Next
/ 4