Skip to content

Instantly share code, notes, and snippets.

@sanuj
Created March 10, 2015 12:41
Show Gist options
  • Save sanuj/e0b6ab3fb8ae8a7d5e55 to your computer and use it in GitHub Desktop.
Save sanuj/e0b6ab3fb8ae8a7d5e55 to your computer and use it in GitHub Desktop.
Better Read/Writer vectors of OpenCV Points.
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <climits>
#include <opencv2/opencv.hpp>
#define DELIMITERS " \t,[]{}:\"abcdefghijklmnopqrstuvwz`~!@#$%^&*()_=+\\|;'?/.<>"
using namespace std;
using namespace cv;
char* removeHyphen(char* input) {
if(input == NULL) return input;
while(*input == '-' && *(input+1) == '-' && *input)
input++;
return input;
}
bool containsNumber(char* inp) {
while(*inp) {
cout << "checked" << endl;
if(*inp=='1' || *inp=='2'|| *inp=='3'|| *inp=='4'|| *inp=='5'|| *inp=='6'|| *inp=='7'|| *inp=='8'|| *inp=='9'|| *inp=='0')
return true;
inp++;
}
return false;
}
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())
{
bool x_found=false, y_found=false;
int x=INT_MIN, y=INT_MIN;
while(getline(fin, line))
{
char* token = strtok((char*)line.c_str(), DELIMITERS);
while(token != NULL)
{
if(*token == 'x')
x_found=true;
else if(*token == 'y')
y_found=true;
else {
if(x_found && containsNumber(token))
{
token = removeHyphen(token);
x = atoi(token);
x_found=false;
}
else if(y_found && containsNumber(token))
{
token = removeHyphen(token);
y = atoi(token);
y_found=false;
}
if(x!=INT_MIN && y!=INT_MIN)
{
pts.push_back(Point(x, y));
x=y=INT_MIN;
}
}
token = strtok(NULL, DELIMITERS);
}
}
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 },
{ "y"
:
7,
"x"
:
34 },
{ "x": 89,
" y": 56 },
{ "y": 1, "x":
9 },
{ "y": -9, "x": -67 },
{ "x ": -=-=-=-=-59, "y": -------2 },
{
x
=
5,
y
= 8},
{
x=$%5, y=---8
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment