openCV中视频的读入、RGB通道分离以及鼠标左击反馈位置、灰度

来源:互联网 发布:linux vi 修改文件 编辑:程序博客网 时间:2024/06/05 06:04


啥话不说,先上代码:


#include <opencv2/core/core.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>using namespace std;using namespace cv;    void onMouse(int event, int x, int y, int flags, void* param)    {        Mat *im = reinterpret_cast<Mat*>(param);        if(event==CV_EVENT_LBUTTONDOWN)        {                std::cout<<"at("<<x<<","<<y<<")value is:"                    <<static_cast<int>(im->at<uchar>(cv::Point(x,y)))<<std::endl;        }    }int main(int argc, char *argv[]){    VideoCapture capture("1.avi");    if(!capture.isOpened())    {        cout<<"fail to open."<<endl;    }    double rate = capture.get(CV_CAP_PROP_FPS);    bool stop(false);    Mat frame;    char ch;    cout<<"please input the channel you want to see:"<<endl;    cin>>ch;    int delay=1000/rate;    while(!stop)    {        if(!capture.read(frame))            break;        vector<Mat> channels;        Mat dst;        split(frame,channels);        switch(ch)        {            case 'b':            dst=channels[0];            break;            case 'g':            dst=channels[1];            break;            case 'r':            dst=channels[2];            break;        }        namedWindow("Img",CV_WINDOW_AUTOSIZE);        imshow("Img",dst);        cv::setMouseCallback("Img",onMouse,reinterpret_cast<void*>(&frame));            if(waitKey(delay)>=0)            {                stop=true;            }    }    waitKey(0);    return 0;}

代码解释:

VideoCapture capture("1.avi");

读入视频至capture中;

if(!capture.isOpened())    {        cout<<"fail to open."<<endl;    }
利用isOpened( )判断导入视频是否成功;

 double rate = capture.get(CV_CAP_PROP_FPS);
导入该视频帧率,帧率是每秒显示帧数;

 char ch;    cout<<"please input the channel you want to see:"<<endl;    cin>>ch;

输入所需显示通道;

int delay=1000/rate;if(waitKey(delay)>=0)            {                stop=true;            }
首先delay代表的是一帧需要停留多少毫秒,量纲分析:1/(1/s)=s;

该条件语句下,首先执行waitKey( ),意味着停留一帧的时间,然后进行判断,由于当delay>0时无按键按下时waitKey返回-1,此时若有按键按下,则返回该按键ASCII码,则if成立,跳出while循环;

if(!capture.read(frame))            break;

读取视频某一帧并检验是否正确读取;

split(frame,channels);

将该图分为三个通道放入向量channels中;

switch(ch)        {            case 'b':            dst=channels[0];            break;            case 'g':            dst=channels[1];            break;            case 'r':            dst=channels[2];            break;        }        namedWindow("Img",CV_WINDOW_AUTOSIZE);        imshow("Img",dst);

选择需要通道并从channels中获取;

 cv::setMouseCallback("Img",onMouse,reinterpret_cast<void*>(&frame));void onMouse(int event, int x, int y, int flags, void* param)    {        Mat *im = reinterpret_cast<Mat*>(param);        if(event==CV_EVENT_LBUTTONDOWN)        {                std::cout<<"at("<<x<<","<<y<<")value is:"                    <<static_cast<int>(im->at<uchar>(cv::Point(x,y)))<<std::endl;        }    }

实现鼠标点击获取坐标与灰度值,onMouse为定义需要执行的鼠标操作,此处定义为输出x,y及其灰度值。