opencv 截图并保存

代码功能:选择图像中矩形区,按S键截图并保存,Q键退出。

#include<opencv2/opencv.hpp>  
#include<iostream>  

using namespace std;
using namespace cv;

Rect select;
bool select_flag = false;
Mat img, showImg;

void S_on_Mouse(int event, int x, int y, int flags, void*param)//画矩形框并截图  
{
    Point p1, p2;
    switch (event)
    {
        case  EVENT_LBUTTONDOWN:
        {
           select.x = x;
           select.y = y;
           select_flag = true;
        }
        break;
        case EVENT_MOUSEMOVE:
        {
            if (select_flag)
            {
                img.copyTo(showImg);
                p1 = Point(select.x, select.y);
                p2 = Point(x, y);
                rectangle(showImg, p1, p2, Scalar(0, 255, 0), 2);
                imshow("img", showImg);
            }
        }
        break;
        case EVENT_LBUTTONUP:
        {
            //显示框出的ROI   
            Rect roi = Rect(Point(select.x, select.y), Point(x, y));
            if (roi.width && roi.height)
            {
                Mat roiImg = img(roi);
                imshow("roi", roiImg);
                imwrite("D://video picture//1.jpg", roiImg);
            }                           
            select_flag = false;
        }
        break;
    }
}

int main()
{
    img = imread("D://Libs//opencv310//opencv//sources//samples//data//aero1.jpg", 1);
    showImg = img.clone();
    select.x = select.y = 0;
    imshow("img", showImg);

    while (1)
    {
        int key = waitKey(10);
        switch (key)
        {
        case 's':
            setMouseCallback("img", S_on_Mouse, 0);
            break;
        }
        if (key == 27 || key == 'q')
            break;
    }
    waitKey(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u013539952/article/details/77171061
今日推荐