您现在的位置是:首页 > 博客日记 > Python Python

使用ffmpeg生成抖音中的像素视频(视频转字符动画)

2018-12-01 09:25:00 【Python】 人已围观

生成抖音中的像素视频(视频转字符动画)

以下还需要需要ffmpeg视频处理工具合成音频 安装ffmpeg |
ffmpeg基本用法

引用类
  1. pip3.7 install numpy opencv-python Pillow

代码实现

  1. # -*- coding:utf-8 -*-
  2. import os, cv2, subprocess, argparse
  3. from PIL import Image, ImageFont, ImageDraw
  4. # pip3.7 install numpy opencv-python Pillow
  5. # 命令行输入参数处理
  6. parser = argparse.ArgumentParser()
  7. parser.add_argument('file')
  8. parser.add_argument('-o', '--output')
  9. parser.add_argument('-f', '--fps', type=float, default=24) # 帧
  10. parser.add_argument('-s', '--save', type=bool, nargs='?', default=False, const=True) # 是否保留Cache文件,默认不保存
  11. # 获取参数
  12. args = parser.parse_args()
  13. INPUT = args.file
  14. OUTPUT = args.output
  15. FPS = args.fps
  16. SAVE = args.save
  17. # 像素对应ascii码
  18. ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")
  19. # ascii_char = list("MNHQ$OC67+>!:-. ")
  20. # ascii_char = list("MNHQ$OC67)oa+>!:+. ")
  21. # 将像素转换为ascii码
  22. def get_char(r, g, b, alpha=256):
  23. if alpha == 0:
  24. return ''
  25. length = len(ascii_char)
  26. gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
  27. unit = (256.0 + 1) / length
  28. return ascii_char[int(gray / unit)]
  29. # 将视频拆分成图片
  30. def videoSplitJpg(file_name):
  31. vc = cv2.VideoCapture(file_name)
  32. c = 1
  33. if vc.isOpened():
  34. r, frame = vc.read()
  35. if not os.path.exists('Cache'):
  36. os.mkdir('Cache')
  37. os.chdir('Cache')
  38. else:
  39. r = False
  40. while r:
  41. cv2.imwrite(str(c) + '.jpg', frame)
  42. # 将txt转换为图片
  43. txtToImage(str(c) + '.jpg')
  44. r, frame = vc.read()
  45. c += 1
  46. os.chdir('..')
  47. return vc
  48. # 将txt转换为图片(换为ascii图)
  49. def txtToImage(file_name):
  50. im = Image.open(file_name).convert('RGB')
  51. # gif拆分后的图像,需要转换,否则报错,由于gif分割后保存的是索引颜色
  52. raw_width = im.width
  53. raw_height = im.height
  54. width = int(raw_width / 6)
  55. height = int(raw_height / 15)
  56. im = im.resize((width, height), Image.NEAREST)
  57. txt = ""
  58. colors = []
  59. for i in range(height):
  60. for j in range(width):
  61. pixel = im.getpixel((j, i))
  62. colors.append((pixel[0], pixel[1], pixel[2]))
  63. if (len(pixel) == 4):
  64. txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
  65. else:
  66. txt += get_char(pixel[0], pixel[1], pixel[2])
  67. txt += '\n'
  68. colors.append((255, 255, 255))
  69. im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
  70. dr = ImageDraw.Draw(im_txt)
  71. # font = ImageFont.truetype(os.path.join("fonts","汉仪楷体简.ttf"),18)
  72. font = ImageFont.load_default().font
  73. x = y = 0
  74. # 获取字体的宽高
  75. font_w, font_h = font.getsize(txt[1]) or (6, 11)
  76. font_h *= 1.37 # 调整后更佳
  77. # ImageDraw为每个ascii码进行上色
  78. for i in range(len(txt)):
  79. if (txt[i] == '\n'):
  80. x += font_h
  81. y = -font_w
  82. dr.text((y, x), txt[i], fill=colors[i])
  83. y += font_w
  84. name = file_name
  85. print(name + ' changed')
  86. im_txt.save(name)
  87. # 将图片合成视频
  88. def jpgToVideo(outfile_name, fps):
  89. fourcc = cv2.VideoWriter_fourcc(*"MJPG")
  90. images = os.listdir('Cache')
  91. im = Image.open('Cache/' + images[0])
  92. vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)
  93. os.chdir('Cache')
  94. for image in range(len(images)):
  95. # Image.open(str(image)+'.jpg').convert("RGB").save(str(image)+'.jpg')
  96. frame = cv2.imread(str(image + 1) + '.jpg')
  97. vw.write(frame)
  98. print(str(image + 1) + '.jpg' + ' finished')
  99. os.chdir('..')
  100. vw.release()
  101. # 调用ffmpeg获取mp3音频文件
  102. def videoGetVoice(file_name, voice_file):
  103. # ffmpeg -i 'file_name' -vn -y -acodec copy 'voice_file' 获取视频中的音频文件
  104. subprocess.call('ffmpeg -i ' + file_name + ' -vn -y -acodec copy ' + voice_file, shell=True)
  105. # 合成音频和视频文件
  106. def video_add_mp3(file_name, voice_file):
  107. outfile_name = file_name.split('.')[0] + '-txt.mp4'
  108. # ffmpeg -i 'file_name' -i 'voice_file' -strict -2 -f mp4 'outfile_name' 合并avi和aac音频生成mp4文件
  109. subprocess.call('ffmpeg -i ' + file_name + ' -i ' + voice_file + ' -strict -2 -f mp4 ' + outfile_name, shell=True)
  110. # 递归删除目录
  111. def remove_dir(path):
  112. if os.path.exists(path):
  113. if os.path.isdir(path):
  114. dirs = os.listdir(path)
  115. for d in dirs:
  116. if os.path.isdir(path + '/' + d):
  117. remove_dir(path + '/' + d)
  118. elif os.path.isfile(path + '/' + d):
  119. os.remove(path + '/' + d)
  120. os.rmdir(path)
  121. return
  122. elif os.path.isfile(path):
  123. os.remove(path)
  124. return
  1. if __name__ == '__main__':
  2. # 将视频拆分成图片
  3. print('--------将视频拆分成图片------------------')
  4. vc = videoSplitJpg(INPUT)
  5. FPS = vc.get(cv2.CAP_PROP_FPS) # 获取帧率
  6. vc.release()
  7. # 将图片合成视频
  8. print('--------将图片合成视频------------------')
  9. jpgToVideo(INPUT.split('.')[0], FPS)
  10. # 音频文件名
  11. voice_file = INPUT.split('.')[0] + '.aac'
  12. # 调用ffmpeg获取mp3音频文件
  13. print('--------调用ffmpeg获取mp3音频文件------------------')
  14. videoGetVoice(INPUT, voice_file)
  15. # 合成音频和视频文件
  16. print('--------合成音频和视频文件------------------')
  17. video_add_mp3(INPUT.split('.')[0] + '.avi', voice_file)
  18. if (not SAVE):
  19. print('--------删除生成的音频视频文件,和cache文件------------------')
  20. remove_dir("Cache")
  21. os.remove(voice_file)
  22. os.remove(INPUT.split('.')[0] + '.avi')
  23. print('--------删除成功------------------')


关注TinyMeng博客,更多精彩分享,敬请期待!
 

很赞哦! ()