1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#include <opencv2/opencv.hpp> using namespace cv;
#define WINDOW_NAME "mouse"
void on_MouseHandle(int event, int x, int y, int flags, void *param); void DrawRectangle(cv::Mat &img, cv::Rect box); void ShowHelpText();
Rect g_rectangle; bool g_bDrawingBox = false; RNG g_rng(12345);
int main(int argc, char **argv) {
ShowHelpText();
g_rectangle = Rect(-1, -1, 0, 0); Mat srcImage(600, 800, CV_8UC3), tempImage; srcImage.copyTo(tempImage); g_rectangle = Rect(-1, -1, 0, 0); srcImage = Scalar::all(0);
namedWindow(WINDOW_NAME); setMouseCallback(WINDOW_NAME, on_MouseHandle, (void *)&srcImage);
while (1) { srcImage.copyTo(tempImage); if (g_bDrawingBox) DrawRectangle(tempImage, g_rectangle); imshow(WINDOW_NAME, tempImage); if (waitKey(10) == 27) break; } return 0; }
void on_MouseHandle(int event, int x, int y, int flags, void *param) {
Mat &image = *(cv::Mat *)param; switch (event) { case EVENT_MOUSEMOVE: { if (g_bDrawingBox) { g_rectangle.width = x - g_rectangle.x; g_rectangle.height = y - g_rectangle.y; } } break;
case EVENT_LBUTTONDOWN: { g_bDrawingBox = true; g_rectangle = Rect(x, y, 0, 0); } break;
case EVENT_LBUTTONUP: { g_bDrawingBox = false; if (g_rectangle.width < 0) { g_rectangle.x += g_rectangle.width; g_rectangle.width *= -1; }
if (g_rectangle.height < 0) { g_rectangle.y += g_rectangle.height; g_rectangle.height *= -1; } DrawRectangle(image, g_rectangle); } break; } }
void DrawRectangle(cv::Mat &img, cv::Rect box) { cv::rectangle( img, box.tl(), box.br(), cv::Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255))); }
void ShowHelpText() { printf("\n\n\n\t欢迎来到【鼠标交互演示】示例程序\n"); printf("\n\n\t请在窗口中点击鼠标左键并拖动以绘制矩形\n"); }
|