首頁 > 軟體

Python實現視訊分幀的方法分享

2023-03-25 06:01:57

下載依賴

pip install opencv-python==4.0.0.21

實現

方法一

def video_to_frames(video_path, outPutDirName):
    """
    抽取視訊幀存為圖片
    :param video_path:
    :param outPutDirName:
    :return:
    """
    times = 0

    # 提取視訊的頻率,每1幀提取一個
    frame_frequency = 1

    # 如果檔案目錄不存在則建立目錄
    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
        # 按照設定間隔儲存視訊幀
        if times % frame_frequency == 0:
            create_path = os.path.join(outPutDirName, f"{str(times)}.jpg")
            cv2.imwrite(create_path, image)

    logger.info('圖片提取結束')
    # 釋放攝像頭裝置
    camera.release()


def image_to_video(image_path, media_path, fps):
    '''
    圖片合成視訊函數
    :param image_path: 圖片路徑
    :param media_path: 合成視訊儲存路徑
    :return:
    '''
    # 獲取圖片路徑下面的所有圖片名稱
    image_names = os.listdir(image_path)
    # 對提取到的圖片名稱進行排序
    image_names.sort(key=lambda n: int(n[:-4]))
    # 設定寫入格式
    fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
    # 設定每秒幀數
    fps = fps
    # 讀取第一個圖片獲取大小尺寸,因為需要轉換成視訊的圖片大小尺寸是一樣的
    image = Image.open(os.path.join(image_path, image_names[0]))
    # 初始化媒體寫入物件
    media_writer = cv2.VideoWriter(media_path, fourcc, fps, image.size)
    # 遍歷圖片,將每張圖片加入視訊當中
    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  # 判斷是否開啟
    # 為單張視訊,以視訊名稱所謂檔名,建立資料夾
    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):
            # 以下三行 進行 旋轉
            #frame = np.rot90(frame, -1)


            #print(fileName)
            # 設定儲存路徑
            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還可以將幀合成視訊流,下面是實現程式碼

#!/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')

到此這篇關於Python實現視訊分幀的方法分享的文章就介紹到這了,更多相關Python視訊分幀內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com