字符视频
Pygame 与cv2 制作字符视频
本人小白第一次发表博客文章
实现功能
目前学习模块有限,想着用pygame和cv2这两个比较常用的模块实现字符视频的操作,视频要获取每一帧的帧数,我省略了这一步,通过ps将视频剪成十帧,保存为png图片,这部应该可以通过python实现,目前限于能力有限。
- 视频剪成若干帧
- 对每一帧进行字符替换操作
- 通过pygame实现顺序播放
实现效果截图
需要导入的库
import cv2
import os
import pygame
视频剪成若干帧
博主通过ps实现,有点捞,opencv也可以做,结尾附图片
对每一帧进行字符替换操作
先附源码
all_path = "./images/"
list_path = os.listdir(all_path)
image_text = []
for path in list_path:
image = cv2.imread(all_path + path, cv2.IMREAD_GRAYSCALE)
img_list = []
for row in image:
img_str = ""
for column in row:
if 0 <= column < 20:
img_str += "-"
elif 20 <= column < 40:
img_str += "+"
elif 40 <= column < 60:
img_str += "*"
elif 60 <= column < 80:
img_str += "@"
elif 80 <= column < 100:
img_str += "$"
elif 100 <= column < 120:
img_str += "&"
elif 120 <= column < 140:
img_str += "%"
elif 160 <= column < 180:
img_str += "#"
elif 200 <= column < 220:
img_str += "="
elif 220 <= column < 240:
img_str += "¥"
else:
img_str += "/"
img_list.append(img_str)
image_text.append(img_list)
代码原理很简单,通过os模块遍历存放图片的文件夹获取相对路径,利用image = cv2.imread(all_path + path, cv2.IMREAD_GRAYSCALE)将图像替换成灰度图像,遍历每张图片,通过循环嵌套,隔20单位,将像素替换成字符,每张图片相当于一个一维数组,按行存放,然后存放到image_text数组中
通过pygame实现顺序播放
先附源码
pygame.display.init()
screen = pygame.display.set_mode([1000, 680])
pygame.display.set_caption("文字视频-小黄人")
pygame.font.init()
clock = pygame.time.Clock()
obj_list = []
font = pygame.font.SysFont('kaiti', 3)
for row in image_text:
obj_list_row = []
for column in row:
text = font.render(column, True, (0, 0, 0))
obj_list_row.append(text)
obj_list.append(obj_list_row)
index_image = 0
def get_image():
global index_image
index_image += 1
if index_image < len(obj_list):
return obj_list[index_image]
else:
index_image = 0
return obj_list[index_image]
while True:
clock.tick(10)
screen.fill(pygame.Color(255, 255, 255))
text_list = get_image()
for index, value in enumerate(text_list):
screen.blit(value, (0, index*3))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.display.update()
pygame基本操作不进行介绍,通过嵌套循环将字符转换成pygame字符对象,通过index_image索引循环,实现图片循环
链接:百度网盘 -> 戳
提取码:pupt