一、基本
二、转换
2.1 视频播放
import numpy as np
import cv2
cap = cv2.VideoCapture('f:/rain_of_lovesickness.mp4')
while (cap.isOpened()):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(40) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
2.2 视频读取每帧,进行处理操作
import numpy
import cv2
vid = cv2.VideoCapture(video_path)
#vid = cv2.VideoCapture(0)
if not vid.isOpened():
raise IOError("Couldn't open webcam or video")
video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))
video_fps = vid.get(cv2.CAP_PROP_FPS)
video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
while True:
return_value, frame = vid.read()
image = Image.fromarray(frame)
image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
log.info('开始读取图像数据并进行预处理')
2.3 视频提取每帧,保存起来
import cv2
vc = cv2.VideoCapture('视频图片') #读入视频文件
c=0
rval=vc.isOpened()
#timeF = 1 #视频帧计数间隔频率
while rval: #循环读取视频帧
c = c + 1
rval, frame = vc.read()
# if(c%timeF == 0): #每隔timeF帧进行存储操作
# cv2.imwrite('smallVideo/smallVideo'+str(c) + '.jpg', frame) #存储为图像
if rval:
#img为当前目录下新建的文件夹
cv2.imwrite('img/'+str(c) + '.jpg', frame) #存储为图像
cv2.waitKey(1)
else:
break
vc.release()
2.4 照片合并成视频
import os
import cv2
from PIL import Image
def unlock_mv(sp):
""" 将视频转换成图片
sp: 视频路径 """
cap = cv2.VideoCapture(sp)
suc = cap.isOpened() # 是否成功打开
frame_count = 0
while suc:
frame_count += 1
suc, frame = cap.read()
params = []
params.append(2) # params.append(1)
cv2.imwrite('mv\\%d.jpg' % frame_count, frame, params)
cap.release()
print('unlock image: ', frame_count)
def jpg2video(sp, fps):
""" 将图片合成视频. sp: 视频路径,fps: 帧率 """
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
images = os.listdir('mv')
im = Image.open('mv/' + images[0])
vw = cv2.VideoWriter(sp, fourcc, fps, im.size)
os.chdir('mv')
for image in range(len(images)):
# Image.open(str(image)+'.jpg').convert("RGB").save(str(image)+'.jpg')
jpgfile = str(image + 1) + '.jpg'
try:
frame = cv2.imread(jpgfile)
vw.write(frame)
except Exception as exc:
print(jpgfile, exc)
vw.release()
print(sp, 'Synthetic success!')
if __name__ == '__main__':
sp = "智能AI科技机器人.mp4"
sp_new = '智能AI科技机器人_new.avi'
unlock_mv(sp) # 视频转图片
jpg2video(sp_new, 28) # 图片转视频
---------------------
作者:医然
来源:CSDN
原文:https://blog.csdn.net/a649344475/article/details/82943215