注意1:
cv2.VideoWriter_fourcc(*'MJPG') 对应avi
输出路径'/home/.../zjc.avi'
#! /usr/bin/env python
import cv2
import os
import glob
def imgs2video(imgs_dir): # imgs_dir是图片所在文件夹路径
fps = 24 # 频率
fourcc = cv2.VideoWriter_fourcc(*'MJPG') # 格式
# 下面是视频存储路径
file_path = imgs_dir + 'zjc.avi'
# avi格式亲测可用, mp4也可以但是报错如下:
'''
OpenCV: FFMPEG: tag 0x47504a4d/'MJPG' is not supported with codec id 7 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
'''
video_writer = cv2.VideoWriter(file_path, fourcc, fps, (720, 540)) # 名字, 格式Four-Character Codes, 频率, 大小这里要与图片一致
# no glob, need number-index increasing
imgs = glob.glob(os.path.join(imgs_dir, '*.jpg')) #
# print(imgs) # 列表
'''
['/home/.../00000305.jpg', ..., '/home/.../00000306.jpg']
乱顺的 从00000070.jpg到00000450.jpg
'''
for i in range(len(imgs)):
i = i + 70 # 这里根据个人情况调整, 因为我的图片是从00000070.jpg 到 00000450.jpg 所以+70
imgname = os.path.join(imgs_dir, '{:0>8}.jpg'.format(i)) # >表示右对齐左边填充, :0表示填充0, 8表示8位数
# print(imgname)
'''
/home/hp/zjc/nk_PyCharm/PyCharm_project/nk_DeepSortYolo/deep_sort_yolov3-master/nk_src/bluesheep/00000070.jpg
.
.
.
/home/hp/zjc/nk_PyCharm/PyCharm_project/nk_DeepSortYolo/deep_sort_yolov3-master/nk_src/bluesheep/00000450.jpg
'''
frame = cv2.imread(imgname) # 读取图片-->frame
# 可以选择resize图像大小 frame = cv2.resize(frame, (512, 512), interpolation=cv2.INTER_CUBIC)
video_writer.write(frame) # 视频写入frame
video_writer.release() # 释放video_writer
if __name__ == '__main__':
imgs2video(
'/home/hp/zjc/nk_PyCharm/PyCharm_project/nk_DeepSortYolo/deep_sort_yolov3-master/nk_src/bluesheep/')
#! /usr/bin/env python
import cv2
import os
import glob
def video2imgs(videoPath, savePicturePath): # imgs_dir是图片所在文件夹路径
cap = cv2.VideoCapture(videoPath) # 视频路径
numFrame = 0 # 用于写出图片的命名
numFrame = numFrame + 69 # 从70开始,这根据自己需要调整
while True:
if cap.grab(): # 如果成功获取图片
flag, frame = cap.retrieve()
if not flag:
print('no flag: flag, frame = cap.retrieve()')
continue
else:
# cv2.imshow('video', frame)
numFrame += 1 # 用于写出图片的命名
n = str(numFrame) # 字符化
n = n.zfill(8) # 这样就是八位数, 前面自动补充0
newPath = savePicturePath + n + ".jpg" # 输出图片的具体路径 = 输出图片的文件夹 + 图片名字.jpg
print(n)
cv2.imencode('.jpg', frame)[1].tofile(newPath) # 关于这个[1]暂时没有具体研究, 可以查看相关资料
else:
print('no cap.grab()')
break
if cv2.waitKey(10) == 27:
break
if __name__ == '__main__':
video2imgs(
'/home/hp/zjc/nk_PyCharm/PyCharm_project/nk_DeepSortYolo/deep_sort_yolov3-master/nk_src/bluesheep_2img/zjc.avi',
'/home/hp/zjc/nk_PyCharm/PyCharm_project/nk_DeepSortYolo/deep_sort_yolov3-master/nk_src/bluesheep_2img/')