利用OpenCV打开摄像头进行视频的捕获,并对捕获的视频进行简单的处理
包括边缘化,高斯模糊等
代码语言:javascript复制#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void ImgSmooth(const cv::Mat &image)
{
cv::namedWindow("in",cv::WINDOW_AUTOSIZE);
cv::namedWindow("out",cv::WINDOW_AUTOSIZE);
cv::imshow("in",image);
//读取像素点
int x=16,y=32;
cv::Vec3b intensity=image.at<cv::Vec3b>(y,x);
uchar blue=intensity[0];
uchar green=intensity[1];
uchar red=intensity[2];
std::cout<<(unsigned int)blue
<<(unsigned int)green<<(unsigned int)red<<endl;
cv::Mat img_gry,img_pyr,img_pyr2,img_cny;
cv::cvtColor(image,img_gry,CV_RGB2GRAY);
std::cout<<"gray pixel: "<<(unsigned int)img_gry.at<uchar>(y,x)<<endl;
x/=4;y/=4;
//高斯模糊以及降采样通过以下函数实现
cv::pyrDown(img_gry,img_pyr);
std::cout<<"Pyramid pixel: "<<(unsigned int)img_pyr.at<uchar>(y,x)<<endl;
// cv::pyrDown(img_pyr,img_pyr2);
cv::imshow("img_pyr",img_pyr);
//边缘提取
cv::Canny(img_pyr,img_cny,10,20,3,true);
img_cny.at<uchar>(x,y)=128;
cv::imshow("img_cny",img_cny);
//矩阵
cv::Mat out;
//高斯核的大小必须是奇数,因为高斯卷积会在其覆盖区域的中心输出
cv::GaussianBlur(image,out,cv::Size(3,3),3,3);
cv::GaussianBlur(out,out,cv::Size(3,3),3,3);
cv::imshow("out",out);
}
int main(int argc,char** argv)
{
cv::VideoCapture inputVideo(0);
//设置摄像头分辨率640*480 帧率30fps
inputVideo.set(CV_CAP_PROP_FRAME_HEIGHT, 1080);
inputVideo.set(CV_CAP_PROP_FRAME_WIDTH, 1920);
inputVideo.set(CV_CAP_PROP_FPS, 30.0);
if (!inputVideo.isOpened())
{
cout << "Could not open the input video " << endl;
return -1;
}
Mat frame;
char imgname[100]={0};
int f = 0;
while (1)
{
inputVideo >> frame;
if (frame.empty()) break;
imshow("Camera", frame);
ImgSmooth(frame);
char key = waitKey(1);
if (key == 27)break;
if (key == 'q' || key == 'Q')
{
sprintf(imgname, "./%d.jpg", f);
cv::imwrite(imgname, frame);
}
}
return 0;
}
同时,我们在进行项目测试时候,往往采集视频进行预处理,处理视频代码如下:
代码语言:javascript复制#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <cstring>
int main(int argc,char** argv)
{
//cv::namedWindow("example",cv::WINDOW_AUTOSIZE);
cv::VideoCapture cap;
cap.open(std::string(argv[1]));
cv::Mat frame;
for(;;)
{
cap>>frame;
if(frame.empty())
break;
cv::imshow("in",frame);
//接下来就可以对frame进行处理了
cv::Mat img_gry;
cv::cvtColor(frame,img_gry,CV_RGB2GRAY);
cv::imshow("out",img_gry);
if(cv::waitKey(33)>=0)
break;
}
return 0;
}
对应的CMakeLists.txt如下:
代码语言:javascript复制cmake_minimum_required(VERSION 2.8.3)
project(img)
set(CMAKE_BUILD_TYPE "Release")
set(CMAKE_CXX_FLAGS "-std=c 11")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -Wall -g")
#set(OpenCV_DIR "/home/lyy/Linux_dependence/opencv-4.1.0/build")
find_package(OpenCV REQUIRED)
#add_executable(img imgCatch.cpp)
#add_executable(img imgshow.cpp)
add_executable(img videoshow.cpp)
target_link_libraries(img ${catkin_LIBRARIES} ${OpenCV_LIBS})