Python抖音快手代码舞(字符舞)的实现方法


Posted in Python onFebruary 07, 2021

先上效果,视频敬上:

字符舞:

Python抖音快手代码舞(字符舞)的实现方法

代码舞

源代码:

video_2_code_video.py

import argparse
import os
import cv2
import subprocess
from cv2 import VideoWriter_fourcc
from PIL import Image, ImageFont, ImageDraw

# 命令行输入参数处理
# aparser = argparse.ArgumentParser()
# aparser.add_argument('file')
# aparser.add_argument('-o','--output')
# aparser.add_argument('-f','--fps',type = float, default = 24)#帧
# aparser.add_argument('-s','--save',type = bool, nargs='?', default = False, const = True)
# 是否保留Cache文件,默认不保存

class Video2CodeVideo:
 def __init__(self):
 self.config_dict = {
  # 原视频文件
  "input_file": "video/test.mp4",
  # 中间文件存放目录
  "cache_dir": "cache",
  # 是否保留过程文件。True--保留,False--不保留
  "save_cache_flag": False,
  # 使用使用的字符集
  "ascii_char_list": list("01B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. "),
 }

 # 第一步从函数,将像素转换为字符
 # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
 def rgb_2_char(self, r, g, b, alpha=256):
 if alpha == 0:
  return ''
 length = len(self.config_dict["ascii_char_list"])
 gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
 unit = (256.0 + 1) / length
 return self.config_dict["ascii_char_list"][int(gray / unit)]

 # 第一步从函数,将txt转换为图片
 # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
 def txt_2_image(self, file_name):
 im = Image.open(file_name).convert('RGB')
 # gif拆分后的图像,需要转换,否则报错,由于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 += self.rgb_2_char(pixel[0], pixel[1], pixel[2], pixel[3])
  else:
   txt += self.rgb_2_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 # 调整后更佳
 # 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
  dr.text((y, x), txt[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)


 # 第一步,将原视频转成字符图片
 # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
 def video_2_txt_jpg(self, file_name):
 vc = cv2.VideoCapture(file_name)
 c = 1
 if vc.isOpened():
  r, frame = vc.read()
  if not os.path.exists(self.config_dict["cache_dir"]):
  os.mkdir(self.config_dict["cache_dir"])
  os.chdir(self.config_dict["cache_dir"])
 else:
  r = False
 while r:
  cv2.imwrite(str(c) + '.jpg', frame)
  self.txt_2_image(str(c) + '.jpg') # 同时转换为ascii图
  r, frame = vc.read()
  c += 1
 os.chdir('..')
 return vc

 # 第二步,将字符图片合成新视频
 def txt_jpg_2_video(self, outfile_name, fps):
 fourcc = VideoWriter_fourcc(*"MJPG")

 images = os.listdir(self.config_dict["cache_dir"])
 im = Image.open(self.config_dict["cache_dir"] + '/' + images[0])
 vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)

 os.chdir(self.config_dict["cache_dir"])
 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()

 # 第三步,从原视频中提取出背景音乐
 def video_extract_mp3(self, file_name):
 outfile_name = file_name.split('.')[0] + '.mp3'
 subprocess.call('ffmpeg -i ' + file_name + ' -f mp3 -y ' + outfile_name, shell=True)

 # 第四步,将背景音乐添加到新视频中
 def video_add_mp3(self, file_name, mp3_file):
 outfile_name = file_name.split('.')[0] + '-txt.mp4'
 subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 -y ' + outfile_name, shell=True)

 # 第五步,如果没配置保留则清除过程文件
 def clean_cache_while_need(self):
 # 为了清晰+代码比较短,直接写成内部函数
 def remove_cache_dir(path):
  if os.path.exists(path):
  if os.path.isdir(path):
   dirs = os.listdir(path)
   for d in dirs:
   if os.path.isdir(path + '/' + d):
    remove_cache_dir(path + '/' + d)
   elif os.path.isfile(path + '/' + d):
    os.remove(path + '/' + d)
   os.rmdir(path)
   return
  elif os.path.isfile(path):
   os.remove(path)
  return
 # 为了清晰+代码比较短,直接写成内部函数
 def delete_middle_media_file():
  os.remove(self.config_dict["input_file"].split('.')[0] + '.mp3')
  os.remove(self.config_dict["input_file"].split('.')[0] + '.avi')
 # 如果没配置保留则清除过程文件
 if not self.config_dict["save_cache_flag"]:
  remove_cache_dir(self.config_dict["cache_dir"])
  delete_middle_media_file()

 # 程序主要逻辑
 def main_logic(self):
 # 第一步,将原视频转成字符图片
 vc = self.video_2_txt_jpg(self.config_dict["input_file"])
 # 获取原视频帧率
 fps = vc.get(cv2.CAP_PROP_FPS)
 # print(fps)
 vc.release()
 # 第二步,将字符图片合成新视频
 self.txt_jpg_2_video(self.config_dict["input_file"].split('.')[0], fps)
 print(self.config_dict["input_file"], self.config_dict["input_file"].split('.')[0] + '.mp3')
 # 第三步,从原视频中提取出背景音乐
 self.video_extract_mp3(self.config_dict["input_file"])
 # 第四步,将背景音乐添加到新视频中
 self.video_add_mp3(self.config_dict["input_file"].split('.')[0] + '.avi', self.config_dict["input_file"].split('.')[0] + '.mp3')
 # 第五步,如果没配置保留则清除过程文件
 self.clean_cache_while_need()

