如何在opencv和c++中使用鼠标在图像上绘制线条

How can i draw lines on a image using mouse in opencv and c++?

本文关键字:图像 鼠标 绘制 opencv c++      更新时间:2023-10-16

我的目标是在opencv和c++中使用鼠标在图像中画一条线。我在网上看了不同的代码,但在有了一些想法后,我想自己尝试一下。我可能完全错了,但我只是个初学者。所以,我想尝试一下,但仍然不起作用,所以我想把它发布在这里。如果可能的话,请纠正我的错误。

 POINT p;
  GetCursorPos(&p);
 bool drawing;
  int x;
  int y;
  int startx,starty;
  int finishx,finishy;
  int z;
  int l;
Mat a;
a = imread("a.JPG");
 if(GetKeyState(VK_LBUTTON) & 0x80 != 0)
 {
     drawing = true;
     x = p.x;
    y = p.y;
    startx = x;//the starting position to start the drawing
     starty = y;

 }
if(GetKeyState(VK_RBUTTON) &0x80 != 0)
 {
     drawing = false;
    z= p.x;
    l = p.y;
    finishx = z;
    finishy = l;
 }
if(drawing==true)
  {
      line(a,Point(startx,starty),Point(finishx,finishy),Scalar(0,0,255),1);
          imshow("test image",a);
  }

您需要将划线代码放入setMouseCallback()指定的回调函数中。OpenCV有一个如何进行回调的演示。另请参阅此问题的答案使用python在open cv中使用鼠标事件绘制矩形或直线(答案在C++中)