字符視頻
- Pygame 與cv2 制作字符視頻
- 實作功能
- 實作效果截圖
- 需要匯入的庫
- 視頻剪成若干幀
- 對每一幀進行字符替換操作
- 通過pygame實作順序播放
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299768.html
標籤:其他
