Return coordinate values from mouse callback function and save values to txt

asked 2014-08-02 02:54:21 -0600

justrookie gravatar image

updated 2015-07-19 14:17:35 -0600

I want to return point coordinates from mouse callback function and save it to txt file, but the txt file is empty. I have checked the code and found that the vector<point> is empty, but I do not know how to fix it. Any help?

My code:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <stdio.h>
#include <vector>
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;


Mat org;
int n=0;
vector<Point> capturePoint;// point coordinates, global variable;

void on_mouse(int event,int x,int y,int flags,void *ustc)
{
    Point pt;//mouse position;
    char coordinate[16];

    if (event == CV_EVENT_LBUTTONDOWN)
    {
        pt = Point(x,y);
        cout<<x<<" "<<y<<endl;
        capturePoint.push_back(pt);
        n++;

        circle(org,pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0);
        sprintf(coordinate,"(%d,%d)",x,y);
        putText(org,coordinate,pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255),1,8);

        //imshow("org",org);

        if(n>=4)//only four points are needed;
        {
            imshow("org",org);
            cvDestroyAllWindows();
        }
    }
}

int main()
{
    org = imread("1-3.jpg",1);

    namedWindow("org",1);
    setMouseCallback("org",on_mouse,0);//mouse callback function;

    imshow("org",org);
    //cout<<n<<endl;

    cout<<capturePoint.size()<<endl;
    ofstream file("sample.txt");//save coordinates to txt file;
    if(!file)
    {
        cout << "open file error!";
        return 1;
    }
    vector<Point>::iterator it=capturePoint.begin();
    for(;it!=capturePoint.end();++it)
    {
        file<< it->x<<','<<it->y<<endl;
    }
    //file<<endl;
    file.close();

    waitKey(0);
    return 0;
}
edit retag flag offensive close merge delete

Comments

3

move the ofstream / vector iterating code after the waitKey(0); (or insert another waitKey(0) before)

then press a key after clicking points

berak gravatar imageberak ( 2014-08-02 03:00:39 -0600 )edit
1

Like berak said. Your actual program is waiting at your waitKey(0) and thus the file writing happens instanteneously.

StevenPuttemans gravatar imageStevenPuttemans ( 2014-08-02 03:34:32 -0600 )edit