# Use Python to read in two columns of fitting lines from CSV files

CurrySerena 2022-05-14 16:18:35 阅读数:824

background ： It is necessary to judge whether the track tracked by the tracking algorithm is a straight line when the target is controlled to walk in a straight line , I saved the pixel position of the center point of the target tracked by the tracking algorithm on the image , Then fit the straight line passing through these points , The accuracy of these straight-line tracking points is then determined by the average distance .（ This is not to consider , Although we control the target to go in a straight line , But is this control precision high , Or say , He walked by himself , The track is offset , This requires a reference , For example, let the sweeper walk along the gap between floor tiles ）

Mainly used python Read csv data

``````def readfile(filename):
with open(filename, 'r') as f:
try:
x = eval(line)
y = eval(line)
x_list.append(x)
y_list.append(y)
except:
pass``````
``````x_list = []
y_list = []
def func(a, b, x):
return a*x + b
def linefitting():
xs = np.array(x_list)
ys = np.array(y_list)
para = np.polyfit(xs, ys, deg = 1)
print(" Fitted linear equation y=",np.poly1d(para) )
y_fitted = func(para,para, xs)
plt.figure
plt.plot(xs, ys, 'ro', label='Original curve')
plt.plot(xs, y_fitted, '-b', label = 'Fitted curve')
plt.savefig('./trajectory.png')
plt.legend()
plt.show()
return para
``````
``````def calprecision(para):
# Calculate the distance from all points to the straight line
# y = a*x + b
# a*x - y + b = 0
# (a/b)*x - (1/b)*y + 1 = 0
# Scheme 1
# a = para/para
# b = -1/para
# c = 1
# Option two
a = para
b = -1
c = para
print("a:", a)
print("b:", b)
print("c:", c)
# ax+by+c = 0
sum = 0
down_num = cmath.sqrt(a**2 + b**2)
# print("down_num:", down_num)
for i in range(len(x_list)):
x = x_list[i]
y = y_list[i]
dis = abs(a*x + b*y + c)/down_num
sum += dis
print(" Total distance ",sum)
average = sum/len(x_list)
print(" Average pixel distance ：",average)``````