Python實現(xiàn)視頻分幀的方法分享
更新時間:2023年03月24日 10:35:22 作者:像風(fēng)一樣的男人@
這篇文章主要為大家詳細(xì)介紹了如何通過Python語言實現(xiàn)視頻分幀的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起嘗試一下
下載依賴
pip install opencv-python==4.0.0.21
實現(xiàn)
方法一
def video_to_frames(video_path, outPutDirName):
"""
抽取視頻幀存為圖片
:param video_path:
:param outPutDirName:
:return:
"""
times = 0
# 提取視頻的頻率,每1幀提取一個
frame_frequency = 1
# 如果文件目錄不存在則創(chuàng)建目錄
if not os.path.exists(outPutDirName):
os.makedirs(outPutDirName)
# 讀取視頻幀
camera = cv2.VideoCapture(video_path)
while True:
times = times + 1
res, image = camera.read()
if not res:
print('not res , not image')
break
# 按照設(shè)置間隔存儲視頻幀
if times % frame_frequency == 0:
create_path = os.path.join(outPutDirName, f"{str(times)}.jpg")
cv2.imwrite(create_path, image)
logger.info('圖片提取結(jié)束')
# 釋放攝像頭設(shè)備
camera.release()
def image_to_video(image_path, media_path, fps):
'''
圖片合成視頻函數(shù)
:param image_path: 圖片路徑
:param media_path: 合成視頻保存路徑
:return:
'''
# 獲取圖片路徑下面的所有圖片名稱
image_names = os.listdir(image_path)
# 對提取到的圖片名稱進行排序
image_names.sort(key=lambda n: int(n[:-4]))
# 設(shè)置寫入格式
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
# 設(shè)置每秒幀數(shù)
fps = fps
# 讀取第一個圖片獲取大小尺寸,因為需要轉(zhuǎn)換成視頻的圖片大小尺寸是一樣的
image = Image.open(os.path.join(image_path, image_names[0]))
# 初始化媒體寫入對象
media_writer = cv2.VideoWriter(media_path, fourcc, fps, image.size)
# 遍歷圖片,將每張圖片加入視頻當(dāng)中
for image_name in image_names:
im = cv2.imread(os.path.join(image_path, image_name))
media_writer.write(im)
# 釋放媒體寫入對象
media_writer.release()
logger.info('無聲視頻寫入完成!')
方法二
import numpy as np
import cv2
import os
import sys
def cut(video_file, target_dir):
cap = cv2.VideoCapture(video_file) # 獲取到一個視頻
isOpened = cap.isOpened # 判斷是否打開
# 為單張視頻,以視頻名稱所謂文件名,創(chuàng)建文件夾
temp = os.path.split(video_file)[-1]
dir_name = temp.split('.')[0]
single_pic_store_dir = os.path.join(target_dir, dir_name)
if not os.path.exists(single_pic_store_dir):
os.mkdir(single_pic_store_dir)
i = 0
while isOpened:
i += 1
(flag, frame) = cap.read() # 讀取一張圖像
fileName = 'image' + str(i) + ".jpg"
if (flag == True):
# 以下三行 進行 旋轉(zhuǎn)
#frame = np.rot90(frame, -1)
#print(fileName)
# 設(shè)置保存路徑
save_path = os.path.join(single_pic_store_dir, fileName)
#print(save_path)
res = cv2.imwrite(save_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 70])
#print(res)
else:
break
return single_pic_store_dir
if __name__ == '__main__':
video_file = 'I:/crack.avi'
cut(video_file, 'I:/data/')
方法三
#!/usr/bin/env python
import cv2
numer = 18
cap=cv2.VideoCapture("/home/linux/work/python/video/"+str(numer)+".mp4")
if cap.isOpened():
ret,frame=cap.read()
else:
ret = False
n=0
i=0
timeF = 40
path='/home/linux/work/python/video/'+str(numer)+'/{}'
while ret:
n = n + 1
ret,frame=cap.read()
if (n%timeF == 0) :
i = i+1
print(i)
filename=str(numer)+"_"+str(i)+".jpg"
cv2.imwrite(path.format(filename),frame)
cv2.waitKey(1)
cap.release()
補充
除了視頻分幀,Python還可以將幀合成視頻流,下面是實現(xiàn)代碼
#!/usr/bin/env python
import cv2
img = cv2.imread('/home/linux/work/python/img/1_475.jpg')
imginfo = img.shape
size = (imginfo[1],imginfo[0])
print(size)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
videoWrite = cv2.VideoWriter('/home/linux/work/python/2.mp4',fourcc,10,size)
for i in range(475,2208):
filename = '/home/linux/work/python/img/1_'+str(i)+'.jpg'
img = cv2.imread(filename,1)
videoWrite.write(img)
print(i)
videoWrite.release()
print('end')
到此這篇關(guān)于Python實現(xiàn)視頻分幀的方法分享的文章就介紹到這了,更多相關(guān)Python視頻分幀內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?Serial串口的簡單數(shù)據(jù)收發(fā)方式
這篇文章主要介紹了Python?Serial串口的簡單數(shù)據(jù)收發(fā)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
一文帶你深入理解Python的`functools.lru_cache`裝飾器
Python中的functools.lru_cache裝飾器是一個非常有用的裝飾器,它可以幫助我們優(yōu)化遞歸函數(shù),避免重復(fù)計算已經(jīng)計算過的值,在這篇文章中,我們將探討?functools.lru_cache?的工作原理以及如何使用它,感興趣的朋友跟著小編一起來學(xué)習(xí)吧2023-07-07

