本文介绍opencv的摄像头和视频读取,保存的操作
import numpy as np
import cv2
cap = cv2.VideoCapture(0) #定义一个cap
while(True):
# Capture frame-by-frame
ret, frame = cap.read() #读取
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #转为灰度图
# Display the resulting frame
cv2.imshow('frame',gray)#显示
if cv2.waitKey(1) & 0xFF == ord('q'): #
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
cap = cv2.VideoCapture(0) 0代表摄像头的编号,如果是读取视频则只需把0改为视频文件的位置路径,注意路径要加双引号“”。
保存视频
首先创建一个 VideoWriter 的对象。确定一个输出文件名称,播放频率和帧的大小。最后一个是 isColor 标签。如果是 True,每一帧就是彩色图,否则就是灰度图。
FourCC 就是一个 4 字节码,用来确定视频的编码格式。可用的编码列表可以从fourcc.org查到。这是平台依赖的。下面这些编码器对我来说是有用个。
• In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 givesvery small size video)
• In Windows: DIVX (More to be tested and added)
• In OSX : (I don’t have access to OSX. Can some one fill this?)
FourCC 码以下面的格式传给程序,以 MJPG 为例:
cv2.cv.FOURCC('M','J','P','G') 或者 cv2.cv.FOURCC(*'MJPG')。
下面的代码是从摄像头中捕获视频,沿水平方向旋转每一帧并保存它。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()