?

단축키

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. 세린서버에서 시도중인 백업 스크립트 입니다.

    Date2017.06.27 Category코드 ByNoYeah Views746
    Read More
  2. AdminLTE용 에디터 스타일

    Date2017.07.07 Category자료 Bytitle: 은메달도다 Views770
    Read More
  3. [PHP/Javascript] 아미나에 자동으로 게시글을 생성하고 Ajax로 전송하여 결과를 표시하기

    Date2019.07.09 Category코드 By이니스프리 Views778
    Read More
  4. even_move - 감성적인 에러 페이지

    Date2017.08.08 Category자료 Bytitle: 열려라 맛스타의 자물쇠TVJ Views798
    Read More
  5. Gentelella

    Date2017.06.29 Category자료 ByNoYeah Views806
    Read More
  6. 폰트를 자동 설치하는 코드

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

    Date2018.10.20 Category코드 By이니스프리 Views841
    Read More
  8. [PHP] 기상청 RSS 시간별 예보 위젯 - cache 적용(?)

    Date2018.10.28 Category코드 By이니스프리 Views850
    Read More
  9. 사이트 서버 이전 (또는 미러링 사이트 구축) 쉽게하는 스크립트

    Date2018.01.14 Category코드 ByNoYeah Views858
    Read More
  10. 소셜XE / 기존 통합 로그인 스킨 V2.2

    Date2017.06.28 Category자료 ByNoYeah Views909
    Read More
  11. 유튜브에 약간의 기능을 추가 해주는 크롬 확장 프로그램.

    Date2018.01.26 Category코드 ByHanam09 Views942
    Read More
  12. [Python] Google Image Search 결과를 받아오기

    Date2019.12.09 Category코드 By이니스프리 Views950
    Read More
  13. 잘못 쓰면 컴퓨터가 날아가는 코드

    Date2018.07.08 Category코드 By제르엘 Views964
    Read More
  14. [아미나] 네이트 실시간 검색어 순위 위젯 (아미나 캐시 적용)

    Date2018.12.18 Category코드 By이니스프리 Views975
    Read More
  15. [PyQt] sir.kr에서 스크랩한 게시글을 보여주는 윈도우앱 (검색 및 정렬 가능)

    Date2019.08.09 Category코드 By이니스프리 Views1001
    Read More
  16. [Python] 선택한 파일을 Dropbox API를 이용하여 업로드하고 공유링크를 받아서 이미지 호스팅 용도로 URL을 변환하기

    Date2019.07.02 Category코드 By이니스프리 Views1005
    Read More
  17. CMD로 로컬 연결 고정 IP 설정하기

    Date2018.02.06 Category코드 Bytitle: 황금 서버 (30일)humit Views1038
    Read More
  18. [Python] 유튜브 영상을 다운받아 일정 간격으로 캡쳐하여 10장씩 merge하기

    Date2020.05.27 Category코드 By이니스프리 Views1063
    Read More
  19. 클라이언트단에서 이미지 리사이징

    Date2018.05.06 Category코드 By네모 Views1078
    Read More
  20. 컴퓨터의 uuid 얻기

    Date2018.01.28 Category코드 Bytitle: 황금 서버 (30일)humit Views1099
    Read More
Board Pagination Prev 1 2 3 4 Next
/ 4