当我们想要使用opencv对视频图像进行处理时,往往第一步便是需要调用电脑摄像头,下面博主将提供两种版本的代码(含详细注释),帮助大家学习如何使用Opencv调用电脑摄像头进行视频录制并保存:
一、C++版本
1. 从相机中读取视频
/*从相机中读取视频*/
#include <opencv2/>
#include <opencv2/>
#include <opencv2/>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
//打开捕获器(0-系统默认摄像头)
VideoCapture cap(0);
Mat frame;
//打开失败
if (!()) {
cerr << "Cannot open camera";
return -1;
}
//打开成功
while (true) {
//读取视频帧
(frame);
//显示图像
imshow("Pig", frame);
//监听键盘,按任意键退出
if (waitKey(5) >= 0)
break;
}
(); //释放捕获器
return 0;
}
2. 从文件中读取视频
/*从文件中读取视频*/
#include <opencv2/>
#include <opencv2/>
#include <opencv2/>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
//视频文件所在路径
String path = "";
//打开捕获器
VideoCapture cap(path);
Mat frame;
//打开失败
if (!()) {
cerr << "Cannot open video";
return -1;
}
//打开成功
while (true) {
//读取视频帧
(frame);
//显示图像
imshow("Pig", frame);
//监听键盘,按任意键退出
if (waitKey(5) >= 0)
break;
}
(); //释放捕获器
return 0;
}
3. 保存视频
/*保存视频*/
#include <opencv2/>
#include <opencv2/>
#include <opencv2/>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
//打开捕获器(0-系统默认摄像头)
VideoCapture cap(0);
Mat frame;
//创建视频写入对象并定义保存格式
VideoWriter videoWriter("", ('X', 'I', 'V', 'D'),25 ,Size(100, 100));
//打开失败
if (!()) {
cerr << "Cannot open camera";
return -1;
}
//打开成功
while(true)
{
//逐帧读取
(frame);
//显示视频画面
imshow("test",frame);
//进行视频保存
(frame);
//监听键盘,按任意键退出
if (waitKey(5) >= 0)
break;
}
(); //释放捕获器
(); //释放视频写入对象
return 0;
}
二、Python版本
1. 从相机中读取视频
'''从相机中读取视频'''
import numpy as np #导入科学计算库numpy
import cv2 as cv #导入opencv-python
#打开捕获器(0-系统默认摄像头)
cap = (0)
#打开失败
if not ():
print("Cannot open camera")
exit()
#打开成功
while True:
#如果正确读取帧,ret为True
ret, frame = ()
#读取失败,则退出循环
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#图像处理-转换为灰度图
gray = (frame, cv.COLOR_BGR2GRAY)
#显示画面
('frame', gray)
#获取键盘按下那个键
key_pressed = (60)
#如果按下esc键,就退出循环
if key_pressed == 27:
break
() #释放捕获器
() #关闭图像窗口
2. 从文件中读取视频
'''从文件中读取视频'''
import numpy as np #导入科学计算库numpy
import cv2 as cv #导入opencv-python
#打开捕获器(''-视频文件所在路径)
cap = ('')
#逐帧处理图像
while ():
#如果正确读取帧,ret为True
ret, frame = ()
#读取失败,则退出循环
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#图像处理-转换为灰度图
gray = (frame, cv.COLOR_BGR2GRAY)
#显示画面
('frame', gray)
#获取键盘按下那个键
key_pressed = (60)
#如果按下esc键,就退出循环
if key_pressed == 27:
break
() #释放捕获器
() #关闭图像窗口
3. 保存视频
'''保存视频'''
import numpy as np #导入科学计算库numpy
import cv2 as cv #导入opencv-python
#打开捕获器(0-系统默认摄像头)
cap = (0)
# 定义编解码器并创建VideoWriter对象
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = ('', fourcc, 20.0, (640, 480)) #视频保存格式
while ():
#如果正确读取帧,ret为True
ret, frame = ()
#读取失败,则退出循环
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#图像处理-翻转图像
frame = (frame, 0)
#保存图像
(frame)
#图像显示
('frame', frame)
#获取键盘按下那个键
key_pressed = (60)
#如果按下esc键,就退出循环
if key_pressed == 27:
break
() #释放捕获器
() #关闭视频保存
() #关闭图像窗口