python 视频转代码视频

 

# -*- coding:utf-8 -*-
#coding:utf-8
import argparse
import os
import cv2
import subprocess
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
from PIL import Image, ImageFont, ImageDraw

# 命令行输入参数处理
# aparser = argparse.ArgumentParser()
# aparser.add_argument('file')
# aparser.add_argument('-o','--output')
# aparser.add_argument('-f','--fps',type = float, default = 24)#帧
# aparser.add_argument('-s','--save',type = bool, nargs='?', default = False, const = True)
# 是否保留Cache文件,默认不保存

# 获取参数
# args = parser.parse_args()
# INPUT = args.file
# OUTPUT = args.output
# SAVE = args.save
# FPS = args.fps
# 像素对应ascii码


ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")


# ascii_char = list("MNHQ$OC67+>!:-. ")
# ascii_char = list("MNHQ$OC67)oa+>!:+. ")

# 将像素转换为ascii码
def get_char(r, g, b, alpha=256):
    if alpha == 0:
        return ''
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]


# 将txt转换为图片
def txt2image(file_name):
    im = Image.open(file_name).convert('RGB')
    # gif拆分后的图像,需要转换,否则报错,由于gif分割后保存的是索引颜色
    raw_width = im.width
    raw_height = im.height
    width = int(raw_width / 6)
    height = int(raw_height / 15)
    im = im.resize((width, height), Image.NEAREST)

    txt = ""
    colors = []
    for i in range(height):
        for j in range(width):
            pixel = im.getpixel((j, i))
            colors.append((pixel[0], pixel[1], pixel[2]))
            if (len(pixel) == 4):
                txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
            else:
                txt += get_char(pixel[0], pixel[1], pixel[2])
        txt += '\n'
        colors.append((255, 255, 255))

    im_txt = Image.new("RGB", (raw_width, raw_height), (255, 255, 255))
    dr = ImageDraw.Draw(im_txt)
    # font = ImageFont.truetype(os.path.join("fonts","汉仪楷体简.ttf"),18)
    font = ImageFont.load_default().font
    x = y = 0
    # 获取字体的宽高
    font_w, font_h = font.getsize(txt[1])
    font_h *= 1.37  # 调整后更佳
    # ImageDraw为每个ascii码进行上色
    for i in range(len(txt)):
        if (txt[i] == '\n'):
            x += font_h
            y = -font_w
           # self, xy, text, fill = None, font = None, anchor = None,
            #*args, ** kwargs
        dr.text((y, x), txt[i],  fill=colors[i])
        #dr.text((y, x), txt[i], font=font, fill=colors[i])
        y += font_w

    name = file_name
    #print(name + ' changed')
    im_txt.save(name)


# 将视频拆分成图片
def video2txt_jpg(file_name):
    vc = cv2.VideoCapture(file_name)
    c = 1
    if vc.isOpened():
        r, frame = vc.read()
        if not os.path.exists('Cache'):
            os.mkdir('Cache')
        os.chdir('Cache')
    else:
        r = False
    while r:
        cv2.imwrite(str(c) + '.jpg', frame)
        txt2image(str(c) + '.jpg')  # 同时转换为ascii图
        r, frame = vc.read()
        c += 1
    os.chdir('..')
    return vc


# 将图片合成视频
def jpg2video(outfile_name, fps):
    fourcc = VideoWriter_fourcc(*"MJPG")

    images = os.listdir('Cache')
    im = Image.open('Cache/' + images[0])
    vw = cv2.VideoWriter(outfile_name + '.avi', fourcc, fps, im.size)

    os.chdir('Cache')
    for image in range(len(images)):
        # Image.open(str(image)+'.jpg').convert("RGB").save(str(image)+'.jpg')
        frame = cv2.imread(str(image + 1) + '.jpg')
        vw.write(frame)
        #print(str(image + 1) + '.jpg' + ' finished')
    os.chdir('..')
    vw.release()


# 递归删除目录
def remove_dir(path):
    if os.path.exists(path):
        if os.path.isdir(path):
            dirs = os.listdir(path)
            for d in dirs:
                if os.path.isdir(path + '/' + d):
                    remove_dir(path + '/' + d)
                elif os.path.isfile(path + '/' + d):
                    os.remove(path + '/' + d)
            os.rmdir(path)
            return
        elif os.path.isfile(path):
            os.remove(path)
        return


