全部代码
静态图像截图
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src, dst, g_img_dst,g_img_sub;
bool g_is_rect_inited = false;
Point g_rect_tl;
void onMouse(int event, int x, int y, int, void*)
{
if (EVENT_LBUTTONDOWN == event) {
g_is_rect_inited = true;
g_rect_tl = Point(x, y);
}
else if (EVENT_MOUSEMOVE == event && g_is_rect_inited) {
src.copyTo(g_img_dst);
rectangle(g_img_dst, g_rect_tl, Point(x, y), Scalar_<uchar>::all(200), 3, 8);
imshow("image", g_img_dst);
}
else if (EVENT_LBUTTONUP == event && g_rect_tl != Point(x, y)) {
src(Rect(g_rect_tl, Point(x, y))).copyTo(g_img_sub);
cvtColor(g_img_sub, dst, COLOR_BGR2GRAY);
imshow("截图", dst);
g_is_rect_inited = false;
}
}
int main(int argc, char** argv) {
src = imread("D:/images/lena.jpg");
if (src.empty()) {
cout << "[ERROR] : please check your image file name." << endl;
return EXIT_FAILURE;
}
namedWindow("image", WINDOW_AUTOSIZE);
setMouseCallback("image", onMouse, 0);
while (true) {
imshow("image", src);
int c = waitKey(0);
if ((c & 255) == 27) { // Esc
destroyAllWindows();
cout << "Exiting ...\n";
break;
}
}
return 0;
}
对视频流截图
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src, dst, g_img_dst,g_img_sub;
bool g_is_rect_inited = false;
Point g_rect_tl;
void onMouse(int event, int x, int y, int, void*)
{
if (EVENT_LBUTTONDOWN == event) {
g_is_rect_inited = true;
g_rect_tl = Point(x, y);
}
else if (EVENT_MOUSEMOVE == event && g_is_rect_inited) {
src.copyTo(g_img_dst);
rectangle(g_img_dst, g_rect_tl, Point(x, y), Scalar_<uchar>::all(200), 3, 8);
imshow("image", g_img_dst);
}
else if (EVENT_LBUTTONUP == event && g_rect_tl != Point(x, y)) {
src(Rect(g_rect_tl, Point(x, y))).copyTo(g_img_sub);
cvtColor(g_img_sub, dst, COLOR_BGR2GRAY);
imshow("截图", dst);
g_is_rect_inited = false;
}
}
int main(int argc, char** argv) {
VideoCapture video(0);
while (1)//循环显示每一帧
{
video >> src;//读取当前帧
if (src.empty()) {
cout << "[ERROR] : please check your image file name." << endl;
break;
}
namedWindow("image", WINDOW_AUTOSIZE);
setMouseCallback("image", onMouse, 0);
while (true) {
imshow("image", src);
int c = waitKey(0);
if ((c & 255) == 27) { // Esc
destroyAllWindows();
cout << "Exiting ...\n";
break;
}
}
return 0;
}
}
reference [OpenCV]在显示窗口中截图
|