if __name__ == '__main__':
 obj = Video2CodeVideo()
 obj.main_logic()

运行环境:

操作系统:win10

版本:Python 3.8.4

依赖库:pip install opencv-python pillow

管理员权限安装,我的已安装过,显示这样:

Python抖音快手代码舞(字符舞)的实现方法

依赖应用: ffpmeg(下载直接解压、将bin目录加到PATH环境变量)

Python抖音快手代码舞(字符舞)的实现方法

小白式运行(大佬请装瞎):

将上面的源代码命名video_2_code_video.py,在同一目录下新建文件夹video:

Python抖音快手代码舞(字符舞)的实现方法

在video中放入要转换的原视频,命名test.mp4:

Python抖音快手代码舞(字符舞)的实现方法

打开Python3.8

Python抖音快手代码舞(字符舞)的实现方法

运行video_2_code_video.py,如下图显示表示正在运行:

Python抖音快手代码舞(字符舞)的实现方法

会产生一些中间文件诸如:

Python抖音快手代码舞(字符舞)的实现方法

Python抖音快手代码舞(字符舞)的实现方法

经过漫长的等待,终于得偿所愿:

Python抖音快手代码舞(字符舞)的实现方法

test-txt.mp4就是所要的代码舞啦:

Python抖音快手代码舞(字符舞)的实现方法

总结 

到此这篇关于Python抖音快手代码舞实现的文章就介绍到这了,更多相关Python抖音快手代码舞内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python和C语言混合编程实例
Jun 04 Python
Python实现将n个点均匀地分布在球面上的方法
Mar 12 Python
使用Python中PDB模块中的命令来调试Python代码的教程
Mar 30 Python
在Python中使用SQLite的简单教程
Apr 29 Python
Python中模块与包有相同名字的处理方法
May 05 Python
python的xpath获取div标签内html内容,实现innerhtml功能的方法
Jan 02 Python
PyQt5实现从主窗口打开子窗口的方法
Jun 19 Python
python高斯分布概率密度函数的使用详解
Jul 10 Python
pytorch实现seq2seq时对loss进行mask的方式
Feb 18 Python
python实现PDF中表格转化为Excel的方法
Jun 16 Python
python中翻译功能translate模块实现方法
Dec 17 Python
Python下opencv库的安装过程及问题汇总
Jun 11 Python
Python图像处理之膨胀与腐蚀的操作
Feb 07 #Python
django inspectdb 操作已有数据库数据的使用步骤
Feb 07 #Python
python数据抓取3种方法总结
Feb 07 #Python
python 批量将中文名转换为拼音
Feb 07 #Python
如何用用Python将地址标记在地图上
Feb 07 #Python
python 三种方法提取pdf中的图片
Feb 07 #Python
Python 转移文件至云对象存储的方法
Feb 07 #Python
You might like
PHP如何抛出异常处理错误
2011/03/02 PHP
jQuery学习笔记之jQuery的事件
2010/12/22 Javascript
JS取文本框中最小值的简单实例
2013/11/29 Javascript
jQuery实现灰蓝风格标准二级下拉菜单效果代码
2015/08/31 Javascript
javascript检查某个元素在数组中的索引值
2016/03/30 Javascript
vue.js实现用户评论、登录、注册、及修改信息功能
2020/05/30 Javascript
JavaScript设计模式之单例模式简单实例教程
2018/07/02 Javascript
vue中promise的使用及异步请求数据的方法
2018/11/08 Javascript
jQuery实现的3D版图片轮播示例【滑动轮播】
2019/01/18 jQuery
JS使用栈判断给定字符串是否是回文算法示例
2019/03/04 Javascript
解决layui 三级联动下拉框更新时回显的问题
2019/09/03 Javascript
node.js开发辅助工具nodemon安装与配置详解
2020/02/06 Javascript
vuex刷新后数据丢失的解决方法
2020/10/18 Javascript
[24:42]VP vs TNC Supermajor小组赛B组 BO3 第三场 6.2
2018/06/03 DOTA
[02:40]2018年度DOTA2最佳新人-完美盛典
2018/12/16 DOTA
Python中Django框架下的staticfiles使用简介
2015/05/30 Python
详解Python爬虫的基本写法
2016/01/08 Python
Python正则表达式教程之三:贪婪/非贪婪特性
2017/03/02 Python
Python中单例模式总结
2018/02/20 Python
Python字典创建 遍历 添加等实用基础操作技巧
2018/09/13 Python
使用PyWeChatSpy自动回复微信拍一拍功能的实现代码
2020/07/02 Python
Python爬虫进阶之爬取某视频并下载的实现
2020/12/08 Python
用python对excel进行操作(读,写,修改)
2020/12/25 Python
在HTML5 canvas里用卷积核进行图像处理的方法
2018/05/02 HTML / CSS
丝芙兰波兰:Sephora.pl
2018/03/25 全球购物
小学师德师风演讲稿
2014/09/02 职场文书
关于国庆节的演讲稿
2014/09/05 职场文书
营销学习心得体会
2014/09/12 职场文书
房屋买卖委托书格式范本格式
2014/10/13 职场文书
2014小学语文教师个人工作总结
2014/12/03 职场文书
早会开场白台词大全
2015/06/01 职场文书
社区志愿服务活动感想
2015/08/07 职场文书
七夕情人节问候语
2015/11/11 职场文书
高三英语教学反思
2016/03/03 职场文书
SpringCloud的JPA连接PostgreSql的教程
2021/06/26 Java/Android
JS轻量级函数式编程实现XDM二
2022/06/16 Javascript