当前位置: 代码迷 >> 综合 >> 使用Python实现MP4格式视频与图片相互转换
  详细解决方案

使用Python实现MP4格式视频与图片相互转换

热度:29   发布时间:2024-02-26 21:09:55.0

下面代码可以实现MP4格式视频与图片的相互转换,亲测可用!

import cv2
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
import os
from PIL import Imagedef Pic2Video():imgPath = "youimgPath"  # 读取图片路径videoPath = "youvideoPath"  # 保存视频路径images = os.listdir(imgPath)fps = 25  # 每秒25帧数# VideoWriter_fourcc为视频编解码器 ('I', '4', '2', '0') —>(.avi) 、('P', 'I', 'M', 'I')—>(.avi)、('X', 'V', 'I', 'D')—>(.avi)、('T', 'H', 'E', 'O')—>.ogv、('F', 'L', 'V', '1')—>.flv、('m', 'p', '4', 'v')—>.mp4fourcc = VideoWriter_fourcc(*"MJPG")image = Image.open(imgPath + images[0])videoWriter = cv2.VideoWriter(videoPath, fourcc, fps, image.size)for im_name in range(len(images)):frame = cv2.imread(imgPath + images[im_name])  # 这里的路径只能是英文路径# frame = cv2.imdecode(np.fromfile((imgPath + images[im_name]), dtype=np.uint8), 1)  # 此句话的路径可以为中文路径print(im_name)videoWriter.write(frame)print("图片转视频结束!")videoWriter.release()cv2.destroyAllWindows()def Video2Pic():videoPath = "./res.mp4"  # 读取视频路径imgPath = "jpg/"  # 保存图片路径cap = cv2.VideoCapture(videoPath)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))  # 获取高度suc = cap.isOpened()  # 是否成功打开frame_count = 0while suc:frame_count += 1suc, frame = cap.read()#cv2.imwrite(imgPath + str(frame_count).zfill(4), frame)cv2.imwrite(imgPath + "%d.jpg" %frame_count, frame)cv2.waitKey(1)cap.release()print("视频转图片结束!")if __name__ == '__main__':Video2Pic()#Pic2Video()

 

  相关解决方案