Python-多段折线Lut拟合工具

用途:给定折断点坐标信息,插值出折线图上对应点的y值
例如:

输入: cut_dots=np.array([[0,0.5],[8,0.65],[18,0.996],[63,0.996]]) #need min/max
拟合结果图
输出: 0.5 0.519 0.538 0.556 0.575 0.594 0.612 0.631 0.65 0.685 0.719 0.754 0.788 0.823 0.858 0.892 0.927 0.961 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996 0.996

完整代码

import numpy as np
import matplotlib.pyplot as plt

def write2txt(txt_path,write_array,type):
    with open(txt_path,'w') as f:
        for i in range(write_array.size):
            if type=='float':
                print(np.around(write_array[i],3),end=' ',file=f)
                print(np.around(write_array[i],3),end=' ')
            elif type=='int':
                print(write_array[i].astype(int),end=' ',file=f)
                print(write_array[i].astype(int),end=' ')

def line_mode(cut_dots):
    cut_dots_T = cut_dots.T
    x = cut_dots_T[0]
    y = cut_dots_T[1]
    table_x = np.linspace(x[0],x[-1],x[-1]-x[0]+1)

    for i in range(x.size-1):
        if i==0:
            table_y = np.linspace(y[0],y[1],x[1]-x[0]+1)
        else:
            table_y = np.concatenate((table_y, np.linspace(y[i],y[i+1],x[i+1]-x[i]+1)[1:]))
    plt.plot(table_x, table_y)
    plt.show()
    return(table_x,table_y)

if __name__ == '__main__':
    # 1. 定义折点,须包括第一个和最后一个点(务必确保最小和最大的x值),定义输出值类型
    cut_dots=np.array([[0,0.5],[8,0.65],[18,0.996],[63,0.996]]) #need min/max
    type = 'float'#'int'
    # 2. 绘制多段折线图,并返回拟合的y值
    table_x,table_y = line_mode(cut_dots)
    # 3. 输出&输出为txt,指定输出文件名
    txt = r'table_y.txt'

    write2txt(txt,table_y,type)

你可能感兴趣的:(Python-多段折线Lut拟合工具)