?

단축키

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
    어딜봐서 허접하다고 하시는 지 모르겠네요. ^^
    대단합니다!

  1. [Python] 싸이월드 미니홈피 백업 스크립트

    Date2019.11.07 Category코드 By이니스프리 Views2169
    Read More
  2. [Python] 유튜브 영상을 다운받아 일정 간격으로 캡쳐하여 10장씩 merge하기

    Date2020.05.27 Category코드 By이니스프리 Views1063
    Read More
  3. [Python] 텔레그램을 이용한 게시판 새 글 알림봇

    Date2018.12.02 Category코드 By이니스프리 Views3547
    Read More
  4. [Python] 휴일지킴이 약국을 크롤링하여 Folium 지도에 마커로 표시하는 PyQt 윈도우 앱

    Date2021.03.13 Category코드 By이니스프리 Views1148
    Read More
  5. [XE / Rhymix] Bootstrap 패널 위젯 스타일

    Date2017.08.09 Category자료 Bytitle: 은메달도다 Views603
    Read More
  6. [아미나] Dropbox API를 이용한 이미지 호스팅 보드스킨

    Date2019.07.13 Category코드 By이니스프리 Views1384
    Read More
  7. [아미나] 게시글을 작성하면 ID와 IP로 필터링하여 자동으로 랜덤 댓글을 남기기 (+랜덤 포인트)

    Date2018.11.18 Category코드 By이니스프리 Views634
    Read More
  8. [아미나] 네이트 실시간 검색어 순위 위젯 (아미나 캐시 적용)

    Date2018.12.18 Category코드 By이니스프리 Views975
    Read More
  9. [아미나] 출석 여부를 나타내는 메인화면 위젯

    Date2018.12.15 Category코드 By이니스프리 Views666
    Read More
  10. [오토핫키] 구글 드라이브의 공유링크를 이미지 호스팅을 위한 다이렉트 링크로 바꿔주는 스크립트

    Date2018.09.25 Category코드 By이니스프리 Views1671
    Read More
  11. [오토핫키] 브라우저를 열어 지난번과 동일한 폴더에 MZK를 다운받고 압축을 네이티브로 해제하는 스크립트

    Date2018.10.20 Category코드 By이니스프리 Views841
    Read More
  12. [오토핫키] 특정 사이트에 대한 ping 테스트 결과를 실행시간과 함께 로그 파일로 저장하는 스크립트

    Date2018.09.22 Category코드 By이니스프리 Views1915
    Read More
  13. [파이썬] Requests를 사용한 네이버 카페 크롤링 - 일정수 이상의 리플이 달린 게시글만 텔레그램 알림

    Date2019.11.17 Category코드 By이니스프리 Views4193
    Read More
  14. 경험치 현황 위젯

    Date2017.06.28 Category자료 ByNoYeah Views622
    Read More
  15. 내가 만든 merge sort

    Date2018.05.17 Bytitle: 대한민국 국기gimmepoint Views370
    Read More
  16. 내가 만든 사칙연산 계산기

    Date2018.05.11 Category코드 Bytitle: 대한민국 국기gimmepoint Views515
    Read More
  17. 내가 만든 함수 모음집

    Date2018.05.08 Category코드 Bytitle: 대한민국 국기gimmepoint Views382
    Read More
  18. 내가 만든 함수 모음집 2

    Date2018.05.12 Category코드 Bytitle: 대한민국 국기gimmepoint Views379
    Read More
  19. 도박 중독자를 위한 광고 차단 규칙

    Date2020.08.21 Category코드 By제르엘 Views294
    Read More
  20. 링크 파싱 애드온용 스킨 (트위터 스타일)

    Date2017.10.03 Category자료 BySNAX Views516
    Read More
Board Pagination Prev 1 2 3 4 Next
/ 4