# -*- coding:utf-8 -*-

# coding:utf-8

import os, cv2, subprocess, shutil

from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize

from PIL import Image, ImageFont, ImageDraw

ffmpeg = r'F:\ffmpeg-20190312-d227ed5-win64-static\bin\ffmpeg.exe'

code_color = (169,169,169) # 颜色RGB 默认灰色 ,'' 则彩色

# 像素对应ascii码

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

#ascii_char = ['.',',',':',';','+','*','?','%','S','#','@'][::-1]

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

# ascii_char = list(". ")

# 将像素转换为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

if code_color:

dr.text((y, x), txt[i], fill=code_color) # fill=colors[i]彩色

else:

dr.text((y, x), txt[i], fill=colors[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, 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()

# 调用ffmpeg获取mp3音频文件

def video2mp3(file_name, outfile_name):

cmdstr = " -i {0} -f mp3 {1} -y".format(file_name, outfile_name)

cmd(cmdstr)

# 合成音频和视频文件

def video_add_mp3(file_name, mp3_file,outfile_name):

cmdstr = " -i {0} -i {1} -strict -2 -f mp4 {2} -y".format(file_name, mp3_file, outfile_name)

cmd(cmdstr)

# 视频截取

def vediocut(file_name, outfile_name, start, end):

cmdstr = " -i {0} -vcodec copy -acodec copy -ss {1} -to {2} {3} -y".format(file_name,start,end,outfile_name)

cmd(cmdstr)

# 执行脚本命令

def cmd(cmdstr):

cmdstr = ffmpeg + cmdstr

response = subprocess.call(cmdstr, shell=True, creationflags=0x08000000)

if response == 1:

print("ffmpeg脚本执行失败,请尝试手动执行:{0}".format(cmdstr))

# 主函数

def main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14'):

"""

:param vedio: 原视频文件地址

:param save: 是否保存临时文件 默认不保存

:param iscut: 是否先对原视频做截取处理 默认不截取

:param start: 视频截取开始时间点 仅当iscut=True时有效

:param end: 视频截取结束时间点 仅当iscut=True时有效

:return: 输出目标视频文件 vedio.split('.')[0] + '-code.mp4'

"""

file_cut = vedio.split('.')[0] + '_cut.mp4'

file_mp3 = vedio.split('.')[0] + '.mp3'

file_temp_avi = vedio.split('.')[0] + '_temp.avi'

outfile_name = vedio.split('.')[0] + '-code.mp4'

print("开始生成...")

if iscut:

print("正在截取视频...")

vediocut(vedio, file_cut, start, end)

vedio = file_cut

print("正在转换代码图片...")

vc = video2txt_jpg(vedio) # 视频转图片,图片转代码图片

FPS = vc.get(cv2.CAP_PROP_FPS)  # 获取帧率

vc.release()

print("正在分离音频...")

video2mp3(vedio, file_mp3)  # 从原视频分离出 音频mp3

print("正在转换代码视频...")

jpg2video(file_temp_avi, FPS)  #代码图片转视频

print("正在合成目标视频...")

video_add_mp3(file_temp_avi, file_mp3, outfile_name) # 将音频合成到代码视频

if (not save): # 移除临时文件

print("正在移除临时文件...")

shutil.rmtree("Cache")

for file in [file_cut, file_mp3, file_temp_avi]:

if os.path.exists(file):

os.remove(file)

print("生成成功:{0}".format(outfile_name))

if __name__ == '__main__':

vedio = r"test.mp4"

main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14')

# -*- coding:utf-8 -*-# coding:utf-8import os, cv2, subprocess, shutilfrom cv2 import VideoWriter, VideoWriter_fourcc, imread, resizefrom PIL import Image, ImageFont, ImageDraw
ffmpeg = r'F:\ffmpeg-20190312-d227ed5-win64-static\bin\ffmpeg.exe'code_color = (169,169,169) # 颜色RGB 默认灰色 ,'' 则彩色
# 像素对应ascii码#ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:oa+>!:+. ")#ascii_char = ['.',',',':',';','+','*','?','%','S','#','@'][::-1]#ascii_char = list("MNHQ$OC67+>!:-. ")ascii_char = list(". ")
# 将像素转换为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        if code_color:            dr.text((y, x), txt[i], fill=code_color) # fill=colors[i]彩色        else:            dr.text((y, x), txt[i], fill=colors[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, 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()
# 调用ffmpeg获取mp3音频文件def video2mp3(file_name, outfile_name):    cmdstr = " -i {0} -f mp3 {1} -y".format(file_name, outfile_name)    cmd(cmdstr)
# 合成音频和视频文件def video_add_mp3(file_name, mp3_file,outfile_name):    cmdstr = " -i {0} -i {1} -strict -2 -f mp4 {2} -y".format(file_name, mp3_file, outfile_name)    cmd(cmdstr)
# 视频截取def vediocut(file_name, outfile_name, start, end):    cmdstr = " -i {0} -vcodec copy -acodec copy -ss {1} -to {2} {3} -y".format(file_name,start,end,outfile_name)    cmd(cmdstr)
# 执行脚本命令def cmd(cmdstr):    cmdstr = ffmpeg + cmdstr    response = subprocess.call(cmdstr, shell=True, creationflags=0x08000000)    if response == 1:        print("ffmpeg脚本执行失败,请尝试手动执行:{0}".format(cmdstr))
# 主函数def main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14'):    """    :param vedio: 原视频文件地址    :param save: 是否保存临时文件 默认不保存    :param iscut: 是否先对原视频做截取处理 默认不截取    :param start: 视频截取开始时间点 仅当iscut=True时有效    :param end: 视频截取结束时间点 仅当iscut=True时有效    :return: 输出目标视频文件 vedio.split('.')[0] + '-code.mp4'    """    file_cut = vedio.split('.')[0] + '_cut.mp4'    file_mp3 = vedio.split('.')[0] + '.mp3'    file_temp_avi = vedio.split('.')[0] + '_temp.avi'    outfile_name = vedio.split('.')[0] + '-code.mp4'    print("开始生成...")    if iscut:        print("正在截取视频...")        vediocut(vedio, file_cut, start, end)        vedio = file_cut    print("正在转换代码图片...")    vc = video2txt_jpg(vedio) # 视频转图片,图片转代码图片    FPS = vc.get(cv2.CAP_PROP_FPS)  # 获取帧率    vc.release()    print("正在分离音频...")    video2mp3(vedio, file_mp3)  # 从原视频分离出 音频mp3    print("正在转换代码视频...")    jpg2video(file_temp_avi, FPS)  #代码图片转视频    print("正在合成目标视频...")    video_add_mp3(file_temp_avi, file_mp3, outfile_name) # 将音频合成到代码视频    if (not save): # 移除临时文件        print("正在移除临时文件...")        shutil.rmtree("Cache")        for file in [file_cut, file_mp3, file_temp_avi]:            if os.path.exists(file):                os.remove(file)    print("生成成功:{0}".format(outfile_name))
if __name__ == '__main__':    vedio = r"test.mp4"    main(vedio, save=False, iscut=False, start='00:00:00', end='00:00:14')

python 视频转成代码视频的更多相关文章

  1. 工具---《.264视频 转成 MP4视频》

    <.264视频 转成 MP4视频> 安装了“爱奇艺万能播放器”可以打开.264视频,但是opencv却不能直接读取.264视频,还是需要想办法“.264视频 转成 MP4/avi视频”. ...

  2. [Python] 将视频转成ASCII符号形式、生成GIF图片

    一.简要说明 简述:本文主要展示将视频转成ASCII符号形式展示出来,带音频. 运行环境:Win10/Python3.5. 主要模块: PIL.numpy.shutil. [PIL]: 图像处理 [n ...

  3. Python 批量下载BiliBili视频 打包成软件

    文章目录 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人,我给大家 ...

  4. 《零基础入门学习Python》【第一版】视频课后答案第002讲

    测试题答案: 0. 什么是BIF?BIF 就是 Built-in Functions,内置函数.为了方便程序员快速编写脚本程序(脚本就是要编程速度快快快!!!),Python 提供了非常丰富的内置函数 ...

  5. Python从入门到精通视频(全60集) ☝☝☝

    Python从入门到精通视频(全60集) Python入门到精通 学习 教程 首先,课程的顺序需要调整:一和三主要是介绍学习和布置开发环境的,一介绍的是非VS开发,三介绍的是VS开发.VS2017现在 ...

  6. python采集A站m3u8视频格式视频

    基本开发环境 (https://jq.qq.com/?_wv=1027&k=NofUEYzs) Python 3.6 Pycharm 相关模块的使用 (https://jq.qq.com/?_ ...

  7. 手把手教你用python打造网易公开课视频下载软件1-总述

    写作前面的话:最近准备重温一下算法导论,感谢大网易把MIT算法导论课程全部贴出来,地址为:http://v.163.com/special/opencourse/algorithms.html,在线看 ...

  8. 关于python测试webservice接口的视频分享

    现在大公司非常流行用python做产品的测试框架,还有对于一些快速原型产品的开发也好,很好地支持OO编程,代码易读.Python的更新挺快的,尤其是第三方库. 对于测试人员,代码基础薄弱,用pytho ...

  9. 利用Ffmpeg获得flv视频缩略图和视频时间的代码

    问题描述:获得flv视频的缩略图和视频时间长度 谷歌了半天发现可以使用Ffmpeg获得视频的一些信息,先介绍一下FFMEPG 这里简单说一下:FFmpeg是用于录制.转换和流化音频和视频的完整解决方案 ...

随机推荐

  1. Java静态代码块、构造代码块执行顺序问题

    package com.zxl.staticdemo; public class BlockTest { static { System.out.println("BlockTest静态代码 ...

  2. 【MySQL 读书笔记】普通索引和唯一索引应该怎么选择

    通常我们在做这个选择的时候,考虑得最多的应该是如果我们需要让 Database MySQL 来帮助我们从数据库层面过滤掉对应字段的重复数据我们会选择唯一索引,如果没有前者的需求,一般都会使用普通索引. ...

  3. MAC 的ideal 修改 项目名称

    在使用 ideal的时候 ,我拷贝了一个文件,想要修改项目的名称,改了qcs-regulation-hefei 但是 (1)我改了项目名称: (2)还改了 pom.xml 但是还是不行,来回切换不同的 ...

  4. 转载:原来JavaScript的闭包是这么回事!

    相关阅读:https://www.itcodemonkey.com/article/8565.html

  5. jmeter笔记(7)--参数化--用户定义的变量

    录制的脚本里面有很多的相同的数据的时候,比如服务器ip,端口号等,当更换服务器的时候,就需要手动的修改脚本里面对应的服务器ip和端口号,比较繁琐,jmeter里面有一个用户自定义变量能很好的解决这个问 ...

  6. Quick RF Tips for General Reference

    传送门:http://www.microwavetools.com/rf-tips-to-make-you-look-smart/ 全文搬运过来的,本篇文章并未有其它意义和目的,仅作为个人参考笔记,我 ...

  7. 使用Excel VBA编程将网点的百度坐标转换后标注到高德地图上

    公司网点表存储的坐标是百度坐标,现需要将网点位置标注到高德地图上,研究了一下高德地图的云图数据模版 http://lbs.amap.com/yuntu/reference/cloudstorage和坐 ...

  8. Redis实现排行榜功能(实战)

    需求前段时间,做了一个世界杯竞猜积分排行榜.对世界杯64场球赛胜负平进行猜测,猜对+1分,错误+0分,一人一场只能猜一次.1.展示前一百名列表.2.展示个人排名(如:张三,您当前的排名106579). ...

  9. Exp5 MSF基础应用

    一.实践内容 1.主动攻击实践 [1]MS08-067 MS08-067 漏洞是2008 年年底爆出的一个特大漏洞,存在于当时的所有微软系统,杀伤力超强.其原理是攻击者利用受害主机默认开放的SMB 服 ...

  10. Jmeter工具进行一个完整的接口测试

    Jmeter工具进行一个完整的接口测试 1.创建一个线程组 通俗的讲一个线程组,,可以看做一个虚拟用户组,线程组中的每个线程都可以理解为一个虚拟用户.   2.输入线程组名字 3.添加一个cookie ...