Python实现视频分解成图片+图片合成视频
来源:脚本之家    时间:2022-04-02 10:43:36
目录
一、python视频拆分+图片合成(源码一)1.python视频拆分2.python图片合成二、python视频拆分+图片合成(源码二)三、python视频拆分(源码三)

一、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:\py\python3.7\test\test98youhuashiping\shipingchaifen\1.mp4"
   frames_save_path = r"E:\py\python3.7\test\test98youhuashiping\shipingchaifen"
   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:\py\python3.7\test\test98youhuashiping\shipingchaifen\pho/"#帧存放路径
    video_dir = r"E:\py\python3.7\test\test98youhuashiping\shipingchaifen/test.mp4" #合成视频存放的路径
    fps = 30 #帧率,每秒钟帧数越多,所显示的动作就会越流畅
    frame2video(im_dir, video_dir, fps)

提示:路径中不要出现中文和特殊字符,且书写要规范!!

二、python视频拆分+图片合成(源码二)

import cv2
import numpy as np
import os
os.chdir(r"E:\py\python3.7\test\test98youhuashiping\chaifen")

##读取视频,并逐帧分解成图片
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:\py\python3.7\test\test98youhuashiping\ceshi\mp4" #视频数据主目录
 
SAVE_DIR = r"E:\py\python3.7\test\test98youhuashiping\ceshi\pho2" #帧文件保存目录
 
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 视频分解与合成内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

关键词: 合成视频 希望大家 特殊字符 保存路径 重新排序

X 关闭

X 关闭