如何在opencv中使用鼠标点击在图像上绘制线条

How do I draw lines on a image using mouse clicks in opencv?

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

因此,在遵循stackexchange用户关于鼠标事件的建议后,我能够理解并使用鼠标点击实现一些简单的任务。所以,下一个目标是用鼠标左键和鼠标右键画一条简单的线。不幸的是,在我实现我的程序后,我看不到任何行。

int x,y;
Point p(0,0);
Point q(0,0);
Mat xal;
void drawimage()
{
    a = q.x - p.x; //i am just checking out the values of a and b to see if the     drawimagefunction is being called in the rightmouse click event
              b = q.y - p.y;
              cout<<" a is :"<<a<<endl;
              cout<<"b is:"<<b<<endl;
    line(xal,Point(p.x,p.y),Point(q.x,q.y),Scalar(0,0,255),2,8);
}
void onMouse( int event, int x, int y, int f, void* )
{
    switch (event)
    {
        case EVENT_LBUTTONDOWN:

            cout<<"Left button was pressed"<<x<<" "<<y<<" "<<endl;
            {
                p.x = x;
                p.y = y;
                cout<<"p is:"<<p.x<<p.y<<endl;
            }
            break;
        case EVENT_RBUTTONDOWN:
            cout<<"Right button was pressed at :"<<x <<" "<<y<<endl;

            {
                q.x = x;
                q.y = y;
                drawimage();//no line is being drawn though i can see that i get the values of a and b in the drawimage function.
            }
            break;
        default:
            break;
    }
}
int main()
{
    xal = imread("pic.JPG);
    namedWindow("Picture",1);
    setMouseCallback("Picture",onMouse,NULL);
    imshow("Picture",xal);
    cvwaitkey(0);
}

在drawLine()函数中的"line(..)"调用后添加以下内容:

imshow("Picture", xal);

问题是,您正在将行写入xal矩阵,但尚未更新屏幕上的图像,这就是imshow(..)调用所要做的。

试试这段代码。它对你很有用。

#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace std;
using namespace cv;
void drawimage()
{
    line(xal,Point(p->x,p->y),Point(q->x,q->y),Scalar(0,0,255),2,8);
}
void CallBackFunc(int event, int x, int y, int flags, void *ptr )
{
    if ( event == EVENT_LBUTTONDOWN )
    {
        Point*p = (Point*)ptr;
        p->x = x;
        p->y = y;
        drawimage();
    }
    else if  ( event == EVENT_RBUTTONDOWN )
    {
        Point*q = (Point*)ptr;
        q->x = x;
        q->y = y;
        drawimage();
    }
}
int main(int argc, char** argv)
{
    // Read image from file 
    Point p;
    Point q;
    Mat xal = imread("MyPic.JPG");
    //if fail to read the image
    if ( xal.empty() ) 
    { 
        cout << "Error loading the image" << endl;
        return -1; 
    }
    //Create a window
    namedWindow("My Window", 1);
    //set the callback function for any mouse event
    setMouseCallback("My Window", CallBackFunc,&p);
    setMouseCallback("My Window", CallBackFunc,&q);
    //show the image
    imshow("My Window", xal);
    // Wait until user press some key
    waitKey(0);
    return 0;
}