Sunday, December 3, 2017

opencv - mouse event 滑鼠事件


利用OpenCV的滑鼠事件(Mouse Event) 實作簡單的小畫家

---

程式碼:

#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

Mat palette; //調色盤
Mat canvas;  //畫布
Scalar brushColor; //儲存畫筆的顏色

void renew_brushColor(int r, int g, int b)
{
 brushColor = Scalar(b, g, r); 
 Mat img_brushColor(150, 150, CV_8UC3, brushColor); //顯示現在畫筆顏色的視窗

 imshow("brush color", img_brushColor);
}

void mouseEvent_getColor(int event, int x, int y, int flag, void* param)
{
 if (event == CV_EVENT_LBUTTONDOWN)
 {
  int r = palette.at<Vec3b>(y, x)[2]; //紅色在第三通道
  int g = palette.at<Vec3b>(y, x)[1]; //綠色在第二通道
  int b = palette.at<Vec3b>(y, x)[0]; //藍色在第一通道

  cout << "x, y = (" << x << ", " << y << ")      ";
  cout << "r, g, b = (" << r << ", "<< g << ", " << b << ")" << endl;

  renew_brushColor(r, g, b);
 }
}

void mouseEvent_drawColor(int event, int x, int y, int flag, void* param)
{
 static bool flag_down = false;

 if (event == CV_EVENT_LBUTTONDOWN)
 {
  flag_down = true;
  
 }

 if (event == CV_EVENT_MOUSEMOVE && flag_down == true)
 {
  circle(canvas, Point(x, y), 3, brushColor, 2, 8, 0);
  imshow("canvas", canvas);

 }

 if (event == CV_EVENT_LBUTTONUP)
 {
  flag_down = false;

 }
}

int main()
{

 palette = imread("colour_palette.png"); //將色票圖檔讀進調色盤
 imshow("colour palette",palette);

 canvas = Mat(300, 300, CV_8UC3, Scalar(255, 255, 255)); //創建畫布
 imshow("canvas", canvas);


 setMouseCallback("colour palette", mouseEvent_getColor);
 setMouseCallback("canvas", mouseEvent_drawColor);

 waitKey(0);
 system("pause");
 return 0;
}

---

我所使用的調色盤檔案: 檔案連結




運行結果:





No comments:

Post a Comment