#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <stdlib.h>
void main( int argc, char** argv )
{
FILE *fp;
int i;
int count = 48; // total number of points
int tmp1, tmp2;
CvPoint left, right;
float *line;
line = new float[4*count];
IplImage* img=cvLoadImage("b.bmp",1);// just a black image
cvNamedWindow( "input_image", CV_WINDOW_AUTOSIZE );
fp = fopen("xy.txt", "r"); // xy.txt have the (x, y)
position
CvPoint* points = (CvPoint*)malloc( count * sizeof(points[0]));
for (i=0; i<count; i++) {
fscanf(fp, "%d %d", &tmp1, &tmp2);
points[i].x = tmp1;
points[i].y = tmp2;
((uchar*)(img->imageData + img->widthStep*tmp2))[tmp1*3 + 0]
=255;
((uchar*)(img->imageData + img->widthStep*tmp2))[tmp1*3 + 1]
=255;
((uchar*)(img->imageData + img->widthStep*tmp2))[tmp1*3 + 2]
=255;
}
fclose(fp);
cvShowImage("input_image", img); // white spots with black
background
cvWaitKey(0);
CvMat point_mat = cvMat( 1, count, CV_32SC2, points );
cvFitLine( &point_mat, CV_DIST_L2 , 0, // line[0]:vector_x, line[1]:
vector_y
0.01, 0.01, line ); // line[2]:x_n, line[3]:y_n
// we get the vector and one point
// on the line, so the line is determined
double a, b, c, d, e, f; // y = a + b*x, b is slop
b = line[1]/ line[0]; // y = c + d*x
a = line[3]- b*line[2]; // y = e + f*x
d = -1/b;
c = points[0].y - d*points[0].x;
f = d;
e = points[count-1].y - f*points[count-1].x;
left.x = (a-c)/(d-b); // x = (a-c)/(d-b)
left.y = c+d*left.x; // y = a + b*x
right.x = (a-e)/(f-b);
right.y = e+f*right.x;
CvPoint center;
center.x = line[2];
center.y = line[3];
// can draw from left to right directly
cvLine( img, center, left, CV_RGB(255,0,0), 1, 8 );
cvLine( img, center, right, CV_RGB(255,0,0), 1, 8 );
cvShowImage("input_image", img);
cvWaitKey(0);
delete []line;
}
Friday, January 13, 2006
OpenCV: fit line (line-fitting )
// fit-line for 2-D data (line-fitting)
Subscribe to:
Post Comments (Atom)
The format is OK
ReplyDeletethank you!
ReplyDeleteThis works only if the first and last point are the extreme point. What if the first and last point are not the extreme point?
ReplyDelete