python如何实现视频转代码视频


Posted in Python onJune 17, 2019

本文实例为大家分享了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编程的流程图如下: 

python如何实现视频转代码视频

注意事项:

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

  • 这次编程使用到了opencv库,需要安装
  • 帧率的获取可以通过这个函数——FPS = vc.get(cv2.CAP_PROP_FPS)
  • 合成后的视频是没有声音的,我们使用ffmpeg进行合成

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的Django框架中URLconf相关的一些技巧整理
Jul 18 Python
Python代码解决RenderView窗口not found问题
Aug 28 Python
浅谈Python中重载isinstance继承关系的问题
May 04 Python
关于PyTorch 自动求导机制详解
Aug 18 Python
Python面向对象之继承原理与用法案例分析
Dec 31 Python
python环境下安装opencv库的方法
Mar 05 Python
jupyter 实现notebook中显示完整的行和列
Apr 09 Python
JupyterNotebook 输出窗口的显示效果调整方法
Apr 13 Python
python3+selenium获取页面加载的所有静态资源文件链接操作
May 04 Python
基于python SMTP实现自动发送邮件教程解析
Jun 02 Python
keras的ImageDataGenerator和flow()的用法说明
Jul 03 Python
python利用 keyboard 库记录键盘事件
Oct 16 Python
python批量爬取下载抖音视频
Jun 17 #Python
python批量下载抖音视频
Jun 17 #Python
Python基础学习之类与实例基本用法与注意事项详解
Jun 17 #Python
python文本数据处理学习笔记详解
Jun 17 #Python
python3+PyQt5 实现Rich文本的行编辑方法
Jun 17 #Python
Appium+python自动化之连接模拟器并启动淘宝APP(超详解)
Jun 17 #Python
python3+PyQt5 数据库编程--增删改实例
Jun 17 #Python
You might like
php中文件上传的安全问题
2006/10/09 PHP
无数据库的详细域名查询程序PHP版(1)
2006/10/09 PHP
不用mod_rewrite直接用php实现伪静态化页面代码
2008/10/04 PHP
PHP 页面跳转到另一个页面的多种方法方法总结
2009/07/07 PHP
php过滤表单提交的html等危险代码
2014/11/03 PHP
弹出模态框modal的实现方法及实例
2017/09/19 PHP
PHP获取当前时间不准确问题解决方案
2020/08/14 PHP
IE6弹出“已终止操作”的解决办法
2010/11/27 Javascript
js实现键盘操作实现div的移动或改变的原理及代码
2014/06/23 Javascript
escape编码与unescape解码汉字出现乱码的解决方法
2014/07/02 Javascript
jquery分隔Url的param方法(推荐)
2016/05/25 Javascript
bootstrap datetimepicker2.3.11时间插件使用
2016/11/19 Javascript
js面向对象编程总结
2017/02/16 Javascript
JSON 数据格式详解
2017/09/13 Javascript
解决循环中setTimeout执行顺序的问题
2018/06/20 Javascript
使用electron实现百度网盘悬浮窗口功能的示例代码
2018/10/24 Javascript
Vue移动端右滑屏幕返回上一页附源码下载
2019/06/26 Javascript
js删除对象中的某一个字段的方法实现
2021/01/11 Javascript
[01:02:07]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
python实现百度关键词排名查询
2014/03/30 Python
python实现在无须过多援引的情况下创建字典的方法
2014/09/25 Python
Python中类的定义、继承及使用对象实例详解
2015/04/30 Python
Python中内置的日志模块logging用法详解
2016/07/12 Python
5款非常棒的Python工具
2018/01/05 Python
Python socket实现简单聊天室
2018/04/01 Python
Python如何给函数库增加日志功能
2020/08/04 Python
Under Armour安德玛法国官网:美国高端运动科技品牌
2018/06/29 全球购物
计算机网络专业推荐信
2013/11/24 职场文书
建筑经济管理专业求职信分享
2014/01/06 职场文书
《跨越百年的美丽》教学反思
2014/02/11 职场文书
捐款倡议书怎么写
2014/05/13 职场文书
办公室主任竞聘演讲稿
2014/05/15 职场文书
十八大宣传标语
2014/10/09 职场文书
公司开业致辞
2015/07/29 职场文书
田径运动会广播稿
2015/08/19 职场文书
2016应届毕业生就业指导课心得体会
2016/01/15 职场文书