先上效果,視訊敬上:

字元舞:

程式碼舞

原始碼:

video_2_code_video.py

  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
8 # 命令列輸入引數處理
9 # aparser = argparse.ArgumentParser()
10 # aparser.add_argument('file')
11 # aparser.add_argument('-o','--output')
12 # aparser.add_argument('-f','--fps',type = float, default = 24)#幀
13 # aparser.add_argument('-s','--save',type = bool, nargs='?', default = False, const = True)
14 # 是否保留Cache檔案,預設不儲存
15
16 class Video2CodeVideo:
17 def __init__(self):
18 self.config_dict = {
19 # 原視訊檔案
20 "input_file": "video/test.mp4",
21 # 中間檔案存放目錄
22 "cache_dir": "cache",
23 # 是否保留過程檔案。True--保留,False--不保留
24 "save_cache_flag": False,
25 # 使用使用的字符集
26 "ascii_char_list": list("01B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. "),
27 }
28
29 # 第一步從函式,將畫素轉換為字元
30 # 呼叫棧:video_2_txt_jpg -> txt_2_image -> rgb_2_char
31 def rgb_2_char(self, r, g, b, alpha=256):
32 if alpha == 0:
33 return ''
34 length = len(self.config_dict["ascii_char_list"])
35 gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
36 unit = (256.0 + 1) / length
37 return self.config_dict["ascii_char_list"][int(gray / unit)]
38
39 # 第一步從函式,將txt轉換為圖片
40 # 呼叫棧:video_2_txt_jpg -> txt_2_image -> rgb_2_char
41 def txt_2_image(self, file_name):
42 im = Image.open(file_name).convert('RGB')
43 # gif拆分後的影象,需要轉換,否則報錯,由於gif分割後儲存的是索引顏色
44 raw_width = im.width
45 raw_height = im.height
46 width = int(raw_width / 6)
47 height = int(raw_height / 15)
48 im = im.resize((width, height), Image.NEAREST)
49
50 txt = ""
51 colors = []
52 for i in range(height):
53 for j in range(width):
54 pixel = im.getpixel((j, i))
55 colors.append((pixel[0], pixel[1], pixel[2]))
56 if (len(pixel) == 4):
57 txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2], pixel[3])
58 else:
59 txt += self.rgb_2_char(pixel[0], pixel[1], pixel[2])
60 txt += '\n'
61 colors.append((255, 255, 255))
62
63 im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
64 dr = ImageDraw.Draw(im_txt)
65 # font = ImageFont.truetype(os.path.join("fonts","漢儀楷體簡.ttf"),18)
66 font = ImageFont.load_default().font
67 x = y = 0
68 # 獲取字型的寬高
69 font_w, font_h = font.getsize(txt[1])
70 font_h *= 1.37 # 調整後更佳
71 # ImageDraw為每個ascii碼進行上色
72 for i in range(len(txt)):
73 if (txt[i] == '\n'):
74 x += font_h
75 y = -font_w
76 # self, xy, text, fill = None, font = None, anchor = None,
77 # *args, ** kwargs
78 dr.text((y, x), txt[i], fill=colors[i])
79 # dr.text((y, x), txt[i], font=font, fill=colors[i])
80 y += font_w
81
82 name = file_name
83 # print(name + ' changed')
84 im_txt.save(name)
85
86
87 # 第一步,將原視訊轉成字元圖片
88 # 呼叫棧:video_2_txt_jpg -> txt_2_image -> rgb_2_char
89 def video_2_txt_jpg(self, file_name):
90 vc = cv2.VideoCapture(file_name)
91 c = 1
92 if vc.isOpened():
93 r, frame = vc.read()
94 if not os.path.exists(self.config_dict["cache_dir"]):
95 os.mkdir(self.config_dict["cache_dir"])
96 os.chdir(self.config_dict["cache_dir"])
97 else:
98 r = False
99 while r:
100 cv2.imwrite(str(c) + '.jpg', frame)
101 self.txt_2_image(str(c) + '.jpg') # 同時轉換為ascii圖
102 r, frame = vc.read()
103 c += 1
104 os.chdir('..')
105 return vc
106
107 # 第二步,將字元圖片合成新視訊
108 def txt_jpg_2_video(self, outfile_name, fps):
109 fourcc = VideoWriter_fourcc(*"MJPG")
110
111 images = os.listdir(self.config_dict["cache_dir"])
112 im = Image.open(self.config_dict["cache_dir"] + '/' + images[0])
113 vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)
114
115 os.chdir(self.config_dict["cache_dir"])
116 for image in range(len(images)):
117 # Image.open(str(image)+'.jpg').convert("RGB").save(str(image)+'.jpg')
118 frame = cv2.imread(str(image + 1) + '.jpg')
119 vw.write(frame)
120 # print(str(image + 1) + '.jpg' + ' finished')
121 os.chdir('..')
122 vw.release()
123
124 # 第三步,從原視訊中提取出背景音樂
125 def video_extract_mp3(self, file_name):
126 outfile_name = file_name.split('.')[0] + '.mp3'
127 subprocess.call('ffmpeg -i ' + file_name + ' -f mp3 -y ' + outfile_name, shell=True)
128
129 # 第四步,將背景音樂新增到新視訊中
130 def video_add_mp3(self, file_name, mp3_file):
131 outfile_name = file_name.split('.')[0] + '-txt.mp4'
132 subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 -y ' + outfile_name, shell=True)
133
134 # 第五步,如果沒配置保留則清除過程檔案
135 def clean_cache_while_need(self):
136 # 為了清晰+程式碼比較短,直接寫成內部函式
137 def remove_cache_dir(path):
138 if os.path.exists(path):
139 if os.path.isdir(path):
140 dirs = os.listdir(path)
141 for d in dirs:
142 if os.path.isdir(path + '/' + d):
143 remove_cache_dir(path + '/' + d)
144 elif os.path.isfile(path + '/' + d):
145 os.remove(path + '/' + d)
146 os.rmdir(path)
147 return
148 elif os.path.isfile(path):
149 os.remove(path)
150 return
151 # 為了清晰+程式碼比較短,直接寫成內部函式
152 def delete_middle_media_file():
153 os.remove(self.config_dict["input_file"].split('.')[0] + '.mp3')
154 os.remove(self.config_dict["input_file"].split('.')[0] + '.avi')
155 # 如果沒配置保留則清除過程檔案
156 if not self.config_dict["save_cache_flag"]:
157 remove_cache_dir(self.config_dict["cache_dir"])
158 delete_middle_media_file()
159
160 # 程式主要邏輯
161 def main_logic(self):
162 # 第一步,將原視訊轉成字元圖片
163 vc = self.video_2_txt_jpg(self.config_dict["input_file"])
164 # 獲取原視訊幀率
165 fps = vc.get(cv2.CAP_PROP_FPS)
166 # print(fps)
167 vc.release()
168 # 第二步,將字元圖片合成新視訊
169 self.txt_jpg_2_video(self.config_dict["input_file"].split('.')[0], fps)
170 print(self.config_dict["input_file"], self.config_dict["input_file"].split('.')[0] + '.mp3')
171 # 第三步,從原視訊中提取出背景音樂
172 self.video_extract_mp3(self.config_dict["input_file"])
173 # 第四步,將背景音樂新增到新視訊中
174 self.video_add_mp3(self.config_dict["input_file"].split('.')[0] + '.avi', self.config_dict["input_file"].split('.')[0] + '.mp3')
175 # 第五步,如果沒配置保留則清除過程檔案
176 self.clean_cache_while_need()
177
178 if __name__ == '__main__':
179 obj = Video2CodeVideo()
180 obj.main_logic()

執行環境:

作業系統:win10
版本:Python 3.8.4
依賴庫:pip install opencv-python pillow
管理員許可權安裝,我的已安裝過,顯示這樣:

依賴應用: ffpmeg(下載直接解壓、將bin目錄加到PATH環境變數)

不下載FFpmeg的話也可執行,但是轉換後的視訊沒有聲音。網上的下載教程比較老了,官網頁面改了。這是我最新下載成功的過程:Windows下載FFmpeg最新版(踩了一上午的坑終於成功)

小白式執行(大佬請裝瞎):

將上面的原始碼命名video_2_code_video.py,在同一目錄下新建資料夾video:

在video中放入要轉換的原視訊,命名test.mp4:

開啟Python3.8

執行video_2_code_video.py,如下圖顯示錶示正在執行:

會產生一些中間檔案諸如:


經過漫長的等待,終於得償所願:

test-txt.mp4就是所要的程式碼舞啦:

下一季:Python之turtle庫畫各種有趣的圖及原始碼(更新中)