1. 程式人生 > >視訊轉成字元畫播放

視訊轉成字元畫播放

import cv2
import os
import pygame


def get_char(pixel):
    ascii_char = '''[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. '''
    char_len = len(ascii_char)
    return ascii_char[int(pixel / 256 * char_len)]


def get_img(gray_img):
    txt = ""
    for pixel_row in gray_img:
        for pixel in pixel_row:
            txt += get_char(pixel)
        txt += "\n"
    return txt


def read_video(video_path: str, music_path=None):
    cap = cv2.VideoCapture(video_path)
    is_opened = cap.isOpened()
    if music_path is not None:
        pygame.mixer.init()
        pygame.mixer.music.load(music_path)
        pygame.mixer.music.play()
    while is_opened:
        (flag, frame) = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.resize(gray, (160, 80))
        if flag:
            print(get_img(gray))
        else:
            return 
        os.system("cls")


if __name__ == '__main__':
    read_video(r"1.flv", r"C:\Users\Administrator\Desktop\1.mp3")