python-視頻分幀&多幀合成視頻

 1.視頻分幀

import cv2
vidcap = cv2.VideoCapture('005.avi')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  if cv2.waitKey(10) == 27:                     
      break
  count += 1

 

2.合成視頻

 

import cv2
 
def images_to_video():
    fps = 30  # 幀率
    num_frames = 500
    img_array = []
    img_width = 720
    img_height = 1280
    for i in range(num_frames+1):
        filename = "./frames/"+str(i)+".png"
        img = cv2.imread(filename)
 
        if img is None:
            print(filename + " is non-existent!")
            continue
        img_array.append(img)
 
    out = cv2.VideoWriter('demo.avi', cv2.VideoWriter_fourcc(*'DIVX'), fps,(img_width,img_height))
 
    for i in range(len(img_array)):
        out.write(img_array[i])
    out.release()
 
 
def main():
   
    images_to_video()
 
 
if __name__ == "__main__":
    main()

 

 

3. 另一種寫法

# -*- coding:utf-8 -*-

"""
@author:老艾
@file: create_image.py
@time: 2018/09/25
"""
import numpy as np
import cv2
import os
import sys

def cut(video_file, target_dir):
    '''
    切分所有的文件
    :param all_file: 所有的文件列表
    :param target_dir: 圖片存放文件夾
    :return: 無返回
    '''

    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 = './1.mp4'
    cut(video_file, './target_pic')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章