最近写了一个python项目,有关一些python的知识点,这里记录一下,便于日后查阅~~
目录
一、python数学相关运算
1、已知两点,拟合直线
# slope斜率,intercept截距
slope, intercept = np.polyfit((x1, x2), (y1, y2), 1)
斜率转角度:
def slope_to_angle(slope):
# 使用反正切函数计算夹角,结果是以弧度为单位的
angle = math.atan(slope)
# 将夹角转换成角度
angle_degrees = math.degrees(angle)
return angle_degrees
2、已知两直线起点与终点,判断两条直线是否平行
def are_lines_parallel(x1, y1, x2, y2, x3, y3, x4, y4):
# 计算两条直线的斜率
slope1 = (y2 - y1) / (x2 - x1) if x2 != x1 else float('inf')
slope2 = (y4 - y3) / (x4 - x3) if x4 != x3 else float('inf')
angle1 = slope_to_angle(slope1)
angle2 = slope_to_angle(slope2)
# 如果两条直线的斜率都存在且相等,或者两条直线都垂直于x轴,则它们是平行的
if (abs(angle1 - angle2) < 2 and not math.isinf(slope1)) or (math.isinf(slope1) and math.isinf(slope2)):
# if ((slope1 - slope2) < 0.01 and not math.isinf(slope1)) or (math.isinf(slope1) and math.isinf(slope2)):
return True
else:
return False
3、已知两条直线,求解两直线交点
# 直线1的参数形式:A1 * x + B1 * y + C1 = 0
line1 = np.array([A1, B1, C1])
line2 = np.array([A2, B2, C2])
def line_intersection(line1, line2):
# 解线性方程组,获取交点
# 线性方程组形式:[A1, B1][x] + [C1] = 0 和 [A2, B2][x] + [C2] = 0
# x = np.linalg.solve([line1[:2], line2[:2]], [-line1[2], -line2[2]])
try:
x = np.linalg.solve([line1[:2], line2[:2]], [-line1[2], -line2[2]])
except:
print("矩阵不存在逆矩阵")
else:
return x
4、判断点是否在多边形内
# 定义多边形的顶点坐标
polygon = Polygon(list_pt)
# 定义要检查的点的坐标
point_to_check = Point(x1, y1)
# 使用within方法判断点是否在多边形内
if point_to_check.within(polygon):
print("点在多边形内")
else:
print("点不在多边形内")
二、python文件操作
pickle模块只能在python中使用,仅限于传输的两端都是python的情况,且需要尽量保持两端的版本一致。非Python程序可能无法重建pickle的Python对象。pickle序列化后的数据,可读性差,一般无法识别。
1、写入txt
import pickle
filename = "calibration.txt"
with open(filename, 'wb') as file:
pickle.dump(position, file)
2、读取txt
import pickle
with open('./calibration/calibration.txt', 'rb') as file:
content = pickle.load(file)
print(content[0:4])
print(content[4:8])
三、list相关操作
语法:
list.index(object[,start,end])
object:需要定索引的列表元素。
start:可选。起始值,表示开始索引的位置。默认从第一个位置开始。
end:可选。结束值,表示结束索引的位置。默认为最后的位置结束。
注意:①若列表中不存在索引值则报错。
②可以只填起始值而不填结束值,但是不能只填结束值。
用法:从列表中获取指定索引元素的第一个匹配位置。
#index
#定义列表
list1 = ['hello', 'world','welcome', 'to', 'our', 'world']
w_index = list1.index('world')
print('第一个匹配world的位置为:',w_index)
wel_index = list1.index('welcome')
print('第一个匹配welcome的位置为:',wel_index)
wor_index = list1.index('world',2)#从2+1的位置开始索引
print('从第3个位置开始索引,第一个匹配world的位置为:',wor_index)
wel_index2 = list1.index('welcome',1,4)
print('第一个匹配welcome的位置为:',wel_index2)
输出结果:
第一个匹配world的位置为: 1
第一个匹配welcome的位置为: 2
从第3个位置开始索引,第一个匹配world的位置为: 5
第一个匹配welcome的位置为: 2
注意:虽然指定了开始索引的位置,但是不代表开始索引的位置变成了起始位置0,起始位置还是原列表list1的hello。