In the main algorithm, we use following equations. Previously, we need to get the sum value (Σ) of x, y, xy, and x^2 of all the samples, as the general rule of Least Squares method.
y = mx + b
m = (n.Σxy - Σx.Σy) / (n.Σx^2 - (Σx)^2)
b = (Σy - m.Σx) / n
θ= atan (m)
Where, m is a slope or gradient of the line, b is y-intercept or y coordinate when x = 0, n is the number of samples, θ is the line angle, x and y are the values that we want to play with.
for i inrange(nSample):
sumX += particles_x[i]
sumY += particles_y[i]
sumXY += particles_x[i] * particles_y[i]
sumX2 += particles_x[i] * particles_x[i]
m = ((nSample * sumXY) - (sumX * sumY)) / ((nSample * sumX2) - (sumX * sumX))
b = (sumY - (m * sumX)) / nSample
theta = -atan(m) * 180 / 3.142857
new_x = 0; new_y = 0
for i inrange(nSample):
ifabs(theta) <= 45.0: #horizontal line, find y
new_x = particles_x[i]
new_y = (m * new_x) + b
else: #vertical line, find x
new_y = particles_y[i]
new_x = (new_y - b) / m
canvas = cv2.line(canvas, (int(new_x), int(new_y)), (int(particles_x[i]), int(particles_y[i])), (0,0,0), 1)
#canvas = cv2.circle(canvas, (int(new_x), int(new_y)), 10, (255,0,0), -1)
The last, plot the final result. It is similar to RANSAC in terms of results. However, each of them has its own pros and cons depending on the use case. Therefore, figuring out the most suitable for our implementation is important.
C++
Python
int min_x = 0;
int max_x = maxSize;
int min_y = round((m * min_x) + b);
int max_y = round((m * max_x) + b);
line(canvas, Point(min_x, min_y), Point(max_x, max_y), Scalar(0,0,255), 5);
string theta_str = to_string((int)round(theta));
putText(canvas, "Theta: "+to_string((int)round(theta))+"deg. m: "+to_string(m)+" b: "+to_string(b), Point(10,maxSize-10), FONT_HERSHEY_COMPLEX, 1, Scalar(0,0,255), 2);
while (1) {
imshow("Least Squares-Based Linear Regression @The JPID Coder", canvas);
waitKey(1);
}
Comments
Post a Comment