# 调用ffmpeg获取mp3音频文件
def video2mp3(file_name):
    outfile_name = file_name.split('.')[0] + '.mp3'
    subprocess.call('ffmpeg -i ' + file_name + ' -f mp3 ' + outfile_name, shell=True)


# 合成音频和视频文件
def video_add_mp3(file_name, mp3_file):
    outfile_name = file_name.split('.')[0] + '-txt.mp4'
    subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 ' + outfile_name, shell=True)


if __name__ == '__main__':
    INPUT = r"G:\py\学习python\视频到代码\video39.mp4"
    OUTPUT = r"G:\py\学习python\视频到代码\video39_2.mp4"
    SAVE = r"G:\py\学习python\视频到代码\\video39_3"
    FPS = "24"
    vc = video2txt_jpg(INPUT)
    FPS = vc.get(cv2.CAP_PROP_FPS)  # 获取帧率
    print(FPS)

    vc.release()

    jpg2video(INPUT.split('.')[0], FPS)
    print(INPUT, INPUT.split('.')[0] + '.mp3')
    video2mp3(INPUT)
    video_add_mp3(INPUT.split('.')[0] + '.avi', INPUT.split('.')[0] + '.mp3')

    if (not SAVE):
        remove_dir("Cache")
        os.remove(INPUT.split('.')[0] + '.mp3')
        os.remove(INPUT.split('.')[0] + '.avi')

流程图

这次python编程的流程图如下: 
这里写图片描述




注意事项

在编程的过程中有需要注意的几点:

  • 这次编程使用到了opencv库,需要安装

  • 帧率的获取可以通过这个函数——FPS = vc.get(cv2.CAP_PROP_FPS)

  • 合成后的视频是没有声音的,我们使用ffmpeg进行合成

---------------------------

2021年12月17日17:25:39

非常高兴大家能喜欢这个博客(有手的帮忙下面点个赞再往下看)

但是some body 总是运行不起来。(一个计算机小白某大学生妹子)

我觉得是open cv没有装好

于是乎。我趁着升级python310 把所有环境都清楚了。

叫你们如何装opencv 以及 其他的需要的插件

安装cv2方案1

访问 https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv

 根据我的电脑是w10 python版本310 而且还是64位系统的amd系统。

所以选这个下载
 

下不下来?

复制地址去迅雷下载

安装方法非常的朴素

pip install 刚才下载的whl文件路径

速度非常快啊。一下就安装好了。。因为下载好了。。

安装cv2方案2

pip install opencv-python

继续运行项目。代码放进了main.py

这里仅仅保留

 a.mp4 是一个带声音的英雄联盟的武打片 2分钟52s 文件比较大 元素比较多

需要耐心等下进度

执行代码

哎呀报错了

import cv2 ImportError: numpy.core.multiarray failed to import

 原来是这样。。需要安装numpy

对不住了各位。。之前教程没写好。我有罪。给我点个赞原谅我一下 呜呜呜

pip install numpy

之后代码会执行。这里会生成缓存文件

看缩略图非常的漂亮。由于我的视频比较大。

我准备把他运行完成。然后看下效果 

 在经历了漫长的2594个后

程序不再生成图片了而是生成了

a.avi这个是纯图片不带声音的输出

代码还在执行

请耐心给他点时间

 

 执行完毕后会有a.mp3和a-txt.mp4两个文件

这分别是分离出来的音频文件和合成后的视频文件 

a.txt.mp4是最终输出文件

出现这个才是执行完成

exit code 0

然后

原视频地址:视屏生成代码源文件_哔哩哔哩bilibili

生成视频地址:视频去哪了呢?_哔哩哔哩_bilibili

你可能会觉得视频效果并不是很好。

但是如果换成建议的动漫或者元素比较少的视频

生成的效果是非常棒的。

更新时间 2021年12月17日18:34:02

点个赞兄弟。都看到这里了

#博客地址
https://blog.csdn.net/mp624183768/article/details/81161260
#git地址
https://gitee.com/liuande/python_video_to_code_video
  • 17
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 42
    评论
评论 42
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值