opencv入门-截图(图像和视频)

Posted 殇堼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv入门-截图(图像和视频)相关的知识,希望对你有一定的参考价值。

全部代码

静态图像截图

#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]在显示窗口中截图

以上是关于opencv入门-截图(图像和视频)的主要内容,如果未能解决你的问题,请参考以下文章

opencv学习-截图(图像和视频)

OpenCV入门(C++/Python)- 使用OpenCV读取和编写视频

OpenCV基于颜色的目标识别(入门简单摄像头版)

OpenCV图像处理——GUI功能

OpenCV+TensorFlow入门人工智能图像处理视频教程 共9章

OpenCV最详细入门-python(代码全部可以直接运行)