一直没好好整理结构,也没个做什么优化。突然要玩一下的话,还得翻好久代码改参数。现在改了改,加了UI,就顺手记录一下。
主要有两大模块
模块 | 功能 |
---|---|
UI模块 | 获取源视频地址、获取输出地址、获取一些参数 |
制作模块 | 从视频分离帧图像,将帧图像转为字符图,将转换后的图片重新合成视频 |
主要用到这几个库
库 | 用途 |
---|---|
tkinter | UI制作 |
cv2 | 视频提取图像、合成视频 |
PIL | 制作字符图 |
os | 路径相关操作 |
import os
import os.path as op
import warnings
from tkinter import Tk, StringVar, Label, Entry, Button, colorchooser, Scale, Spinbox, HORIZONTAL
from tkinter.filedialog import askdirectory, askopenfile
from tkinter.messagebox import showinfo, askokcancel
import threading
import cv2
from PIL import Image, ImageDraw, ImageFont
from random import randint
格式根据后缀判断
必须选择一个视频文件才能继续
class get_video():
def __init__(self):
self.box = Tk()
self.box.geometry('600x100')
self.video_path = StringVar
def if_video(self, path):
if path:
self.video_path = path.name
self.video_path = str(self.video_path)
if not self.video_path.split('/')[-1].split('.')[-1] in ['mp4', 'avi', 'gif', 'mkv', 'flv']:
if askokcancel('提示', '请选择视频文件!'):
self.selectpath()
else:
pass
else:
showinfo('yap!', f'视频{self.video_path} 选择成功')
self.box.destroy()
else:
showinfo('!!!!!!', '选择为空,请重新选择')
self.selectpath()
def selectpath(self):
path = askopenfile()
self.if_video(path)
def get_video_path(self):
Label(self.box, text='目标视频:', font=10).grid(row=0, column=0)
Entry(self.box, textvariable=self.video_path, width=50).grid(row=1, column=1)
Button(self.box, text='选择视频文件', font=6, fg='red', command=self.selectpath).grid(row=1, column=2)
self.box.mainloop()
-
制作字符动画[需要确定输出路径-类的继承、公用]
参数 说明 raw_video 源视频 rawpic_path 源视频提取出的帧图像保存路径(由输出路径+/raw 获得) 输出路径由后边的子类提供
这个之前有写过较详细的文章。点这里
def pic_split(self, raw_video, rawpic_path): vc = cv2.VideoCapture(raw_video) success, frame = vc.read() i = 0 while success: i += 1 img_path = f'{rawpic_path}/{i}.png' if op.exists(img_path): success, frame = vc.read() continue cv2.imwrite(img_path, frame) if success: print(f'\r Split img[{i} {img_path}', end='') success, frame = vc.read()
参数 说明 chrps_path 制作后的字符帧图形保存路径(由输出路径+/chrps 获得) video_out 成品视频输出路径 输出路径由后边的子类提供
def chps_to_video(self, chrps_path, video_out): warnings.filterwarnings('ignore') pic_list = os.listdir(chrps_path) imgg = Image.open(op.join(chrps_path, pic_list[0])) size = imgg.size imgg.close() fps = 20 fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') video = cv2.VideoWriter(video_out, fourcc, fps, size) for itm in range(ln:=len(pic_list)): item = op.join(chrps_path, f'{itm+1}.png') img = cv2.imread(item) video.write(img) print(f'\r Loading [{itm+1} of {ln}', end='') video.release()
先写一个基本函数对单张处理
然后再家个壳调用基本程序,实现连续处理多张图像(方便线程多开、但是加了UI后线程出了问题,暂时搁置)这个之前有写过较详细的文章。点这里
def mk_chrimg(self, img):# 单张处理 chrs = '@&$#%QPBMFHjlcvtuoi1+=-' # 字符集 allc = len(chrs) per_span = 256/allc font = ImageFont.truetype(r'c:\windows\fonts\simsun.ttc', self.font_size) img = img.resize((int(img.size[0]*self.up_size), int(img.size[1]*self.up_size))) img = img.convert('L') new_img = Image.new('RGB', img.size, self.bg) draw = ImageDraw.Draw(new_img) for y in range(0, img.size[1], self.font_size): for x in range(0, img.size[0], self.font_size): gray = img.getpixel((x, y)) char = chrs[int(gray//per_span)] draw.text((x, y), char, font=font, fill=self.font_color, direction=None) return new_img
# 多张连续处理 def ims_to_chrp(self, img_list, chrps_path): for img in img_list: name = op.split(img)[-1] out_path = op.join(chrps_path, name) if op.exists(out_path): continue im = Image.open(img) image = self.mk_chrimg(im) image.save(out_path) print(f'\r Pic: {name}, Got!', end='')
对于后边这个壳子(函数)
参数 说明 img_list 待处理源图像的地址列表 chrps_path 处理后字符图像的保存地址 Point 说明 video_out 视频输出路径(在总输出路径下,主要以随机数命名0 被注释掉的线程 由于卡BUG,先搁置 def do_it(self): rawpic_path = op.join(self.outpath, 'raw') chrps_path = op.join(self.outpath, 'chrps') video_out = op.join(self.outpath, f'out_{randint(0, 999)}.mp4') if not op.exists(rawpic_path): os.mkdir(rawpic_path) if not op.exists(chrps_path): os.mkdir(chrps_path) self.pic_split(self.video_path, rawpic_path) ims = os.listdir(rawpic_path) ln = len(ims) img_list = [rawpic_path+f'/{name+1}.png' for name in range(ln)] self.ims_to_chrp(img_list, chrps_path) ''' threads = [] for i in range(3): start = int(i/3)*ln end = int((i+1)//3)*ln if not i-2: end = ln th = threading.Thread(target=self.ims_to_chrp, args=(img_list[start:end], chrps_path)) threads.append(th) for th in threads: th.setDaemon(True) th.start() th.join() ''' self.chps_to_video(chrps_path, video_out)
1. 继承前边两父类
2. 初始化一些制作成品所需的参数
3. 获取输出路径并判断
4. 获取成品制作参数
成品制作参数:
参数 说明 up_size 原图像放大比例(int、float) font_size 字符图中字符的大小(int) bg 制作字符图的背景颜色(str, tuple) chr_color 字符的颜色(str, tuple)
class main_(get_video, mk_chra):
def __init__(self):
self.bg = (255, 255, 255)
self.up_size = 1
self.font_size = 14
self.font_color = 'black'
get_video.__init__(self)
mk_chra.__init__(self)
self.get_video_path()
if isinstance(self.video_path, str):
self.outpath = StringVar
self.root = Tk()
self.root.geometry('600x340')
# 图像放大倍数滚动条
Label(self.root, text='1.选择图像放大倍数[UP_SIZE]', font=16).place(x=13, y=12)
self.up_sizes = Scale(self.root, from_=0, to=8, orient=HORIZONTAL,
resolution=.1, length=560, tickinterval=1.0)
self.up_sizes.place(x=15, y=36)
# 字体大小滚动条
Label(self.root, text='2.选择字体大小[FONT_SIZE]', font=19).place(x=13, y=100)
self.font_sizes = Scale(self.root, from_=0, to=25, orient=HORIZONTAL,
resolution=1, length=560, tickinterval=1)
self.font_sizes.place(x=15, y=130)
# 背景颜色
self.bgb = Button(self.root, text='选择背景颜色', font=15, command=self.get_bg)
self.bgb.place(x=120, y=200)
# 字符颜色
self.fntc = Button(self.root, text='选择字符颜色', font=15, command=self.get_font_color)
self.fntc.place(x=300, y=200)
Label(self.root, text='3.选择输出路径后开使*', font=22, fg='red').place(x=13, y=260)
self.button = Button(self.root,
text='选择输出路径并开始', font=10, fg='green', command=self.get_outpath, )
self.button.place(x=200, y=290)
self.root.mainloop()
def get_bg(self):
self.bg = colorchooser.askcolor()[1]
self.bgb.config(state='disabled')
def get_font_color(self):
self.font_color = colorchooser.askcolor()[1]
self.fntc.config(state='disabled')
def get_outpath(self):
self.outpath = askdirectory()
self.if_ok()
def if_ok(self):
self.outpath = str(self.outpath)
if len(self.outpath):
if not askokcancel('确认', f'是否输出到{self.outpath}'):
self.get_outpath()
else:
self.button.config(state='disabled')
if self.font_sizes.get():
self.font_size = self.font_sizes.get()
if self.up_sizes.get():
self.up_size = self.up_sizes.get()
self.root.destroy()
self.do_it()
#self.root.destroy()
else:
showinfo('!!!', '选择为空')
后续可改进:制作完成后可以自动删除图像数据
完整源码