這篇文章主要爲大家詳細介紹了python遊戲開發之視頻轉彩色字符動畫,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文實例爲大家分享了python視頻轉彩色字符動畫的具體代碼,供大家參考,具體內容如下
一、效果
原圖:
轉換後:
效果可通過代碼開頭幾行的參數調節
二、代碼
開頭幾行代碼,自己看着調整,把效果調到最佳就ok。
依賴庫:
pip install opencv-python
pip install pygame
代碼:
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()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。