python 抖音视频转字符画 GIF

python 抖音视频转字符画 GIF,第1张

两种方法代码demo链接:https://download.csdn.net/download/qq_42789677/85223448

import imageio
import numpy as np
import matplotlib.pyplot as plt
video = imageio.get_reader('D:\SelfFile\Self\Anaconda\other\aa.mp4')
imgs = [np.mean(im,2) for im in video]
plt.imshow(imgs[30])
plt.show()

#将图像宽度缩小至width
from itertools import product #用于循环嵌套
def resizeImg(img,w,h=None):
     m,n = img.shape
     if n<w:
         return img
     if not h:
         h = int(m*w/n)
     im = np.zeros([h,w])
     rw,rh = n/w,m/h #缩放比例
     dw,dh = int(rw),int(rh) #取均值的步长
     for i,j in product(range(h),range(w)):
         I,J = int(i*rh),int(j*rw)
         im[i,j] = np.mean(img[I:I+dh,J:J+dw])
     return im
# 测试一下
 
im = resizeImg(imgs[30],160)
plt.imshow(im)
plt.show()

pixels = "B8&WMZO0QJX@%&jfoavunxr#t/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ^`'. " #用于映射的字符
 
def im2txt(img):
    im = np.floor(img/255*len(pixels)).astype(int)
    txts = ""
    for line in im:
        txts += "".join([pixels[i - 1] for i in line])
        txts += '\r\n'    #像素换行时文本也要换行
    return txts
 
#测试
txt = im2txt(im)
 
plt.figure(figsize=(8,4.5))
plt.rcParams['font.sans-serif'] = 'SIMSUN'  #SIMSUN为宋体
plt.axis([0,10,0,10])
_ = plt.text(5, 5, txt, fontsize=6, linespacing=0.6,ha='center', va='center',wrap=True)
plt.gca().set_axis_off()
plt.savefig('test.png', bbox_inches='tight')
plt.show()


from matplotlib import animation
fig = plt.figure(figsize=(8,4.5))
plt.rcParams['font.sans-serif'] = 'SIMSUN'
ax = fig.add_subplot(xlim=(0,10),ylim=(0,10))
ax.set_axis_off()
 
text = ax.text(5, 5, txt, fontsize=6, linespacing=0.6,  ha='center', va='center',wrap=True)
 
def animate(im):
    text.set_text(im2txt(im))
    return [text]
 
imgs = [resizeImg(im,160) for im in imgs]
 
ani = animation.FuncAnimation(fig, animate, imgs[:200], interval=10, blit=True)
ani.save("16Test.gif", writer='pillow')#保存
plt.show()

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/792715.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存