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入门(C++/Python)- 使用OpenCV读取和编写视频