c++ - 无法使用鼠标单击在图像上绘制多条线

标签 c++ opencv

我学会了如何在 OpenCV 中使用 line( frame, Point( 15, 20 ), Point( 70, 50), 'r', 2, 8 );

我还学会了如何使用鼠标点击在图像上画线。例如,下面的代码绘制了一条连接用户点击图像的两点的线:

using namespace cv;
using namespace std;


void onMouse(int evt, int x, int y, int flags, void* param) {
    if(evt == CV_EVENT_LBUTTONDOWN) {
        std::vector<cv::Point>* ptPtr = (std::vector<cv::Point>*)param;
        ptPtr->push_back(cv::Point(x,y));
    }
}

int main()

{

std::vector<Point> points;

cv::namedWindow("Output Window");

Mat frame = cv::imread("chhha.png");

cv::setMouseCallback("Output Window", onMouse, (void*)&points);
int X1=0, Y1=0, X2=0, Y2=0; 

while(1)
{
    cv::imshow("Output Window", frame);

    if (points.size() > 1) //we have 2 points
    {

        for (auto it = points.begin(); it != points.end(); ++it)
        {


        }

        break;
    }
    waitKey(10);
}


 // Now let us draw a line on the image 
  line( frame, points[0], points[1], 'r',  2, 8 );
  cv::imshow("Output Window", frame);

  waitKey( 10 );

getch(); 

return 0;  
}

现在基本上我想要的是继续绘制线条,直到我右键单击或者可能输入了一些字符。

到目前为止我尝试的是使用 do-while 循环:

char m; 
do{
while(1)
{
    cv::imshow("Output Window", frame);

    if (points.size() > 1) //we have 2 points
    {

        for (auto it = points.begin(); it != points.end(); ++it)
        {


        }


        break;
    }
    waitKey(10);


}


//      Draw a line 
line( frame, points[0], points[1], 'r',  2, 8 );
cv::imshow("Output Window", frame);


cout<<"do you want more lines, if so , press 'y'"<<endl; 
cin>>m; 

// instead of this a right click check would be much better 
if(m!='y')

{
    break; 
}


}while(m=='y');

但问题是这样连一条线都画不出来,点击几下输入“y”后,应用程序不会响应。

请帮我解决这个问题。

最佳答案

您的代码可能存在多个问题,无法按照您的意愿执行。首先想到的是您没有清除用于捕获坐标的 vector 。画线后

line( frame, points[0], points[1], 'r',  2, 8 );

你应该像这样重置 vector

points.clear();

以便下一次鼠标点击的坐标转到 points[0]。否则它会追加到 vector 上,您会一遍又一遍地在前两个鼠标坐标之间画线。

关于c++ - 无法使用鼠标单击在图像上绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24604621/

相关文章:

c++ - Boost Asio - 消息内容传输错误

opencv - 片段着色器 : texture2D() and texelFetch()

python - 从OpenCV中的图像定位和提取(未知)书籍

c++ - 如何乘以矩阵?

c++ - Opencv 功能匹配在 iPhone 上中断,但在模拟器上没有

c++ - OpenCV 中的 accumulateWeighted 函数断言失败

android - 在 native 代码中使用 opencv 进行 Android 应用程序开发

c++ - 在 C++ 中自动从 double/int/string 转换为 bool

c++ - 用标准 C 或 C++ 编写的解释器

c++ - 让敌方车辆跟随玩家车辆 C++