首頁 > 軟體

Python實現視訊分解成圖片+圖片合成視訊

2022-04-02 10:00:50

一、python視訊拆分+圖片合成(原始碼一)

1.python視訊拆分

import cv2
 
def video2frame(videos_path,frames_save_path,time_interval):
 
  '''
  :param videos_path: 視訊的存放路徑
  :param frames_save_path: 視訊切分成幀之後圖片的儲存路徑
  :param time_interval: 儲存間隔
  :return:
  '''
  vidcap = cv2.VideoCapture(videos_path)
  success, image = vidcap.read()
  count = 0
  while success:
    success, image = vidcap.read()
    count += 1
    if count % time_interval == 0:
      cv2.imencode('.jpg', image)[1].tofile(frames_save_path + "/frame%d.jpg" % count)
    # if count == 20:
    #   break
  print(count)
 
if __name__ == '__main__':
   videos_path = r'E:pypython3.7testtest98youhuashipingshipingchaifen1.mp4'
   frames_save_path = r'E:pypython3.7testtest98youhuashipingshipingchaifen'
   time_interval = 2#隔一幀儲存一次
   video2frame(videos_path, frames_save_path, time_interval)

2.python圖片合成

import cv2
import os
import numpy as np
from PIL import Image
 
 
def frame2video(im_dir,video_dir,fps):
 
    im_list = os.listdir(im_dir)
    im_list.sort(key=lambda x: int(x.replace("frame","").split('.')[0]))  #最好再看看圖片順序對不
    img = Image.open(os.path.join(im_dir,im_list[0]))
    img_size = img.size #獲得圖片解析度,im_dir資料夾下的圖片解析度需要一致
 
 
    # fourcc = cv2.cv.CV_FOURCC('M','J','P','G') #opencv版本是2
    fourcc = cv2.VideoWriter_fourcc(*'XVID') #opencv版本是3
    videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
    # count = 1
    for i in im_list:
        im_name = os.path.join(im_dir+i)
        frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1)
        videoWriter.write(frame)
        # count+=1
        # if (count == 200):
        #     print(im_name)
        #     break
    videoWriter.release()
    print('finish')
 
if __name__ == '__main__':
    im_dir = r'E:pypython3.7testtest98youhuashipingshipingchaifenpho/'#幀存放路徑
    video_dir = r'E:pypython3.7testtest98youhuashipingshipingchaifen/test.mp4' #合成視訊存放的路徑
    fps = 30 #影格率,每秒鐘幀數越多,所顯示的動作就會越流暢
    frame2video(im_dir, video_dir, fps)

提示:路徑中不要出現中文和特殊字元,且書寫要規範!!

二、python視訊拆分+圖片合成(原始碼二)

import cv2
import numpy as np
import os
os.chdir(r'E:pypython3.7testtest98youhuashipingchaifen')

##讀取視訊,並逐幀分解成圖片
cap = cv2.VideoCapture('1.mp4')  #開啟一個視訊
isOpened = cap.isOpened() #判斷是否開啟
print(isOpened)

#獲取視訊的相關資訊,視訊的每一幀圖片的寬度都是一致的
fps = cap.get(cv2.CAP_PROP_FPS) #影格率,即每秒鐘由多少張圖片組成
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) #獲取寬度
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) #獲取高度
print(fps,width,height)  #輸出相關資訊

i = 0  
while (isOpened):
    #讀取視訊的前兩秒的影象,共計2*int(fps)張
    if i ==int(fps)*2 :  
        break
    else:
        i = i+1
    (flag,frame) = cap.read() #讀取每一張 flag frame
    filename = 'image'+str(i)+'.jpg'
    #將讀取的圖片寫入檔案中,
    if flag == True:
        cv2.imwrite(filename,frame,[cv2.IMWRITE_JPEG_QUALITY,100])  #確定圖片質量,100算是高的
print('end!')   

##讀取零散圖片(上面分解的圖片),並將其合成視訊
img = cv2.imread('image1.jpg')
imginfo = img.shape
size = (imginfo[1],imginfo[0])  #與預設不同,opencv使用 height在前,width在後,所有需要自己重新排序
print(size)

#建立寫入物件,包括 新建視訊名稱,每秒鐘多少幀圖片(10張) ,size大小
#一般人眼最低解析度為19幀/秒
videoWrite = cv2.VideoWriter('2.mp4',-1,10,size) 

for i in range(1,40):
    filename = 'image'+str(i)+'.jpg'
    img = cv2.imread(filename,1)  #1 表示彩圖,0表示灰度圖  
    
    #直接寫入圖片對應的資料
    videoWrite.write(img)  

videoWrite.release() #關閉寫入物件
print('end')
     

三、python視訊拆分(原始碼三)

import cv2 #匯入opencv模組
import os
import time
 
def video_split(video_path,save_path):
    '''
    對視訊檔切割成幀
    '''
    '''
    @param video_path:視訊路徑
    @param save_path:儲存切分後幀的路徑
    '''
    vc=cv2.VideoCapture(video_path)
    #一幀一幀的分割 需要幾幀寫幾
    c=0
    if vc.isOpened():
        rval,frame=vc.read()
    else:
        rval=False
    while rval:
        rval,frame=vc.read()
        # 每秒提取2幀圖片
        if c % 2 == 0:
            cv2.imwrite(save_path + "/" + str('%06d'%c)+'.jpg',frame)
            cv2.waitKey(1)
        c=c+1
 
DATA_DIR = r"E:pypython3.7testtest98youhuashipingceshimp4" #視訊資料主目錄
 
SAVE_DIR = r"E:pypython3.7testtest98youhuashipingceshipho2" #幀檔案儲存目錄
 
start_time = time.time()
for parents,dirs,filenames in os.walk(DATA_DIR):
    #if parents == DATA_DIR:
    #    continue
 
    print("正在處理資料夾",parents)
    path = parents.replace("\","//")
    f = parents.split("\")[1]
    save_path = SAVE_DIR + "//" + f
    # 對每視訊資料進行遍歷
    for file in filenames:
        file_name = file.split(".")[0]
        save_path_ = save_path + "/" + file_name
        if not os.path.isdir(save_path_):
            os.makedirs(save_path_)
        video_path = path + "/" + file
        video_split(video_path,save_path_)
 
end_time = time.time()
print("Cost time",start_time - end_time)

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


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