本文实例为大家分享了python视频转彩色字符动画的具体代码,供大家参考,具体内容如下
一、效果
原图:
转换后:
效果可通过代码开头几行的参数调节
二、代码
开头几行代码,自己看着调整,把效果调到最佳就ok。
依赖库:
pip install opencv-python
pip install pygame
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
import pygame import cv2 font_size = 18 # 字体大小,可自行调整 win_size = ( 1440 , 1000 ) # 窗口大小,可自行调整 video_size = ( 30 , 30 ) # 视频大小,可自行调整 video_path = './cat.gif' # 视频文件(可以为常见的视频格式和gif) str_text = '假装失智' # 替换字符,可自定义,没有长度限制,但至少得有一个 def video2imgs(video_name, size): img_list = [] cap = cv2.videocapture(video_name) while cap.isopened(): ret, frame = cap.read() if ret: img = cv2.resize(frame, size, interpolation = cv2.inter_area) img_list.append(img) else : break cap.release() return img_list # 初始化pygame def main(): pygame.init() winsur = pygame.display.set_mode(win_size) imgs = video2imgs(video_path, video_size) btnfont = pygame.font.sysfont( "fangsong" , font_size) btnfont.set_bold(true) # 生成surface sur_list = [] for img in imgs: height, width, color = img.shape surface = pygame.surface(win_size) a = 0 x, y = 0 , 0 for row in range (height): x = 0 for col in range (width): # 获取当前像素rgb rgb = img[row][col] rgb[ 0 ], rgb[ 2 ] = rgb[ 2 ], rgb[ 0 ] text_texture = btnfont.render(str_text[a], true, rgb) a = a + 1 a = a % len (str_text) surface.blit(text_texture, (x, y)) x = x + font_size y = y + font_size sur_list.append(surface) # 游戏主循环 current_frame = 0 while true: for event in pygame.event.get(): if event. type = = pygame.quit: exit() pygame.time.delay( int ( 1000 / 24 )) winsur.fill(( 0 , 0 , 0 )) winsur.blit(sur_list[current_frame], [ 0 , 0 ]) current_frame + = 1 current_frame % = len (sur_list) # 刷新界面 pygame.display.flip() if __name__ = = '__main__' : main() |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_39687901/article/details/83347915