用摄像头捕获视频
import cv2 as cv
import numpy
cap = cv.VideoCapture(0)
while(cap.isOpened()):ret, frame = cap.read() # read() 它返回两个值,第一个是布尔值,表示是否成功读取到一帧,第二个是帧本身。cv.imshow('Video', frame)if cv.waitKey(25) & 0xFF == ord('q'):cap.release()break
cv.destroyAllWindows()
没有摄像头,我们可以使用一款APPIP摄像头
cap = cv.VideoCapture(0) 0改成IP摄像头内容中的局域网IP
从文件中播放视频
import cv2 as cv
myVC = cv2.VideoCapture('../video.mp4') # 设置窗口宽高 myVC.set(3, 160) myVC.set(4,120)
while True:check, frame = myVC.read()cv2.imshow('Camera', frame)if(cv2.waitKey(1) == ord('q')):myVC.release()break
cv2.destroyAllWindows()
保存视频
import cv2 as cv
import numpy as npmyVC = cv.VideoCapture(0)
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640,480))while(myVC.isOpened()):ret, frame = myVC.read() # 读操作if ret == True:frame = cv.flip(frame, 0) # flip() 用于沿Y轴翻转视频的1图像out.write(frame) # 写操作cv.imshow('Camera', frame) # 展示效果:在哪个窗口,哪一帧图像if cv.waitKey(1) & 0xFF == ord('q'):breakelse:break
myVC.release()
out.release()
cv.destroyAllWindows()