目录
win10系统, opencv4.5版本,读取mp4,保存mp4,示例代码,测试ok。
h264格式 依赖openh264-1.8.0-win64.dll
win10系统, opencv4.5版本,读取mp4,保存mp4,示例代码,测试ok。
opencv4.2以上版本,写完图片, 不调用release,
1)调用break,
2)或者release(),
3)或者sys.exit(),
4) if cnt>200:
aaa=1/0
这样会抛异常,
但是以上4种情况保存的mp4都能正常播放;
如果是手动关闭程序,不能播放,
def save_():
cap_1 = cv2.VideoCapture(0)
write_ok = False
sz = (int(cap_1.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap_1.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 25
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
# fourcc = cv2.VideoWriter_fourcc(*'mpeg')
print(sz)
vout_1 = cv2.VideoWriter()
vout_1.open('./output.mp4' ,fourcc ,fps ,sz ,True)
cnt = 0
while(True):
cnt += 1
ret_1, frame_1 = cap_1.read()
print(cnt,frame_1.shape,sz,cv2.__version__)
cv2.imshow("asdf",frame_1)
cv2.waitKey(1)
vout_1.write(frame_1)
if cnt>200:
break
# vout_1.release()
# sys.exit()
以前的ffmpeg必须写尾巴,否则视频无法读取。
import cv2
import sys
import time
def save_():
cap_1 = cv2.VideoCapture(r'weilan2.mp4')
write_ok = False
sz = (int(cap_1.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap_1.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 10
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
# fourcc = cv2.VideoWriter_fourcc(*'mpeg')
print(sz)
vout_1 = cv2.VideoWriter()
vout_1.open('./output.mp4' ,fourcc ,fps ,sz ,True)
cnt = 0
while(cnt < 20):
cnt += 1
print(cnt)
ret_1, frame_1 = cap_1.read()
vout_1.write(frame_1)
# vout_1.release()
# sys.exit()
def play():
dir_path = r'output.mp4'
cap = cv2.VideoCapture(dir_path)
count = 0
while True:
ret, imv = cap.read()
if imv is None:
break
count += 1
print(count)
cv2.imshow("asdf", imv)
cv2.waitKey(1)
if __name__ == '__main__':
play()
# save_()
h264格式 依赖openh264-1.8.0-win64.dll
fourcc = cv2.VideoWriter_fourcc(*'avc1')
opencv以前的版本,需要下载动态库:
openh264-1.8.0-win64.dll
保存代码:
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 不需要openh264-1.8.0-win64.dll
# !/usr/bin/env python
# -*-coding:utf-8-*-
import datetime
import time
import cv2
import os
cam = cv2.VideoCapture(0)
time_now =time.time()
# fourcc = cv2.VideoWriter_fourcc(*'avc1')
os.makedirs('capture', exist_ok=True)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
video_out = None
while True:
ret, frame = cam.read()
if video_out:
video_out.write(frame)
cv2.imshow("asdf", frame)
cv2.waitKey(1)
if video_out is None or time.time() - time_now > 10:
if video_out:
print("save", video_path)
video_out.release()
video_out = None
timestr = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
video_path = 'capture/' +timestr + '.mp4'
video_out = cv2.VideoWriter(video_path, fourcc, 30.0, (640, 480))
time_now = time.time()