2024-09-01
OpenCV
00

python安装opencv:

pip install opencv-python

提取视频帧 视频转图片:

python
import os mp4file = 'input.mp4' savefile = "./output" if not os.path.exists(savefile): os.mkdir(savefile) import cv2 cap = cv2.VideoCapture(mp4file) fourcc = cv2.VideoWriter_fourcc(*'XVID') fps = cap.get(cv2.CAP_PROP_FPS) size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) print(fps) print(size) i = 0 while (cap.isOpened()): i = i + 1 ret, frame = cap.read() if ret == True: cv2.imwrite(savefile + '/' + str(i) + '.jpg', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break print(i) cap.release() cv2.destroyAllWindows()

图片转视频:

python
import os mp4file = 'out.mp4' savefile = "./output" if not os.path.exists(savefile): os.mkdir(savefile) import cv2 fourcc = cv2.VideoWriter_fourcc(*'XVID') fps = 30 size =(720, 1280) videoWriter = cv2.VideoWriter(mp4file, fourcc, fps, size) # 最后一个是保存图片的尺寸 for i in range(1, 1402): frame = cv2.imread(savefile + '/' + str(i) + '.jpg') videoWriter.write(frame) videoWriter.release()

合成,一定得注意尺寸的大小。

python
# coding=utf-8 import os import cv2 from PIL import Image def makevideo(path, fps): """ 将图片合成视频. path: 视频路径,fps: 帧率 """ fourcc = cv2.VideoWriter_fourcc(*"mp4v") path1 = r'D:\yifei111\PycharmProjects\python_test\jigan_res4' im = Image.open(r'D:\yifei111\PycharmProjects\python_test\jigan1\251.jpg') print(im.size) vw = cv2.VideoWriter(path, fourcc, fps, im.size) for i in os.listdir(path1): frame = cv2.imread(path1 + '\\' + i) frame = frame[200:649, :] frame = cv2.resize(frame, im.size) vw.write(frame) if __name__ == '__main__': video_path = r'D:\yifei111\PycharmProjects\python_test\DST_test_new4.mp4' makevideo(video_path, 30) # 图片转视频
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!