python 視頻和圖片轉換 視頻壓縮 圖片降低分辨率 圖像處理

_jym 2022-01-07 15:03:27 阅读数:414

python 降低 低分辨率 低分 分辨率

這是最近無聊的想法,對視頻進行處理,其實也就是對圖片的處理。

對視頻進行後期處理,思路就是,視頻轉圖片,然後對圖片進行處理,再把圖片轉視頻。

圖片處理的多麼奇怪,視頻就多麼奇怪,我當時想了想覺得挺好玩就做了玩玩。

視頻可能很大,對視頻處理要花好長時間,所以還進行了視頻壓縮等操作。

用到的代碼如下。

單個視頻轉圖片

''' 提取單個視頻的所有幀 '''
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 = i
if 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.filePath
elif self.system_ == "Linux":
self.filePath = (self.filePath + "/") if self.filePath.rsplit("/",1)[-1] else self.filePath
self.fileInputPath = self.filePath + inputName
self.fileOutPath = self.filePath + outName
@property
def 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 True
else:
return False
def SaveVideo(self):
fpsize = os.path.getsize(self.fileInputPath) / 1024
if 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 True
else:
return True
def Compress_Video(self):
# 异步保存打開下面的代碼,注釋同步保存的代碼
# thr = threading.Thread(target=self.SaveVideo)
# thr.start()
#下面為同步代碼
fpsize = os.path.getsize(self.fileInputPath) / 1024
if 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 True
else:
return True
if __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 re
Start_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+pic
im=Image.open(path)
w,h=im.size
h_new=new_depth
w_new=new_width
count=count+1
out = im.resize((w_new,h_new),Image.ANTIALIAS)
#new_pic=re.sub(pic[:-4],pic[:-4]+'_new',pic)
new_pic=pic
new_path=end_path+new_pic
out.save(new_path)
count=str(count)

圖像處理

import cv2
import os
import numpy as np
from matplotlib import pyplot as plt
def 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 plt
def 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 + noise
if out.min() < 0:
low_clip = -1.
else:
low_clip = 0.
out = np.clip(out, low_clip, 1.0)
out = np.uint8(out * 255)
return out
def 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_1
img_mask[mask_blue != 0] = color_2
img_mask[mask_green != 0] = color_3
img_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 figure
cv2.imwrite('./img3/'+"/"+filename,img_mask)
#注意*處如果包含家目錄(home)不能寫成~符號代替
#必須要寫成"/home"的格式,否則會報錯說找不到對應的目錄
#讀取的目錄
read_path('./img2/')
#print(os.getcwd())
版权声明:本文为[_jym]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201071503271608.html