最简单python命令行视频转字符(抖音同款)
可自由选择对比度(ascii_char 代表用到的字符,从像素多到少,字符数越多对比度越低)
使用方法:
1. 将代码中’video_3.mp4’替换成你的视频名字
2. 修改ascii_char 调整合适对比度(可选)
3. 修改freq 调整合适频率(可选)
# coding: utf8
import cv2 as cv
import os
import time
freq = 3
# 替换字符列表
# ascii_char = list(r"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# ascii_char = list(r"@&B*LY7x-i\^. ")
ascii_char = list(r"@x. ")
char_len = len(ascii_char)
# 加载视频
cap = cv.VideoCapture('video_3.mp4') # 修改此处设置为你的视频的名字
count = -1
while True:
# 读取视频每一帧
hasFrame, frame = cap.read()
if not hasFrame:
break
count += 1
if count % freq != 0:
continue
# 视频长宽
width = frame.shape[0]
height = frame.shape[1]
b, g, r = cv.split(frame)
frame = cv.merge([r, r, b])
# 转灰度图
img_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# 缩小图片并调整长宽比
img_resize = cv.resize(img_gray, (int(width / 5), int(height / 6)))
text = ''
# 遍历图片中的像素
for row in img_resize:
for pixel in row:
# 根据像素值,选取对应的字符
text += ascii_char[int(pixel / 256 * char_len)]
text += '\n'
# 清屏
os.system('clear') # mac是'clear'
# 输出生成的字符方阵
print(text)
# 适当暂停一下
time.sleep(0.02)