Python3視頻轉(zhuǎn)字符動畫的實(shí)例代碼
更新時(shí)間:2019年08月29日 10:31:50 作者:挑食de豬隊(duì)友
這篇文章主要介紹了Python3視頻轉(zhuǎn)字符動畫的實(shí)例代碼,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
Python3視頻轉(zhuǎn)字符動畫,具體代碼如下所示:
# -*- coding:utf-8 -*-
import json
import os
import subprocess
from pathlib import Path
from cv2 import cv2
import numpy as np
from time import time
import webbrowser
play_chars_js = '''
let i = 0;
window.setInterval(function(){
let img = frames[i++];
let html = ""
for(let line of img){
for(let char of line){
let [[r,g,b], ch] = char;
html += '<span style="color:rgb(' + r + ', ' + g + ', '+ b + ');">'+ ch + '</span>'
// html += '<span style="background-color:rgb(' + r + ', ' + g + ', '+ b + ');">'+ ch + '</span>'
}
html += "<br>"
}
document.getElementsByClassName("video-panel")[0].innerHTML = html
}, 1000/fps);
document.getElementsByTagName("audio")[0].play();
'''
class VideoToHtml:
# 像素形狀,因?yàn)轭伾呀?jīng)用rgb控制了,這里的pixels其實(shí)可以隨意排
pixels = "$#@&%ZYXWVUTSRQPONMLKJIHGFEDCBA098765432?][}{/)(><zyxwvutsrqponmlkjihgfedcba*+1-."
def __init__(self, video_path, fps_for_html=8, time_interval=None):
"""
:param video_path: 字符串, 視頻文件的路徑
:param fps_for_html: 生成的html的幀率
:param time_interval: 用于截取視頻(開始時(shí)間,結(jié)束時(shí)間)單位秒
"""
self.video_path = Path(video_path)
# 從指定文件創(chuàng)建一個(gè)VideoCapture對象
self.cap = cv2.VideoCapture(video_path)
self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.frames_count_all = self.cap.get(cv2.CAP_PROP_FRAME_COUNT)
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
self.resize_width = None
self.resize_height = None
self.frames_count = 0
self.fps_for_html = fps_for_html
self.time_interval = time_interval
def video2mp3(self):
"""#調(diào)用ffmpeg獲取mp3音頻文件"""
mp3_path = self.video_path.with_suffix('.mp3')
subprocess.call('ffmpeg -i ' + str(self.video_path) + ' -f mp3 ' + str(mp3_path), shell=True)
return mp3_path
def set_width(self, width):
"""只能縮小,而且始終保持長寬比"""
if width >= self.width:
return False
else:
self.resize_width = width
self.resize_height = int(self.height * (width / self.width))
return True
def set_height(self, height):
"""只能縮小,而且始終保持長寬比"""
if height >= self.height:
return False
else:
self.resize_height = height
self.resize_width = int(self.width * (height / self.height))
return True
def resize(self, img):
"""
將img轉(zhuǎn)換成需要的大小
原則:只縮小,不放大。
"""
# 沒指定就不需resize了
if not self.resize_width or not self.resize_height:
return img
else:
size = (self.resize_width, self.resize_height)
return cv2.resize(img, size, interpolation=cv2.INTER_CUBIC)
def get_img_by_pos(self, pos):
"""獲取到指定位置的幀"""
# 把指針移動到指定幀的位置
self.cap.set(cv2.CAP_PROP_POS_FRAMES, pos)
# cap.read() 返回值介紹:
# ret 布爾值,表示是否讀取到圖像
# frame 為圖像矩陣,類型為 numpy.ndarray.
ret, frame = self.cap.read()
return ret, frame
def get_frame_pos(self):
"""生成需要獲取的幀的位置,使用了惰性求值"""
step = self.fps / self.fps_for_html
# 如果未指定
if not self.time_interval:
self.frames_count = int(self.frames_count_all / step) # 更新count
return (int(step * i) for i in range(self.frames_count))
# 如果指定了
start, end = self.time_interval
pos_start = int(self.fps * start)
pos_end = int(self.fps * end)
self.frames_count = int((pos_end - pos_start) / step) # 更新count
return (pos_start + int(step * i) for i in range(self.frames_count))
def get_imgs(self):
assert self.cap.isOpened()
for i in self.get_frame_pos():
ret, frame = self.get_img_by_pos(i)
if not ret:
print("讀取失敗,跳出循環(huán)")
break
yield self.resize(frame) # 惰性求值
# 結(jié)束時(shí)要釋放空間
self.cap.release()
def get_char(self, gray):
percent = gray / 255 # 轉(zhuǎn)換到 0-1 之間
index = int(percent * (len(self.pixels) - 1)) # 拿到index
return self.pixels[index]
def get_json_pic(self, img):
"""測試階段,不實(shí)用"""
json_pic = []
# 寬高剛好和size相反,要注意。(這是numpy的特性。。)
height, width, channel = img.shape
# 轉(zhuǎn)換成灰度圖,用來選擇合適的字符
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for y in range(height):
line = []
for x in range(width):
r, g, b = img[y][x]
gray = img_gray[y][x]
char = self.get_char(gray)
line.append([[int(r), int(g), int(b)], char])
json_pic.append(line)
return json.dumps(json_pic)
def write_html_with_json(self, file_name):
"""測試階段,不實(shí)用"""
mp3_path = self.video2mp3()
time_start = time()
with open(file_name, 'w') as html:
# 要記得設(shè)置monospace等寬字體,不然沒法玩
html.write('<!DOCTYPE html>'
'<html>'
'<body style="font-family: monospace; font-size: small; font-weight: bold; text-align: center; line-height: 0.8;">'
'<div class="video-panel"></div>'
f'<audio src="{mp3_path.name}" autoplay controls></audio>'
'</body>'
'<script>'
'var frames=[\n')
try:
i = 0
for img in self.get_imgs():
json_pic = self.get_json_pic(img)
html.write(f"{json_pic},")
if i % 20:
print(f"進(jìn)度:{i/self.frames_count * 100:.2f}%, 已用時(shí):{time() - time_start:.2f}")
i += 1
finally:
html.write('\n];\n'
f'let fps={self.fps_for_html};\n'
f'{play_chars_js}'
'</script>\n'
'</html>')
def main():
# 視頻路徑,換成你自己的
video_path = "ceshi.mp4"
video2html = VideoToHtml(video_path, fps_for_html=8)
video2html.set_width(120)
html_name = Path(video_path).with_suffix(".html").name
video2html.write_html_with_json(html_name)
if __name__ == "__main__":
main()
總結(jié)
以上所述是小編給大家介紹的Python3視頻轉(zhuǎn)字符動畫的實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Python PCA降維的兩種實(shí)現(xiàn)方法
大家好,本篇文章主要講的是Python PCA降維的兩種實(shí)現(xiàn)方法,感興趣的的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
Python結(jié)合多線程與協(xié)程實(shí)現(xiàn)高效異步請求處理
在現(xiàn)代Web開發(fā)和數(shù)據(jù)處理中,高效處理HTTP請求是關(guān)鍵挑戰(zhàn)之一,本文將結(jié)合Python異步IO(asyncio)和多線程技術(shù),探討如何優(yōu)化請求處理邏輯,解決常見的線程事件循環(huán)問題,有需要的小伙伴可以根據(jù)需求進(jìn)行選擇2025-04-04
Python?異步如何使用等待有時(shí)間限制協(xié)程
這篇文章主要為大家介紹了Python?異步如何使用等待有時(shí)間限制協(xié)程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

