skLearn
先上计算交点函数:
适用于一次与二次、二次与二次曲线交点
def poly_intersection_from_coef(coef1, coef2, x_min, x_max, y_min, y_max, offset=0):
"""
计算交点:模拟 draw_fitted_curve 的点偏移效果。
:param coef1: 第一个曲线的poly系数
:param coef2: 第二个曲线的poly系数
:param x_min, x_max, y_min, y_max: ROI范围
:param offset: 偏移量,对最终点进行平移(模拟绘图点偏移)
:return: [(x, y)]
"""
poly1 = np.poly1d(coef1)
poly2 = np.poly1d(coef2)
print(' poly1 ==',poly1,)
print(' *************')
print(' poly2 ==',poly2)
print(' ***************')
# 构造差值多项式(不偏移自变量)
intersection_poly = poly1 - poly2
intersection_x = intersection_poly.r
intersection_x = intersection_x[np.isreal(intersection_x)].real
intersections = []
for x in intersection_x:
if x_min <= x <= x_max: # 不做 offset 修正
x_global = x + offset # 平移x
y = poly1(x) # 对应原多项式计算y(未平移)
if y_min <= y <= y_max:
intersections.append((int(round(x_global)), int(round(y))))
intersections.sort(key=lambda p: p[0])
if not intersections:
print("⚠️ 未找到有效交点,可能为非相交或超出ROI范围")
return intersections
def get_polynomial_coefficients(model, degree = 2):
"""从拟合模型中提取多项式系数"""
# 获取 RANSAC 内部的线性回归器
linear_regressor = model.named_steps['ransacregressor'].estimator_
# 获取系数和截距
coefficients = linear_regressor.coef_
intercept = linear_regressor.intercept_
# 多项式系数(按次数从低到高排列)
poly_coefficients = [intercept] # 常数项
print('coefficients ,intercept==== ',coefficients ,intercept)
# 提取不同次数的系数
for i in range(1, degree + 1):
# 对于 degree=i,PolynomialFeatures 会生成 x, x², ..., x^i
# 对应的系数位于 linear_regressor.coef_ 的第 i 个位置
poly_coefficients.append(coefficients[i])
# 如果需要高次项在前的格式,则反转系数列表
high_degree_first=True
#反转为高次在前
if high_degree_first:
poly_coefficients.reverse()
return poly_coefficients
###########原
def extract_coef_from_pipeline(pipeline_model):######只适用于1,2次
"""
从Pipeline模型中提取多项式拟合系数,并按np.polyfit格式输出(高次项在前)。
自动适配1次或2次拟合。
"""
ransac_estimator = pipeline_model.named_steps['ransacregressor'].estimator_
coef = ransac_estimator.coef_ #多项式的系数(不含常数项)
intercept = ransac_estimator.intercept_ #常数项(截距)
# 获取多项式阶数
poly_degree = len(coef)-1
if poly_degree == 1:
# 一次拟合:[x, 常数]
print('一次###',coef,intercept)
return [coef[1], intercept] # [斜率, 截距]
elif poly_degree == 2:
# 二次拟合:[x², x, 常数]
print('二次###',coef,intercept)
return [coef[2], coef[1], intercept]
else:
raise ValueError(f"extract_coef_from_pipeline不支持的多项式维度:degree={poly_degree}")
right_top_ransac, X_rt, y_rt = self.ransac_fit(right_top_points, degree=self.fit_degree, params=params)
right_bottom_ransac, X_rb, y_rb = self.ransac_fit(right_bottom_points, degree=1, params=params)
right_candidates = poly_intersection_from_coef(coef_rt, coef_rb, 0, roi_width, 0, roi_height, offset=+ j2-x_min)
对于extract_coef_from_pipeline函数中的coef = ransac_estimator.coef_ 的多项式的系数其为升序的即:对于二次曲线:二次拟合:[0,x,x², ]#x的0次x,1次x,2次x, 截距为intercept = ransac_estimator.intercept_