歡迎關(guān)注公眾號:Romi的雜貨鋪衙熔,這里有更多python相關(guān)的好康的~
在這篇文章中姻乓,我們將使用Python下載視頻,并將普通的視頻轉(zhuǎn)化為的代碼版本的視頻斤儿,效果如下:
首先我們需要獲取網(wǎng)頁上的視頻。一般情況下通過APP或者網(wǎng)頁上的視頻下載的問題有:
1.沒有提供下載按鈕導(dǎo)致無法下載
2.下載后的格式一般為.flv格式腔丧,或者是有自己的格式無法解析(例如B站)
針對第一個問題,我們的解決辦法就是Python中的you_get庫.You-Get 只需要一行代碼就可以便利的下載網(wǎng)絡(luò)上的媒體信息
you_get下載視頻
you_get主頁:https://github.com/soimort/you-get
中文說明文檔:https://github.com/soimort/you-get/wiki/%E4%B8%AD%E6%96%87%E8%AF%B4%E6%98%8E
首先依舊是需要安裝you-get庫,同時還需要安裝FFmpeg,這個工具是you-get庫的必要依賴惩阶,同時也會在其他的地方用到辐赞。本篇文章提供的FFmpeg地址為解壓免安裝版本括享,下載后解壓并記一下文件路徑搂根。其他
安裝完成后如果想下載某個網(wǎng)頁的視頻,,只需要一句簡單的 you-get+網(wǎng)址即可下載視頻.
$ you-get http://www.fsf.org/blogs/rms/20140407-geneva-tedx-talk-free-software-free-society
Site: fsf.org
Title: TEDxGE2014_Stallman05_LQ
Type: WebM video (video/webm)
Size: 27.12 MiB (28435804 Bytes)
Downloading TEDxGE2014_Stallman05_LQ.webm ...
100.0% ( 27.1/27.1 MB) ├████████████████████████████████████████┤[1/1] 12 MB/s
需要注意一點,上述例子you_get的基本命令是在cmd中輸入的命令行,如果我們使用IDE時需要使用os.system()方法來執(zhí)行cmd命令
import os
os.system('you-get http://www.fsf.org/blogs/rms/20140407-geneva-tedx-talk-free-software-free-society')
在一下的you_get示例中,所有的代碼均為cmd的代碼铃辖,所以使用IDE的同學(xué)記得要在代碼前加入os.system()函數(shù)以保證正確運行剩愧。
在下載前可以使用 --info/-i 以查看所有可用畫質(zhì)與格式:
$ you-get -i 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
site: YouTube
title: Me at the zoo
streams: # Available quality and codecs
[ DEFAULT ] _________________________________
- itag: 43
container: webm
quality: medium
size: 0.5 MiB (564215 bytes)
# download-with: you-get --itag=43 [URL]
- itag: 18
container: mp4
quality: medium
# download-with: you-get --itag=18 [URL]
- itag: 5
container: flv
quality: small
# download-with: you-get --itag=5 [URL]
- itag: 36
container: 3gp
quality: small
# download-with: you-get --itag=36 [URL]
- itag: 17
container: 3gp
quality: small
# download-with: you-get --itag=17 [URL]
標有DEFAULT 為默認畫質(zhì)。使用上述下載語句即可開始下載默認畫質(zhì)的視頻
如果希望下載其他格式或畫質(zhì)的視頻娇斩,使用提示中出現(xiàn)的 # download-with: 選項即可仁卷。例如我想下載上述示例中的MP4格式的視屏:
$ you-get --itag=18 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
當(dāng)下載視頻遇到問題時:
- 一是排除網(wǎng)絡(luò)問題;
- 二是確保you-get更新到最新版本犬第;
- 三是檢查目標視頻是否已經(jīng)確認無法爬取锦积。
- 四--debug參數(shù)進行調(diào)試
同時可以使用--output-dir/-o 設(shè)定路徑, --output-filename/-O 設(shè)定輸出文件名:
$ you-get -o ~/Videos -O zoo.webm 'https://www.youtube.com/watch?v=jNQXAC9IVRw'
這樣從網(wǎng)頁上下載視頻的問題就解決了!
視頻格式轉(zhuǎn)化
第二個問題就是從網(wǎng)頁上下載視頻的視頻很只有flv格式瓶殃,不利于預(yù)覽和處理充包。因此需要轉(zhuǎn)化視頻格式,比如轉(zhuǎn)化成MP4格式遥椿。但是一般在線頻轉(zhuǎn)化要么有視頻大小的限制,要么需要下載app或者會員淆储。這時候就要用到上面我們下載的FFmpeg處理視頻
FFmpeg 是視頻處理最常用的開源軟件冠场。它功能強大,用途廣泛本砰,大量用于視頻網(wǎng)站和商業(yè)軟件(比如 Youtube 和 iTunes)碴裙,也是許多音頻和視頻格式的標準編碼/解碼實現(xiàn)。使用FFmpeg 命令行處理視頻点额,比桌面視頻處理軟件更簡潔高效舔株。
例如我們想把所有的flv文件轉(zhuǎn)化為mp4文件:
(本部分涉及cmd命令與FFmpeg 命令行,如有疑問可以先搜一下Windows cmd命令的用法和FFmpeg 命令行的用法)
- 1.解壓后打開bin还棱,把三個可執(zhí)行文件復(fù)制到C:\Windows\system32
- 2.打開CMD载慈,cd 到指定文件夾
- 3.執(zhí)行cmd命令:
for %i in (*.flv) do ffmpeg -i “%i” -c copy “%~ni.mp4”
之后就可以發(fā)現(xiàn)所有的flv格式視頻全部轉(zhuǎn)化為了MP4格式。
轉(zhuǎn)化代碼版視頻
之后就可以將普通的視頻轉(zhuǎn)化為代碼版視頻了珍手。這里使用的代碼原作者文章:https://www.cnblogs.com/TurboWay/p/9748535.html
使用方法:
一办铡、環(huán)境準備
1.需要安裝opencv辞做,直接安裝 pip install opencv-python
2.需要安裝ffmpeg (上述步驟中已下載解壓的可跳過),直接解壓免安裝寡具,下載傳送門秤茅;
3.將 ffmpeg.exe 的路徑復(fù)制,替換代碼開頭的 ffmpeg = r'G:\ffmpeg\bin\ffmpeg.exe'
二童叠、如何使用:
1.替換主函數(shù)里的vedio視頻地址
2.運行程序即可
注意對存儲空間的要求較高框喳,請保證有足夠的存儲空間
代碼如下:
# -*- coding:utf-8 -*-
# coding:utf-8
import os, cv2, subprocess, shutil
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
from PIL import Image, ImageFont, ImageDraw
ffmpeg = r'D:\ffmpeg\bin\ffmpeg.exe'
code_color = (169,169,169) # 顏色RGB 默認灰色 ,'' 則彩色
# 像素對應(yīng)ascii碼
#ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")
#ascii_char = ['.',',',':',';','+','*','?','%','S','#','@'][::-1]
#ascii_char = list("MNHQ$OC67+>!:-. ")
ascii_char = list("MNHQ$OC67)oa+>!:+. ")
# 將像素轉(zhuǎn)換為ascii碼
def get_char(r, g, b, alpha=256):
if alpha == 0:
return ''
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)]
# 將txt轉(zhuǎn)換為圖片
def txt2image(file_name):
im = Image.open(file_name).convert('RGB')
# gif拆分后的圖像厦坛,需要轉(zhuǎn)換帖努,否則報錯,由于gif分割后保存的是索引顏色
raw_width = im.width
raw_height = im.height
width = int(raw_width / 6)
height = int(raw_height / 15)
im = im.resize((width, height), Image.NEAREST)
txt = ""
colors = []
for i in range(height):
for j in range(width):
pixel = im.getpixel((j, i))
colors.append((pixel[0], pixel[1], pixel[2]))
if (len(pixel) == 4):
txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
else:
txt += get_char(pixel[0], pixel[1], pixel[2])
txt += '\n'
colors.append((255, 255, 255))
im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
dr = ImageDraw.Draw(im_txt)
# font = ImageFont.truetype(os.path.join("fonts","漢儀楷體簡.ttf"),18)
font = ImageFont.load_default().font
x = y = 0
# 獲取字體的寬高
font_w, font_h = font.getsize(txt[1])
font_h *= 1.37 # 調(diào)整后更佳
# ImageDraw為每個ascii碼進行上色
for i in range(len(txt)):
if (txt[i] == '\n'):
x += font_h
y = -font_w
# self, xy, text, fill = None, font = None, anchor = None,
# *args, ** kwargs
if code_color:
dr.text((y, x), txt[i], fill=code_color) # fill=colors[i]彩色
else:
dr.text((y, x), txt[i], fill=colors[i]) # fill=colors[i]彩色
# dr.text((y, x), txt[i], font=font, fill=colors[i])
y += font_w
name = file_name
# print(name + ' changed')
im_txt.save(name)
# 將視頻拆分成圖片
def video2txt_jpg(file_name):
vc = cv2.VideoCapture(file_name)
c = 1
if vc.isOpened():
r, frame = vc.read()
if not os.path.exists('Cache'):
os.mkdir('Cache')
os.chdir('Cache')
else:
r = False
while r:
cv2.imwrite(str(c) + '.jpg', frame)
txt2image(str(c) + '.jpg') # 同時轉(zhuǎn)換為ascii圖
r, frame = vc.read()
c += 1
os.chdir('..')
return vc
# 將圖片合成視頻
def jpg2video(outfile_name, fps):
fourcc = VideoWriter_fourcc(*"MJPG")
images = os.listdir('Cache')
im = Image.open('Cache/' + images[0])
vw = cv2.VideoWriter(outfile_name, fourcc, fps, im.size)
os.chdir('Cache')
for image in range(len(images)):
# Image.open(str(image)+'.jpg').convert("RGB").save(str(image)+'.jpg')
frame = cv2.imread(str(image + 1) + '.jpg')
vw.write(frame)
# print(str(image + 1) + '.jpg' + ' finished')
os.chdir('..')
vw.release()
# 調(diào)用ffmpeg獲取mp3音頻文件
def video2mp3(file_name, outfile_name):
cmdstr = " -i {0} -f mp3 {1} -y".format(file_name, outfile_name)
cmd(cmdstr)
# 合成音頻和視頻文件
def video_add_mp3(file_name, mp3_file,outfile_name):
cmdstr = " -i {0} -i {1} -strict -2 -f mp4 {2} -y".format(file_name, mp3_file, outfile_name)
cmd(cmdstr)
# 視頻截取
def vediocut(file_name, outfile_name, start, end):
cmdstr = " -i {0} -vcodec copy -acodec copy -ss {1} -to {2} {3} -y".format(file_name,start,end,outfile_name)
cmd(cmdstr)
# 執(zhí)行腳本命令
def cmd(cmdstr):
cmdstr = ffmpeg + cmdstr
response = subprocess.call(cmdstr, shell=True, creationflags=0x08000000)
if response == 1:
print("ffmpeg腳本執(zhí)行失敗,請嘗試手動執(zhí)行:{0}".format(cmdstr))
# 主函數(shù)
def main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14'):
"""
:param vedio: 原視頻文件地址
:param save: 是否保存臨時文件 默認不保存
:param iscut: 是否先對原視頻做截取處理 默認不截取
:param start: 視頻截取開始時間點 僅當(dāng)iscut=True時有效
:param end: 視頻截取結(jié)束時間點 僅當(dāng)iscut=True時有效
:return: 輸出目標視頻文件 vedio.split('.')[0] + '-code.mp4'
"""
file_cut = vedio.split('.')[0] + '_cut.mp4'
file_mp3 = vedio.split('.')[0] + '.mp3'
file_temp_avi = vedio.split('.')[0] + '_temp.avi'
outfile_name = vedio.split('.')[0] + '-code.mp4'
print("開始生成...")
if iscut:
print("正在截取視頻...")
vediocut(vedio, file_cut, start, end)
vedio = file_cut
print("正在轉(zhuǎn)換代碼圖片...")
vc = video2txt_jpg(vedio) # 視頻轉(zhuǎn)圖片粪般,圖片轉(zhuǎn)代碼圖片
FPS = vc.get(cv2.CAP_PROP_FPS) # 獲取幀率
vc.release()
print("正在分離音頻...")
video2mp3(vedio, file_mp3) # 從原視頻分離出 音頻mp3
print("正在轉(zhuǎn)換代碼視頻...")
jpg2video(file_temp_avi, FPS) #代碼圖片轉(zhuǎn)視頻
print("正在合成目標視頻...")
video_add_mp3(file_temp_avi, file_mp3, outfile_name) # 將音頻合成到代碼視頻
if (not save): # 移除臨時文件
print("正在移除臨時文件...")
shutil.rmtree("Cache")
for file in [file_cut, file_mp3, file_temp_avi]:
if os.path.exists(file):
os.remove(file)
print("生成成功:{0}".format(outfile_name))
if __name__ == '__main__':
vedio = r"test.mp4"
main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14')
這樣就可以將一個視頻轉(zhuǎn)化為代碼版的視頻了拼余!