一、环境准备

1、需要安装opencv,直接安装 pip install opencv-python

  2、需要安装ffmpeg ,直接解压免安装,下载传送门; 将 ffmpeg.exe 的路径复制,替换代码开头的  ffmpeg = r'G:\ffmpeg\bin\ffmpeg.exe‘

  3、源码参考自 https://blog.csdn.net/kongfu_cat/article/details/79681719?utm_source=copy ,对其修改了一下,并增加了视频截取和颜色选择的功能,亲测可用。

二、源代码

# -*- 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'D:\ffmpeg\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("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
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')

【python3】将视频转换为代码视频的更多相关文章

  1. python 视频转成代码视频

    # -*- coding:utf-8 -*- # coding:utf-8 import os, cv2, subprocess, shutil from cv2 import VideoWriter ...

  2. OpenCV视频读取播放,视频转换为图片

    转载请注明出处!!! http://blog.csdn.net/zhonghuan1992 OpenCV视频读取播放,视频转换为图片 介绍几个有关视频读取的函数: VideoCapture::Vide ...

  3. Python小工具:利用ffmpy3库3秒钟将视频转换为音频

    作者 | pk 哥 来源公众号 | Python知识圈(ID:PythonCircle) 最近,有读者微信上私聊我,想让我写一篇视频批量转换成音频的文章,我答应了,周末宅家里把这个小工具做出来了. 这 ...

  4. 基于 Android 的 3D 视频示例代码

    笔者:Mark Liu 下载样本代码 简单介绍 在Android 中,创建一个可以播放视频剪辑的应用很easy:创建一个採用 3D 图形平面的游戏应用也很easy.可是,创建一个可以在 3D 图形对象 ...

  5. 基于 Android 的 3D 视频样本代码

    作者:Mark Liu 下载样本代码 简单介绍 在Android 中,创建一个可以播放视频剪辑的应用很easy:创建一个採用 3D 图形平面的游戏应用也很easy.可是,创建一个可以在 3D 图形对象 ...

  6. 【转】如何将qlv格式的腾讯视频转换为mp4格式

    一般来说,每个视频网站都会有自己的视频播放格式,如优酷的KUX.爱奇艺的QSV和腾讯的QLV等.但是大家知道,优酷是有转码功能的,而就目前来说腾讯视频还没有转码功能,这就给大家造成了一定的困扰.这里呢 ...

  7. 如何将qlv格式的腾讯视频转换为mp4格式

    一般来说,每个视频网站都会有自己的视频播放格式,如优酷的KUX.爱奇艺的QSV和腾讯的QLV等. 但是大家知道,优酷是有转码功能的,而就目前来说腾讯视频还没有转码功能,下面是将qlv格式的腾讯视频转换 ...

  8. Python3 多线程爬取梨视频

    多线程爬取梨视频 from threading import Thread import requests import re # 访问链接 def access_page(url): respons ...

  9. C#控制台程序取得INSOYA视频区的视频的真实URL,视频标题,发布时间集合。

    准备工作 起因是因为这个网站:http://i.youku.com/kmsfan 这个是一个叫做冒险岛的游戏的资讯论坛,以前我经常在里面传视频,现在我不玩这个游戏了,但是很多玩家还是经常到我的网站里面 ...

随机推荐

  1. PHP匹配当前传入是何种类型

    本文出至:新太潮流网络博客 /** * [is_string_regular_type 正则自动验证传入数据] * @E-mial wuliqiang_aa@163.com * @TIME 2017- ...

  2. html + css + jquery实现简单的进度条实例

    <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta ...

  3. Docker 报错 error during connect: Get pipe/docker_engine: The system cannot find the file specified. - 摘要: 本文讲的是Docker 报错 error during connect: Get pipe/dock

    error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.37/version: open //./pipe/docker_ ...

  4. [翻译] CRPixellatedView-用CIPixellate滤镜动态渲染UIView

    CRPixellatedView-用CIPixellate滤镜动态渲染UIView https://github.com/chroman/CRPixellatedView 本人测试的效果: Usage ...

  5. [翻译] M13BadgeView

    M13BadgeView M13BadgeView is a customizable badge view for iOS applications. The badge is built to b ...

  6. 导出Excel 2007 (NPOI)

    今天在导出Excel2007时报了个错,问是否修复,点yes就提示修复正常了,但具体什么原因没说,如图 之前简单的导出代码是这样写的 public static void ExportToWeb(st ...

  7. September 19th 2017 Week 38th Tuesday

    Live boldly. Push yourself. Don't settle. 勇敢生活,突破自我,永不设限! Don't indulge in the past, whether it was ...

  8. php中查询时间

    在做查询过程中,例如要实现查上个月从第一天到最后一天的佣金(提成),那我们在程序实现过程中就要让程序在上个月的范围内查询,第一天是比较好办,但最后一天就不定,要去写段函数进行月份及年份判断来得出上个月 ...

  9. .split("\n") 和 .strip("我是诗人的感叹")

    s10='''诗人 学者 作家 # 这里面是有换行     "\n"    的,    要想变成一行, 删除strip不行,要用 split分开,这样就能变成一个列表,里面是各个字 ...

  10. 2251. [2010Beijing Wc]外星联络【后缀数组】

    Description 小 P 在看过电影<超时空接触>(Contact)之后被深深的打动,决心致力于寻 找外星人的事业.于是,他每天晚上都爬在屋顶上试图用自己的收音机收听外星 人发来的信 ...