侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   201

本文实例为大家分享了python如何实现视频转代码视频的具体代码,供大家参考,具体内容如下

# -*- coding:utf-8 -*-#coding:utf-8import argparseimport osimport cv2import subprocessfrom cv2 import VideoWriter, VideoWriter_fourcc, imread, resizefrom 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进行合成

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


  • 上一条:
    python3.6根据m3u8下载mp4视频
    下一条:
    python批量爬取下载抖音视频
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客