当前位置:   article > 正文

使用python制作字符视频(蔡徐坤唱跳rap字符视频)_python画蔡徐坤跳舞字符版

python画蔡徐坤跳舞字符版

 我生成了一个蔡徐坤 唱、跳、RAP的字符视频,链接为:

蔡徐坤唱跳RAP字符视频

使用python将一个视频转换为字符视频

详细视频教程,总共8分钟。

用python制作字符视频详细教程(视频版)

文字教程见下文:

首先需要安装python

然后安装所需要的包:cv2、PIL

具体安装方法:

安装cv2

pip install opencv-python

安装PIL

pip install pillow

在安装过程中经常遇到安装时间过长、安装失败等问题。

可以在官网下载对应版本的whl文件,采用本地安装的方法。

opencv-python官方下载地址   

pillow官方下载地址

我的博客下载地址

下载时需要注意自己的电脑是32位还是64位,

需要注意自己电脑上装的python是多少版本的,

选择opencv_python和pillow时,要对应上才行。

此外还需要下载ffmpeg包,用来抽取视频中的声音,以及将声音添加到生成的字符视频中。

如果不配置ffmpeg的话,生成的视频是没有声音的。

下载时同样要注意自己的电脑是32位还是64位。

ffmpeg32位和64位下载地址

下载好ffmpeg包之后还需要配置环境变量。

