Skip to content

Instantly share code, notes, and snippets.

@sanuj
Created March 7, 2015 17:19
Show Gist options
  • Save sanuj/50818db8e0365508aa67 to your computer and use it in GitHub Desktop.
Save sanuj/50818db8e0365508aa67 to your computer and use it in GitHub Desktop.
Read/Write vectors of OpenCV Points.
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void writePointVector(const vector<Point>& pts, const string& filename)
{
ofstream fout(filename.c_str());
if(fout.is_open())
{
fout << "[\n";
for(int i=0; i<pts.size()-1; i++)
fout << "\t{ \"x\": " << pts[i].x << ", \"y\": " << pts[i].y << " },\n";
fout << "\t{ \"x\": " << pts[pts.size()-1].x << ", \"y\": " << pts[pts.size()-1].y << " }\n";
fout << "]\n";
fout.close();
}
else
cout << "Unable to open " << filename << endl;
}
void readPointVector(const string& filename, vector<Point>& pts)
{
ifstream fin(filename.c_str());
string line;
if(fin.is_open())
{
while(getline(fin, line))
{
char* token;
token = strtok((char*)line.c_str(), " \t,[]{}:\"");
while(token != NULL)
{
char *x=NULL, *y=NULL;
if(*token == 'x')
{
x = strtok(NULL, " \t,[]{}:\"");
strtok(NULL, " \t,[]{}:\"");
y = strtok(NULL, " \t,[]{}:\"");
}
else if(*token == 'y')
{
y = strtok(NULL, " \t,[]{}:\"");
strtok(NULL, " \t,[]{}:\"");
x = strtok(NULL, " \t,[]{}:\"");
}
if(x!=NULL && y!=NULL)
pts.push_back(Point(atoi(x), atoi(y)));
token = strtok(NULL, " \t,[]{}:\"");
}
}
fin.close();
}
else
cout << "Unable to open " << filename << endl;
}
int main()
{
vector<Point> pts;
// pts.push_back(Point(2, 3));
// pts.push_back(Point(7, 34));
// pts.push_back(Point(89, 56));
// pts.push_back(Point(-1, 7));
// writePointVector(pts, "vector_output.txt");
readPointVector("vector_input.txt", pts);
for(int i=0; i<pts.size(); i++)
cout << "x: " << pts[i].x << ", y: " << pts[i].y << endl;
return 0;
}
x: 2, y: 3
x: 34, y: 7
x: 89, y: 56
x: 9, y: 1
x: -67, y: -9
x: 59, y: 2
[
{ "x": 2, "y": 3 },
{ "y": 7, "x": 34 },
{ "x": 89, " y": 56 },
{ "y": 1, "x": 9 },
{ "y": -9, "x": -67 },
{ "x ": 59, "y": 2 }
]
[
{ "x": 2, "y": 3 },
{ "x": 7, "y": 34 },
{ "x": 89, "y": 56 },
{ "x": -1, "y": 7 }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment