OpenCV教程-OpenCV VideoCapture
OpenCV提供了VideoCapture()函数,用于处理摄像头。我们可以执行以下任务:
读取视频、显示视频和保存视频。
从摄像头捕获并显示。
从摄像头捕获视频
OpenCV允许使用摄像头(网络摄像头)捕获实时流的简单界面。它将视频转换为灰度并显示出来。
import cv2import numpy as npcap = cv2.VideoCapture(0)while(True):# Capture image frame-by-frameret, frame = cap.read()# Our operations on the frame come heregray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# Display the resulting framecv2.imshow('frame',gray)if cv2.waitKey(1) & 0xFF == ord('q'):break# When everything done, release the capturecap.release()cv2.destroyAllWindows()
cap.read()返回一个布尔值(True/False)。如果正确读取帧,它将返回True。
👉点击领取:最全Python资料合集
从文件播放视频
import numpy as npimport cv2cap = cv2.VideoCapture('filename')while(cap.isOpened()):ret, frame = cap.read()#it will open the camera in the grayscale modegray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)cv2.imshow('frame',gray)if cv2.waitKey(1) & 0xFF == ord('q'):breakcap.release()cv2.destroyAllWindows()
保存视频
cv2.imwrite()函数用于将视频保存到文件中。首先,我们需要创建一个VideoWriter对象。然后,应该在函数内指定FourCC代码和每秒帧数(fps)。帧大小应该在函数内传递。
import numpy as npimport cv2cap = cv2.VideoCapture(0)# Define the codec and create VideoWriter objectfourcc = 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 frameout.write(frame)cv2.imshow('frame',frame)if cv2.waitKey(1) & 0xFF == ord('q'):breakelse:break# Release everything if job is finishedcap.release()out.release()cv2.destroyAllWindows()
它将保存视频到指定位置。运行上述代码并查看输出。
热门推荐