等一切准备工作就绪之后,就可以运行python代码生成字符视频了,python代码如下。

  1. import argparse
  2. import os
  3. import cv2
  4. import subprocess
  5. from cv2 import VideoWriter_fourcc
  6. from PIL import Image, ImageFont, ImageDraw
  7. class Video2CodeVideo:
  8. def __init__(self):
  9. self.config_dict = {
  10. # 原视频文件
  11. "input_file": "test.mp4",
  12. # 中间文件存放目录
  13. "cache_dir": "cache",
  14. # 是否保留过程文件。True--保留,False--不保留
  15. "save_cache_flag": True,
  16. # 使用使用的字符集
  17. "ascii_char_list": list("01B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. "),
  18. }
  19. # 第一步从函数,将像素转换为字符
  20. # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
  21. def rgb_2_char(self, r, g, b, alpha=256):
  22. if alpha == 0:
  23. return ''
  24. length = len(self.config_dict["ascii_char_list"])
  25. gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
  26. unit = (256.0 + 1) / length
  27. return self.config_dict["ascii_char_list"][int(gray / unit)]
  28. # 第一步从函数,将txt转换为图片
  29. # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
  30. def txt_2_image(self, file_name):
  31. im = Image.open(file_name).convert('RGB')
  32. # gif拆分后的图像,需要转换,否则报错,由于gif分割后保存的是索引颜色
  33. raw_width = im.width
  34. raw_height = im.height
  35. width = int(raw_width / 6)
  36. height = int(raw_height / 15)
  37. im = im.resize((width, height), Image.NEAREST)
  38. txt = ""
  39. colors = []
  40. for i in range(height):
  41. for j in range(width):
  42. pixel = im.getpixel((j, i))
  43. colors.append((pixel[0], pixel[1], pixel[2]))
  44. if (len(pixel) == 4):
  45. txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2], pixel[3])
  46. else:
  47. txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2])
  48. txt += '\n'
  49. colors.append((255, 255, 255))
  50. im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
  51. dr = ImageDraw.Draw(im_txt)
  52. font = ImageFont.load_default().font
  53. x = y = 0
  54. # 获取字体的宽高
  55. font_w, font_h = font.getsize(txt[1])
  56. font_h *= 1.37 # 调整后更佳
  57. # ImageDraw为每个ascii码进行上色
  58. for i in range(len(txt)):
  59. if (txt[i] == '\n'):
  60. x += font_h
  61. y = -font_w
  62. dr.text((y, x), txt[i], fill=colors[i])
  63. y += font_w
  64. name = file_name
  65. im_txt.save(name)
  66. # 第一步,将原视频转成字符图片
  67. # 调用栈:video_2_txt_jpg -> txt_2_image -> rgb_2_char
  68. def video_2_txt_jpg(self, file_name):
  69. vc = cv2.VideoCapture(file_name)
  70. c = 1
  71. if vc.isOpened():
  72. r, frame = vc.read()
  73. if not os.path.exists(self.config_dict["cache_dir"]):
  74. os.mkdir(self.config_dict["cache_dir"])
  75. os.chdir(self.config_dict["cache_dir"])
  76. else:
  77. r = False
  78. while r:
  79. cv2.imwrite(str(c) + '.jpg', frame)
  80. self.txt_2_image(str(c) + '.jpg') # 同时转换为ascii图
  81. r, frame = vc.read()
  82. c += 1
  83. os.chdir('..')
  84. return vc
  85. # 第二步,将字符图片合成新视频
  86. def txt_jpg_2_video(self, outfile_name, fps):
  87. fourcc = VideoWriter_fourcc(*"MJPG")
  88. images = os.listdir(self.config_dict["cache_dir"])
  89. im = Image.open(self.config_dict["cache_dir"] + '/' + images[0])
  90. vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)
  91. os.chdir(self.config_dict["cache_dir"])
  92. for image in range(len(images)):
  93. frame = cv2.imread(str(image + 1) + '.jpg')
  94. vw.write(frame)
  95. os.chdir('..')
  96. vw.release()
  97. # 第三步,从原视频中提取出背景音乐
  98. def video_extract_mp3(self, file_name):
  99. outfile_name = file_name.split('.')[0] + '.mp3'
  100. subprocess.call('ffmpeg -i ' + file_name + ' -f mp3 -y ' + outfile_name, shell=True)
  101. # 第四步,将背景音乐添加到新视频中
  102. def video_add_mp3(self, file_name, mp3_file):
  103. outfile_name = file_name.split('.')[0] + '-txt.mp4'
  104. subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 -y ' + outfile_name, shell=True)
  105. # 第五步,如果没配置保留则清除过程文件
  106. def clean_cache_while_need(self):
  107. # 为了清晰+代码比较短,直接写成内部函数
  108. def remove_cache_dir(path):
  109. if os.path.exists(path):
  110. if os.path.isdir(path):
  111. dirs = os.listdir(path)
  112. for d in dirs:
  113. if os.path.isdir(path + '/' + d):
  114. remove_cache_dir(path + '/' + d)
  115. elif os.path.isfile(path + '/' + d):
  116. os.remove(path + '/' + d)
  117. os.rmdir(path)
  118. return
  119. elif os.path.isfile(path):
  120. os.remove(path)
  121. return
  122. # 为了清晰+代码比较短,直接写成内部函数
  123. def delete_middle_media_file():
  124. os.remove(self.config_dict["input_file"].split('.')[0] + '.mp3')
  125. os.remove(self.config_dict["input_file"].split('.')[0] + '.avi')
  126. # 如果没配置保留则清除过程文件
  127. if not self.config_dict["save_cache_flag"]:
  128. remove_cache_dir(self.config_dict["cache_dir"])
  129. delete_middle_media_file()
  130. # 程序主要逻辑
  131. def main_logic(self):
  132. # 第一步,将原视频转成字符图片
  133. print("第一步,正在将原视频转成字符图片")
  134. vc = self.video_2_txt_jpg(self.config_dict["input_file"])
  135. # 获取原视频帧率
  136. fps = vc.get(cv2.CAP_PROP_FPS)
  137. print("获取原视频帧率:")
  138. print(fps)
  139. vc.release()
  140. print("已将原视频转成字符图片\n")
  141. # 第二步,将字符图片合成新视频
  142. print("第二步,正在将字符图片合成新视频")
  143. self.txt_jpg_2_video(self.config_dict["input_file"].split('.')[0], fps)
  144. print(self.config_dict["input_file"], self.config_dict["input_file"].split('.')[0] + '.mp3')
  145. print("已将字符图片合成新视频\n")
  146. # 第三步,从原视频中提取出背景音乐
  147. print("第三步, 正在从原视频中提取出背景音乐")
  148. self.video_extract_mp3(self.config_dict["input_file"])
  149. print("已从原视频中提取出背景音乐\n")
  150. # 第四步,将背景音乐添加到新视频中
  151. print("第四步, 正在将背景音乐添加到新视频中")
  152. self.video_add_mp3(self.config_dict["input_file"].split('.')[0] + '.avi', self.config_dict["input_file"].split('.')[0] + '.mp3')
  153. print("已将背景音乐添加到新视频中\n")
  154. # 第五步,如果没配置保留则清除过程文件
  155. self.clean_cache_while_need()
  156. print("字符视频制作完毕\n字符视频为test-txt.mp4\n")
  157. print("按任意键结束")
  158. a=input()
  159. if __name__ == '__main__':
  160. obj = Video2CodeVideo()
  161. obj.main_logic()

注意要将源视频和python代码放在一个目录下,将原视频命名为test.mp4,运行结束后,会生成一个test-txt.mp4文件,就是我们想要的字符视频。

有问题欢迎交流

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/205385
推荐阅读
相关标签
  

闽ICP备14008679号