python 做视频后期
- 单个视频转图片
- 所有图片转视频
- 视频压缩 - ffmpeg
- 图片降低分辨率
- 图像处理
这是最近无聊的想法,对视频进行处理,其实也就是对图片的处理。
对视频进行后期处理,思路就是,视频转图片,然后对图片进行处理,再把图片转视频。
图片处理的多么奇怪,视频就多么奇怪,我当时想了想觉得挺好玩就做了玩玩。
视频可能很大,对视频处理要花好长时间,所以还进行了视频压缩等操作。
用到的代码如下。
单个视频转图片
'''
提取单个视频的所有帧
'''
import cv2
import numpy as np
def save_image(image,addr,num):#存储的图片路径address=addr+str(num)+'.jpg'#存储图片cv2.imwrite(address,image)
#读入视频
videoCapture=cv2.VideoCapture("./video/snowman.mp4")
#读取视频帧
success,frame=videoCapture.read()
i=0
while success:i=i+1#保存图片save_image(frame,'./img/',i)if success:print('save image:',i)#读取视频帧sucess,frame=videoCapture.read()
所有图片转视频
import cv2
import os
fps = 29#帧速率
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(filename='./c.mp4', fourcc=fourcc, fps=fps, frameSize=(1080, 1920)) # 图片实际尺寸,不然生成的视频会打不开
for i in range(1,258):p = iif os.path.exists('./img/'+str(p)+'.jpg'): #判断图片是否存在img = cv2.imread(filename='./img/'+str(p)+'.jpg')#cv2.waitKey(100)video_writer.write(img)
video_writer.release()
视频压缩 - ffmpeg
在命令行输入:python ZIP.py ./ c.mp4 c2.mp4
import sys
import os
import zlib
import threading
import platform
from PIL import Image# python press.py ./ 12.mp4 23.mp4
# python 文件名 路径 要压缩的文件 压缩之后的文件名# python ZIP.py ./ c.mp4 c2.mp4
#filePath = "./"
#inputName = "c.mp4"
#outName = "c2.mp4"class Compress_Pic_or_Video(object):def __init__(self,filePath,inputName,outName=""):self.filePath = filePath #文件地址self.inputName = inputName #输入的文件名字self.outName = outName #输出的文件名字self.system_ = platform.platform().split("-",1)[0]if self.system_ == "Windows":self.filePath = (self.filePath + "\\") if self.filePath.rsplit("\\",1)[-1] else self.filePathelif self.system_ == "Linux":self.filePath = (self.filePath + "/") if self.filePath.rsplit("/",1)[-1] else self.filePathself.fileInputPath = self.filePath + inputNameself.fileOutPath = self.filePath + outName@propertydef is_video(self):videoSuffixSet = {"WMV","ASF","ASX","RM","RMVB","MP4","3GP","MOV","M4V","AVI","DAT","MKV","FIV","VOB"}suffix = self.fileInputPath.rsplit(".",1)[-1].upper()if suffix in videoSuffixSet:return Trueelse:return Falsedef SaveVideo(self):fpsize = os.path.getsize(self.fileInputPath) / 1024if fpsize >= 150.0: #大于150KB的视频需要压缩if self.outName:compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath,self.fileOutPath)isRun = os.system(compress)else:compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileInputPath)isRun = os.system(compress)if isRun != 0:return (isRun,"没有安装ffmpeg")return Trueelse:return Truedef Compress_Video(self):# 异步保存打开下面的代码,注释同步保存的代码# thr = threading.Thread(target=self.SaveVideo)# thr.start()#下面为同步代码fpsize = os.path.getsize(self.fileInputPath) / 1024if fpsize >= 150.0: # 大于150KB的视频需要压缩compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileOutPath)isRun = os.system(compress)if isRun != 0:return (isRun, "没有安装ffmpeg")return Trueelse:return Trueif __name__ == "__main__":b = sys.argv[1:] #测试压缩savevideo = Compress_Pic_or_Video(b[0],b[1],b[2])print(savevideo.Compress_Video())
图片降低分辨率
#coding=utf-8
import os #打开文件时需要
from PIL import Image
import reStart_path='C:/Users/jym/PycharmProjects/video2picture/img/'
end_path='C:/Users/jym/PycharmProjects/video2picture/img2/'
new_width=281
new_depth=500
list=os.listdir(Start_path)
#print list
count=0
for pic in list:path=Start_path+picim=Image.open(path)w,h=im.sizeh_new=new_depthw_new=new_widthcount=count+1out = im.resize((w_new,h_new),Image.ANTIALIAS)#new_pic=re.sub(pic[:-4],pic[:-4]+'_new',pic)new_pic=picnew_path=end_path+new_picout.save(new_path)count=str(count)
图像处理
import cv2
import os
import numpy as np
from matplotlib import pyplot as pltdef read_path(file_pathname):#遍历该目录下的所有图片文件for filename in os.listdir(file_pathname):print(filename)img = cv2.imread(file_pathname+'/'+filename)#插入图像处理代码cv2.imwrite('./img3/'+"/"+filename,img)#注意*处如果包含家目录(home)不能写成~符号代替
#必须要写成"/home"的格式,否则会报错说找不到对应的目录
#读取的目录
read_path('./img2/')
#print(os.getcwd())
这里面图像处理代码根据自己需要进行编写,比如下面。
import cv2
import os
import numpy as np
from matplotlib import pyplot as pltdef gasuss_noise(image, mean=0, var=0.001):'''添加高斯噪声mean : 均值var : 方差'''image = np.array(image / 255, dtype=float)noise = np.random.normal(mean, var ** 0.5, image.shape)out = image + noiseif out.min() < 0:low_clip = -1.else:low_clip = 0.out = np.clip(out, low_clip, 1.0)out = np.uint8(out * 255)return outdef read_path(file_pathname):#遍历该目录下的所有图片文件for filename in os.listdir(file_pathname):print(filename)img = cv2.imread(file_pathname+'/'+filename)#out2 = cv2.erode(img,None,iterations=3)hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)# 分别设置HSV颜色空间中,红色、黄色、蓝色、绿色的阈值lower_red = np.array([0, 43, 46])upper_red = np.array([10, 255, 255])lower_yellow = np.array([26, 43, 46])upper_yellow = np.array([34, 255, 255])lower_blue = np.array([100, 43, 46])upper_blue = np.array([124, 255, 255])lower_green = np.array([35, 43, 46])upper_green = np.array([77, 255, 255])# 使用inRange函数获取图像中目标颜色的索引mask_red = cv2.inRange(hsv, lower_red, upper_red)mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)mask_green = cv2.inRange(hsv, lower_green, upper_green)mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)img_mask = np.copy(img)color_1 = [128, 9, 21]color_2 = [50, 14, 77]color_3 = [61, 154, 124]color_4 = [59, 170, 246]# 给目标像素赋值img_mask[mask_red != 0] = color_1img_mask[mask_blue != 0] = color_2img_mask[mask_green != 0] = color_3img_mask[mask_yellow != 0] = color_4#out2 = gasuss_noise(img, mean=0, var=0.01)####change to gray#(下面第一行是将RGB转成单通道灰度图,第二步是将单通道灰度图转成3通道灰度图)#img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#image_np=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)#####save figurecv2.imwrite('./img3/'+"/"+filename,img_mask)#注意*处如果包含家目录(home)不能写成~符号代替
#必须要写成"/home"的格式,否则会报错说找不到对应的目录
#读取的目录
read_path('./img2/')
#print(os.getcwd())