We use trackbars with opencv to change the line coordinates. There is a difference between C++ and Python when using the trackbars. In C++, callback values of the trackbars can be passed directly to the declared variables. Meanwhile in Python, we need to create callback functions to recive the trackbar values.
Python
deftrackbar1_cb(x): #executed when trackbar changesglobal val_tr1
val_tr1 = int(cv2.getTrackbarPos(name_tr1, title_win))
deftrackbar2_cb(x): #executed when trackbar changesglobal val_tr2
val_tr2 = int(cv2.getTrackbarPos(name_tr2, title_win))
To calculate the intersection between two lines, we use the standard form of the line equation.
Ax + By = C
Then, following equations are used to find the intersection coordinate in the algorithm. Remember that this uses two lines, and each line consists of two coordinates. For example, line one has P0 & P1 coordinate, and line two has P2 & P3 coordinate. Every P# has x and y value.
In the main algorithm, all the formulas are updated in a closed loop based on the trackbars' values. Therefore, we can play with the trackbars to get the desired results. The "canvas.png" can be downloaded here.
C++
Python
Mat canvas_in = imread("canvas.png");
resize(canvas_in, canvas_in, Size(maxSize, maxSize));
namedWindow(title_win);
createTrackbar(name_tr1, title_win, &val_tr1, maxSize, 0);
createTrackbar(name_tr2, title_win, &val_tr2, maxSize, 0);
while (1) {
//get the line values from the trackbarsint p0_x = val_tr1;
int p0_y = 0;
int p1_x = val_tr1;
int p1_y = maxSize;
int p2_x = 0;
int p2_y = val_tr2;
int p3_x = maxSize;
int p3_y = val_tr2;
/*Intersection between two lines***********************************/
float A1 = p1_y - p0_y;
float A2 = p3_y - p2_y;
float B1 = p0_x - p1_x;
float B2 = p2_x - p3_x;
float C1 = (A1 * p0_x) + (B1 * p0_y);
float C2 = (A2 * p2_x) + (B2 * p2_y);
float div = (A1* B2) - (A2 * B1);
float x = ((B2 * C1) - (B1 * C2)) / div;
float y = ((A1 * C2) - (A2 * C1)) / div;
/******************************************************************/
//plot the resultsMat canvas = canvas_in.clone();
line(canvas, Point(p0_x, p0_y), Point(p1_x, p1_y), Scalar(255,0,0), 5);
line(canvas, Point(p2_x, p2_y), Point(p3_x, p3_y), Scalar(0,0,255), 5);
circle(canvas, Point(x, y), 50, Scalar(0,255,0), 5);
imshow(title_win, canvas);
waitKey(1);
}
Executing the above codes should show the intersection position based on the two lines. Where, these two lines can be played using the trackbars. Please look at for the implementation of this algorithm.
Comments
Post a Comment