一、基础的视频读写
从本地读取视频:
capture = cv.VideoCapture("D:/pythonTest/img/flower.mp4")
获取视频的各个参数:
height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
weight = capture.get(cv.CAP_PROP_FRAME_WIDTH)
count = capture.get(cv.CAP_PROP_FRAME_COUNT) #帧数
fps = capture.get(cv.CAP_PROP_FPS) #频率:每秒播放几帧
print(height,weight,count,fps)
视频的播放:
while(True):
ret,frame = capture.read()
if ret is True:
cv.imshow("video_input",frame)
c = cv.waitKey(100)
if c==27:
break
播放的效果:
注意一下:
1.视频帧播放的频率fps,这里显示是30,这与电脑的计算速度相关
2.cv.waitkey(100) 中的100可以调整播放的速度
3.c==27 是指按ESC键退出。
二、通过摄像头来获取视频
capture = cv.VideoCapture(0)
0 代表的是摄像头编号,可以自行查看本机摄像头编号。
效果:
欸,好想加个美颜 ……
这里的视频帧数量是-1。
三、保存视频
将摄像头录制的视频保存到本地:
out = cv.VideoWriter("D:/pythonTest/img/test.mp4",cv.VideoWriter_fourcc('D','I','V','X'),15,(np.int(weight),np.int(height)),True)
这里的VedioWriter_fourcc后的参数代表的是mp4存储格式,其他格式的存储代码可以自行搜索。
下面是完整的获取视频、播放并存储的代码:
def video_io_demo():
#capture = cv.VideoCapture("D:/pythonTest/img/flower.mp4")
capture = cv.VideoCapture(0)
height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
weight = capture.get(cv.CAP_PROP_FRAME_WIDTH)
count = capture.get(cv.CAP_PROP_FRAME_COUNT) #帧数
fps = capture.get(cv.CAP_PROP_FPS) #频率:每秒播放几帧
print(height,weight,count,fps)
out = cv.VideoWriter("D:/pythonTest/img/test.mp4",cv.VideoWriter_fourcc('D','I','V','X'),15,(np.int(weight),np.int(height)),True)
while(True):
ret,frame = capture.read()
if ret is True:
cv.imshow("video_input",frame)
out.write(frame)
c = cv.waitKey(100)
if c==27:
break
于是就得到了生成的新视频:
这里用到的视频编码库是FFMPEG
四、对视频做处理
首先在原代码上添加process_frame函数。这里可以做一个跳帧处理,因为我们的眼睛不用捕获到所有的帧,所以跳帧处理可以减少计算量。
def video_io_demo():
#capture = cv.VideoCapture("D:/pythonTest/img/flower.mp4")
capture = cv.VideoCapture(0)
height = capture.get(cv.CAP_PROP_FRAME_HEIGHT)
weight = capture.get(cv.CAP_PROP_FRAME_WIDTH)
count = capture.get(cv.CAP_PROP_FRAME_COUNT) #帧数
fps = capture.get(cv.CAP_PROP_FPS) #频率:每秒播放几帧
print(height,weight,count,fps)
#out = cv.VideoWriter("D:/pythonTest/img/test.mp4",cv.VideoWriter_fourcc('D','I','V','X'),15,(np.int(weight),np.int(height)),True)
type = 0
while(True):
ret,frame = capture.read()
if ret is True:
cv.imshow("video_input",frame)
result = process_frame(frame,type)
cv.imshow("result",result)
#out.write(frame)
c = cv.waitKey(2)
if c > 0:
type = np.abs(c)%3
if c==27:
break
然后来完善这个process_frame的函数。可以根据自己想要的处理效果进行,就和图像处理的方法一样。
我来尝试两种。
1。做一个视频二值化的处理
def process_frame(frame,type):
if type == 0:
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
#ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
binary = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,25,10)
return binary
else:
return frame
效果如下:
2。再做一个unsharpe的操作,是一个我非常喜欢的效果
def process_frame(frame,type):
if type == 0:
kernel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
im = cv.filter2D(frame,-1,kernel)
aw = cv.addWeighted(im,2,cv.GaussianBlur(frame,(0,0),15),-2,128)
return aw
else:
return frame
看右边视频的这个效果,是不是还挺有趣的,他会给轮廓的边缘做一个提亮。
总之,在process_frame这一部分可以根据自己的需要做一个变换。