Opencv之视频处理手册
播放视频(可暂停
图片文件合成视频
学习前言
因为最近老是用到Opencv这个库来处理视频,过程遇到了非常多的细节问题,最后把成品干脆直接放到博客来,这样以后可以随时过来取用。
播放视频(可暂停
#使用cv2读取显示视频
#引入math
import math
#引入opencv
import cv2
#opencv获取本地视频
def play_video(video_path):
cap = cv2.VideoCapture('test.mp4')
#打开文件状态
isopen = cap.isOpened()
if not isopen:
print("Err: Video is failure. Exiting ...")
#视频时长总帧数
total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
#视频帧率
fps = cap.get(cv2.CAP_PROP_FPS)
#播放帧间隔毫秒数
wait = int(1000/fps) if fps else 1
#帧数计数器
read_frame = 0
#循环读取视频帧
while(isopen):
#读取帧图像
ret, frame = cap.read()
#读取错误处理
if not ret:
if read_frame < total_frame:
#读取错误
print("Err: Can't receive frame. Exiting ...")
else:
#正常结束
print("Info: Stream is End")
break
#帧数计数器+1
read_frame = read_frame + 1
print("frame:"+str(read_frame)+"/"+str(total_frame))
#计算当前播放时码
timecode_h = int(read_frame / fps / 60 /60)
timecode_m = int(read_frame / fps / 60)
timecode_s = read_frame / fps % 60
s = math.modf( timecode_s )
timecode_s = int(timecode_s)
timecode_f = int(s[0] * fps)
print("{:0>2d}:{:0>2d}:{:0>2d}.{:0>2d}".format(timecode_h,timecode_m,timecode_s,timecode_f))
#显示帧图像
cv2.imshow('image', frame)
#播放间隔
wk = cv2.waitKey( wait )
#按键值 & 0xFF是一个二进制AND操作 返回一个不是单字节的代码
keycode = wk & 0xff
#空格键暂停
if keycode == ord(" "):
cv2.waitKey(0)
#q键退出
if keycode == ord('q'):
print("Info: By user Cancal ...")
break
#释放实例
cap.release()
#销毁窗口
cv2.destroyAllWindows()
使用步骤:
#使用cv2读取显示视频
#引入math
import math
#引入opencv
import cv2
#opencv获取本地视频
def play_video(video_path):
cap = cv2.VideoCapture('test.mp4')
#打开文件状态
isopen = cap.isOpened()
if not isopen:
print("Err: Video is failure. Exiting ...")
#视频时长总帧数
total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
#视频帧率
fps = cap.get(cv2.CAP_PROP_FPS)
#播放帧间隔毫秒数
wait = int(1000/fps) if fps else 1
#帧数计数器
read_frame = 0
#循环读取视频帧
while(isopen):
#读取帧图像
ret, frame = cap.read()
#读取错误处理
if not ret:
if read_frame < total_frame:
#读取错误
print("Err: Can't receive frame. Exiting ...")
else:
#正常结束
print("Info: Stream is End")
break
#帧数计数器+1
read_frame = read_frame + 1
print("frame:"+str(read_frame)+"/"+str(total_frame))
#计算当前播放时码
timecode_h = int(read_frame / fps / 60 /60)
timecode_m = int(read_frame / fps / 60)
timecode_s = read_frame / fps % 60
s = math.modf( timecode_s )
timecode_s = int(timecode_s)
timecode_f = int(s[0] * fps)
print("{:0>2d}:{:0>2d}:{:0>2d}.{:0>2d}".format(timecode_h,timecode_m,timecode_s,timecode_f))
#显示帧图像
cv2.imshow('image', frame)
#播放间隔
wk = cv2.waitKey( wait )
#按键值 & 0xFF是一个二进制AND操作 返回一个不是单字节的代码
keycode = wk & 0xff
#空格键暂停
if keycode == ord(" "):
cv2.waitKey(0)
#q键退出
if keycode == ord('q'):
print("Info: By user Cancal ...")
break
#释放实例
cap.release()
#销毁窗口
cv2.destroyAllWindows()
play_video(需要播放视频的路径)
图片文件合成视频
# -*- coding: UTF-8 -*-
import os
import cv2
import time
class BatchRename():
def __init__(self, goal_path, goal_label):
self.path = goal_path # 目标图片列表路径
self.label = goal_label
def format_path(self):
self.path = self.path.replace("\", '//')
def rename(self):
fileList = os.listdir(self.path)
# fileList.sort()
total_num = len(fileList)
i = 0
for item in fileList:
endN = "." + item.split('.')[-2]
src = os.path.join(self.path, item)
dst = os.path.join(os.path.abspath(self.path), self.label + str(i) + endN)
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
i += 1
except Exception as e:
print(e)
print("rename dir fallr")
print('total %d to rename & converted %d jpgs' % (total_num, i))
# 图片合成视频
def picvideo(img_path, size):
filelist = os.listdir(img_path) # 获取该目录下的所有文件名
'''
fps:
帧率:1秒钟有n张图片写进去[控制一张图片停留5秒钟,那就是帧率为1,重复播放这张图片5次]
如果文件夹下有50张 534*300的图片,这里设置1秒钟播放5张,那么这个视频的时长就是10秒
'''
fps = 15
video_path = os.path.join('Package\video', img_path.split('\')[-1] + ".avi") # 导出路径
# 可以用(*'DVIX')或(*'X264'),如果都不行先装ffmepg
fourcc = cv2.VideoWriter_fourcc('I','4','2','0') # 不同视频编码对应不同视频格式(例:'I','4','2','0' 对应avi格式)
video = cv2.VideoWriter(video_path, fourcc, fps, size, True)
for i in range(len(filelist)):
item = os.path.join(img_path, str(i)+'.png')
img = cv2.imread(item) # 使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。
video.write(img) # 把图片写进视频
video.release() # 释放
print('video_path:', video_path)
return video_path
def main(img_path):
img_list = os.listdir(img_path)
img = cv2.imread(os.path.join(img_path, img_list[7]))
w, h, _ = img.shape
return picvideo(img_path, (h, w)) # 尺寸要调转,挖槽,坑死他爹地我了
if __name__ == '__main__':
main('PackageOrigrial\tds_nm_01')
使用步骤:
# -*- coding: UTF-8 -*-
import os
import cv2
import time
class BatchRename():
def __init__(self, goal_path, goal_label):
self.path = goal_path # 目标图片列表路径
self.label = goal_label
def format_path(self):
self.path = self.path.replace("\", '//')
def rename(self):
fileList = os.listdir(self.path)
# fileList.sort()
total_num = len(fileList)
i = 0
for item in fileList:
endN = "." + item.split('.')[-2]
src = os.path.join(self.path, item)
dst = os.path.join(os.path.abspath(self.path), self.label + str(i) + endN)
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
i += 1
except Exception as e:
print(e)
print("rename dir fallr")
print('total %d to rename & converted %d jpgs' % (total_num, i))
# 图片合成视频
def picvideo(img_path, size):
filelist = os.listdir(img_path) # 获取该目录下的所有文件名
'''
fps:
帧率:1秒钟有n张图片写进去[控制一张图片停留5秒钟,那就是帧率为1,重复播放这张图片5次]
如果文件夹下有50张 534*300的图片,这里设置1秒钟播放5张,那么这个视频的时长就是10秒
'''
fps = 15
video_path = os.path.join('Package\video', img_path.split('\')[-1] + ".avi") # 导出路径
# 可以用(*'DVIX')或(*'X264'),如果都不行先装ffmepg
fourcc = cv2.VideoWriter_fourcc('I','4','2','0') # 不同视频编码对应不同视频格式(例:'I','4','2','0' 对应avi格式)
video = cv2.VideoWriter(video_path, fourcc, fps, size, True)
for i in range(len(filelist)):
item = os.path.join(img_path, str(i)+'.png')
img = cv2.imread(item) # 使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。
video.write(img) # 把图片写进视频
video.release() # 释放
print('video_path:', video_path)
return video_path
def main(img_path):
img_list = os.listdir(img_path)
img = cv2.imread(os.path.join(img_path, img_list[7]))
w, h, _ = img.shape
return picvideo(img_path, (h, w)) # 尺寸要调转,挖槽,坑死他爹地我了
if __name__ == '__main__':
main('PackageOrigrial\tds_nm_01')
只需在main('存放图片的文件夹路径')中传入参数即可。
暑期编程PK赛 得CSDN机械键盘等精美礼品!


