OpenCV制作视频字符画[Python]
import cv2
import os
import time
import platform
show_heigth = 30
show_width = 80
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
#生成一个ascii字符列表
char_len = len(ascii_char)
def readVideo(videoPath):
vc = cv2.VideoCapture(videoPath)
if vc.isOpened():
rval,frame = vc.read()
else:
rval = False
frame_count = 0
ouputList = []
# fource = cv2.VideoWriter_fourcc(*'XVID')
# out = cv2.VideoWriter('c.avi', fource, 20.0, (show_width, show_heigth), False)
while rval:
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray,(show_width,show_heigth))
text = ""
for gr in gray:
for g in gr:
text += ascii_char[int(g / 256 * char_len)]
text+="\t"
# out.write(gray)
ouputList.append(text)
frame_count+=1
if frame_count%100==0:
print("已处理%d帧"%frame_count)
rval,frame = vc.read()
vc.release()
# out.release()
cv2.destroyAllWindows()
with open('c.txt','a+') as fs:
for line in ouputList:
fs.write(line+"\n")
return ouputList
def playL(oList):
ds = ["30","31","32","33","34","35","36","37"]
i = 0
c = ""
for f in oList:
i+=1
if i%60==0:
c = ds[int(i/10%8-1)]
time.sleep(0.016)
t = os.system("clear")
f = f.replace('\t', '\n')
print("\033[1;%sm%s"%(c,f),flush=True)
print()
print()
def playW(oList):
cs = ["01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F"]
i = 0
c = ""
for f in oList:
i+=1
if i%60==0:
a = "color %s"%(cs[int(i / 10 % 15)-1])
os.system(a)
os.system("cls")
time.sleep(0.016)
f = f.replace('\t', '\n')
print(f,flush=True)
print()
print()
if __name__ == '__main__':
videoPath = ".\b.mp4"
ouputLists = []
#获取数据
if os.path.exists("c.txt"):
with open('c.txt','r') as fs:
ouputLists = fs.readlines()
else:
ouputLists = readVideo(videoPath)
#播放
if platform.system()=="Windows":
playW(ouputLists)
else:
playL(ouputLists)
效果展示