Free learning recommendation: python video tutorial
First the effect, here’s the video:
Character dance:
Code dance
Source code:
video_2_code_video.py
import argparseimport osimport cv2import subprocessfrom cv2 import VideoWriter_fourccfrom 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()
Running environment:
Operating system: win10
Version: Python 3.8.4
Dependent library: pip install opencv-python pillow
Installed with administrator rights, mine has been installed, the display is like this:
Dependent application: ffpmeg (download and unzip directly, add the bin directory to the PATH environment variable)
Novice-style operation (big guys, please pretend to be blind):
Name the above source code video_2_code_video.py and create a new file in the same directory Clip video:
Put the original video to be converted in the video and name it test.mp4:
Open Python3.8
Run video_2_code_video.py, as shown below, it is running:
will generate some intermediate files such as:
After a long wait, finally Get what you want:
test-txt.mp4 is the code dance you want:
Lots of free learning recommendations, so please Visit python tutorial(video)
The above is the detailed content of Introducing Python's Douyin Kuaishou character dance. For more information, please follow other related articles on the PHP Chinese website!

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
