日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python视频处理代码_python如何实现视频转代码视频

發布時間:2025/3/11 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python视频处理代码_python如何实现视频转代码视频 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文實例為大家分享了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進行合成

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

總結

以上是生活随笔為你收集整理的python视频处理代码_python如何实现视频转代码视频的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。