🎬 视频转字符动画

📋 功能说明
  • 将视频转换为字符画动画
  • 支持实时播放
  • 可调节分辨率
💻 源代码
import cv2
import numpy as np
import time

# 字符集 (从暗到亮)
ascii_char = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. "

def resize(img, new_width):
    """调整图片大小"""
    height, width = img.shape
    ratio = height / width / 2
    new_height = int(new_width * ratio)
    return cv2.resize(img, (new_width, new_height))

def convert_to_char(image):
    """转换为字符"""
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = resize(image, 80)
    
    result = ""
    for row in image:
        for pixel in row:
            index = int(pixel / 256 * len(ascii_char))
            result += ascii_char[min(index, len(ascii_char)-1)]
        result += "\n"
    return result

def video_to_ascii(video_path):
    """视频转字符动画"""
    cap = cv2.VideoCapture(video_path)
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        ascii_frame = convert_to_char(frame)
        print("\033[H\033[J", end="")  # 清屏
        print(ascii_frame)
        cv2.waitKey(30)
    
    cap.release()

# 示例
video_to_ascii("video.mp4")
📦 运行环境
pip install opencv-python numpy
技术原理
  1. OpenCV读取视频帧
  2. 灰度转换
  3. 像素亮度映射到字符
  4. 终端实时显示