我有一个定义的函数,可以从自变量x内插因变量y(x)。 (已知的值在下面的函数中显示。)我希望对整个值[512x512](甚至[512x512x133])数组执行该操作,而不是对单个值x0执行它。是否有比通过嵌套的for loop2 in range(0, len(target(loop1,loop2)))
循环遍历每一行更好的方法?
我将添加嵌套的for
循环来重写此函数,但是首先,我将阅读更多Python教程。当前在section 4.6, "Defining Functions"上。
def interpSPR(target):
"""Interpolate SPR given CT value according to Kanematsu et al. 2003
We use the lookup table provided by Dr. Matsumura to interpolate SPR values
from each pixel's CT Number."""
## Input CT Number to Stopping Power Ratio (SPR) Lookup Table from XiO-N
CTvalues = [-992.516,-399.723,-152.726, 94.27054,291.868,1971.447,11081,24414]
SPR = [ 0, 0.602, 0.913822,1.078872, 1.151456,1.900912, 6, 12]
# Check first to see if the value is one of those already in the table.
if target in CTvalues:
for num in range(0,len(CTvalues)):
if target == CTvalues[num]:
return SPR[num]
# If it isn't, interpolate the value.
else:
for num in range(0,len(CTValues)):
if target < CTvalues[0]:
y1,y2,x0,x1,x2 = SPR[0],SPR[1],target,CTvalues[0],CTvalues[1]
answer = y1 - ((x1-x0)/(x2 - x1))*(y2 - y1)
return answer
elif target > CTvalues[num] and target < CTValues[num+1]:
y1,y2,x0,x1,x2 = SPR[num],SPR[num+1],target,CTvalues[num],CTvalues[num+1]
answer = y1 - ((x1-x0)/(x2 - x1))*(y2 - y1)
return answer
elif target > CTvalues[-1]:
y1,y2,x0,x1,x2 = SPR[-2],SPR[-1],target,CTvalues[-2],CTvalues[-1]
answer = y1 - ((x1-x0)/(x2 - x1))*(y2 - y1)
return answer
答案 0 :(得分:0)
numpy为此np.interp()
提供了内置功能:
import numpy as np
def interpSPR(target):
CTvalues = [-992.516, -399.723, -152.726, 94.27054, 291.868, 1971.447, 11081, 24414]
SPR = [ 0, 0.602, 0.913822, 1.078872, 1.151456, 1.900912, 6, 12]
return np.interp(target, CTvalues, SPR)
如果我们稍微改变数据,则在图中更容易看到:
CTvalues = [0, 5, 15, 20, 40]
SPR = [2, 7, 20, 21, 50]
def interpSPR(target):
CTvalues = [0, 5, 15, 20, 40]
SPR = [2, 7, 20, 21, 50]
return np.interp(target, CTvalues, SPR)
fig, ax = plt.subplots()
ax.scatter(CTvalues, SPR)
target = np.linspace(-10, 50, 100)
ax.plot(target, interpSPR(target))