def get_LUT_value(self, data, window, level):
"""Apply the RGB Look-Up Table for the given data and window/level value."""
if not have_numpy:
raise ImportError("Numpy is not available. See http://numpy.scipy.org/ to download and install")
if isinstance(window, list):
window = window[0]
if isinstance(level, list):
level = level[0]
return np.piecewise(data,
[data <= (level - 0.5 - (window - 1) / 2),
data > (level - 0.5 + (window - 1) / 2)],
[0, 255, lambda data: ((data - (level - 0.5)) / (window - 1) + 0.5) * (255 - 0)]
)
# -----------------------------------------------------------
# ImFrame.loadPIL_LUT(dataset)
# Display an image using the Python Imaging Library (PIL)
# -----------------------------------------------------------
python类piecewise()的实例源码
def get_LUT_value(self, data, window, level):
"""Apply the RGB Look-Up Table for the given data and window/level value."""
if not have_numpy:
raise ImportError("Numpy is not available. See http://numpy.scipy.org/ to download and install")
if isinstance(window, list):
window = window[0]
if isinstance(level, list):
level = level[0]
return np.piecewise(data,
[data <= (level - 0.5 - (window - 1) / 2),
data > (level - 0.5 + (window - 1) / 2)],
[0, 255, lambda data: ((data - (level - 0.5)) / (window - 1) + 0.5) * (255 - 0)]
)
# -----------------------------------------------------------
# ImFrame.loadPIL_LUT(dataset)
# Display an image using the Python Imaging Library (PIL)
# -----------------------------------------------------------
def cosine_kernel(x):
'''
Raised cosine basis kernel, normalized such that it integrates to 1
centered at zero. Time is rescaled so that the kernel spans from
-2 to 2
Parameters
----------
x : vector
Returns
-------
vector
$\\tfrac 1 4 + \\tfrac 1 2 cos(x)$ if $x\in[-\pi,\pi]$, otherwise 0.
'''
x = np.float64(np.abs(x))/2.0*np.pi
return np.piecewise(x,[x<=np.pi],[lambda x:(np.cos(x)+1)/4.0])
def safe_inverse_root(d):
if (d < 0).any():
raise ValueError
return np.piecewise(d, [d>0, d==0], [lambda x: x**(-0.5), lambda x: x])
def get_LUT_value(data, window, level):
"""Apply the RGB Look-Up Table for the given data and window/level value."""
if not have_numpy:
raise ImportError("Numpy is not available. See http://numpy.scipy.org/"
" to download and install")
return np.piecewise(data,
[data <= (level - 0.5 - (window - 1) / 2),
data > (level - 0.5 + (window - 1) / 2)],
[0, 255, lambda data: ((data - (level - 0.5)) /
(window - 1) + 0.5) * (255 - 0)])
def breakpoint_linear(x, ts, k1, k2, c1):
'''Function representing a step-wise linear curve with one
breakpoint located at ts.
'''
return np.piecewise(x, [x < ts], [lambda x: k1 * x + c1,
lambda x: k2 * x + (k1 - k2) * ts + c1])
def nfw_cumulative(self,R):
'''
Cumulative radial NFW distribution
@param R: Radius
@return float: Probability of being within R
'''
R0 = self.__R0
norm = self.__norm
Rs = self.__Rs
Rcore = self.__Rcore
def integrate(z):
return quad(nfw,0,z,args=(norm,Rs,Rcore))[0]
if np.isscalar(R):
R = np.array([float(R)])
else:
R = R.astype(np.float)
res = np.piecewise(R, [R < 0.0, np.logical_and(R >= 0.0, R < R0), R >= R0],
[lambda z: z,
lambda z: np.fromiter(map(integrate,z),np.float),
lambda z: z/R0])
if len(res) == 1:
return res[0]
else:
return res
def coordinate_Newton(losses, indice, grad, hess, batch_size, mt_arr, vt_arr, real_modifier, up, down, lr, adam_epoch, beta1, beta2, proj):
# def sign(x):
# return np.piecewise(x, [x < 0, x >= 0], [-1, 1])
cur_loss = losses[0]
for i in range(batch_size):
grad[i] = (losses[i*2+1] - losses[i*2+2]) / 0.0002
hess[i] = (losses[i*2+1] - 2 * cur_loss + losses[i*2+2]) / (0.0001 * 0.0001)
# print("New epoch:")
# print('grad', grad)
# print('hess', hess)
# hess[hess < 0] = 1.0
# hess[np.abs(hess) < 0.1] = sign(hess[np.abs(hess) < 0.1]) * 0.1
# negative hessian cannot provide second order information, just do a gradient descent
hess[hess < 0] = 1.0
# hessian too small, could be numerical problems
hess[hess < 0.1] = 0.1
# print(hess)
m = real_modifier.reshape(-1)
old_val = m[indice]
old_val -= lr * grad / hess
# set it back to [-0.5, +0.5] region
if proj:
old_val = np.maximum(np.minimum(old_val, up[indice]), down[indice])
# print('delta', old_val - m[indice])
m[indice] = old_val
# print(m[indice])
def get_LUT_value(data, window, level):
"""Apply the RGB Look-Up Table for the given data and window/level value."""
if not have_numpy:
raise ImportError("Numpy is not available. See http://numpy.scipy.org/"
" to download and install")
return np.piecewise(data,
[data <= (level - 0.5 - (window - 1) / 2),
data > (level - 0.5 + (window - 1) / 2)],
[0, 255, lambda data: ((data - (level - 0.5)) /
(window - 1) + 0.5) * (255 - 0)])
def predict(weight, inp):
inp = modulate(inp)
net = np.dot(weight, inp)
predOtp = np.piecewise(net, [net<0, net>0], [-1, 1])
return demodulate(predOtp)
def continuum_kernel(x):
'''
limit of continuum magic kernel as a piecewise function.
See http://johncostella.webs.com/magic/
Parameters
----------
Returns
-------
'''
x = np.float64(abs(x))
return np.piecewise(x,[x>=1.5,(x>=0.5)&(x<1.5),(x>=0.0)&(x<0.5)],\
[lambda x:0, lambda x:0.5*(x-1.5)**2, lambda x:0.75-x**2])
def cosine_kernel(x):
'''
raised cosine basis kernel, normalized such that it integrates to 1
centered at zero. Time is rescaled so that the kernel spans from
-2 to 2
Parameters
----------
Returns
-------
'''
x = np.float64(np.abs(x))/2.0*pi
return np.piecewise(x,[x<=pi],[lambda x:(np.cos(x)+1)/4.0])
def stabilize(td):
"""Compensate for motion of the ATIS sensor during recording of the Neuromorphic datasets
Applies to the N-MNIST and N-Caltech101 datasets.
The image motion is originally induced by egorotation of the ATIS sensor
td: eventvision.Events
"""
assert isinstance(td, ev.Events)
def correct_saccade1(data):
data.x -= np.rint(3.5 * data.ts / 105e3).astype(np.uint16)
data.y -= np.rint(7 * data.ts / 105e3).astype(np.uint16)
return data
def correct_saccade2(data):
data.x -= np.rint(3.5 + 3.5 * (data.ts - 105e3) / 105e3).astype(np.uint16)
data.y -= np.rint(7 - 7 * (data.ts - 105e3) / 105e3).astype(np.uint16)
return data
def correct_saccade3(data):
data.x -= np.rint(7 - 7 * (data.ts - 210e3) / 105e3).astype(np.uint16)
return data
copy = np.piecewise(td.data,\
[td.data.ts <= 105e3, (td.data.ts > 105e3) & (td.data.ts <= 210e3), (td.data.ts > 210e3)],\
[correct_saccade1, correct_saccade2, correct_saccade3]).view(np.recarray)
# after saccades, we might end up with invalid x and y values, have to
# correct these
x_vals = copy.x
y_vals = copy.y
copy.x = np.piecewise(x_vals,\
[x_vals >= 65000, (x_vals < 65000) & (x_vals >= td.width), x_vals < td.width],\
[0, td.width - 1, lambda x: x])
copy.y = np.piecewise(y_vals,\
[y_vals >= 65000, (y_vals < 65000) & (y_vals >= td.height), y_vals < td.height],\
[0, td.height - 1, lambda y: y])
return copy
def show_em(self):
"""Displays the EM events (grayscale ATIS events)"""
frame_length = 24e3
t_max = self.data.ts[-1]
frame_start = self.data[0].ts
frame_end = self.data[0].ts + frame_length
max_val = 1.16e5
min_val = 1.74e3
val_range = max_val - min_val
thr = np.rec.array(None, dtype=[('valid', np.bool_), ('low', np.uint64), ('high', np.uint64)], shape=(self.height, self.width))
thr.valid.fill(False)
thr.low.fill(frame_start)
thr.high.fill(0)
def show_em_frame(frame_data):
"""Prepare and show a single frame of em data to be shown"""
for datum in np.nditer(frame_data):
ts_val = datum['ts'].item(0)
thr_data = thr[datum['y'].item(0), datum['x'].item(0)]
if datum['p'].item(0) == 0:
thr_data.valid = 1
thr_data.low = ts_val
elif thr_data.valid == 1:
thr_data.valid = 0
thr_data.high = ts_val - thr_data.low
img = 255 * (1 - (thr.high - min_val) / (val_range))
#thr_h = cv2.adaptiveThreshold(thr_h, 255,
#cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
img = np.piecewise(img, [img <= 0, (img > 0) & (img < 255), img >= 255], [0, lambda x: x, 255])
img = img.astype('uint8')
cv2.imshow('img', img)
cv2.waitKey(1)
while frame_start < t_max:
#with timer.Timer() as em_playback_timer:
frame_data = self.data[(self.data.ts >= frame_start) & (self.data.ts < frame_end)]
show_em_frame(frame_data)
frame_start = frame_end + 1
frame_end += frame_length + 1
#print 'showing em frame took %s seconds' %em_playback_timer.secs
cv2.destroyAllWindows()
return
def show_td(self, wait_delay=1):
"""Displays the TD events (change detection ATIS or DVS events)
waitDelay: milliseconds
"""
frame_length = 24e3
t_max = self.data.ts[-1]
frame_start = self.data[0].ts
frame_end = self.data[0].ts + frame_length
td_img = np.ones((self.height, self.width), dtype=np.uint8)
while frame_start < t_max:
frame_data = self.data[(self.data.ts >= frame_start) & (self.data.ts < frame_end)]
if frame_data.size > 0:
td_img.fill(128)
#with timer.Timer() as em_playback_timer:
for datum in np.nditer(frame_data):
td_img[datum['y'].item(0), datum['x'].item(0)] = datum['p'].item(0)
#print 'prepare td frame by iterating events took %s seconds'
#%em_playback_timer.secs
td_img = np.piecewise(td_img, [td_img == 0, td_img == 1, td_img == 128], [0, 255, 128])
cv2.imshow('img', td_img)
cv2.waitKey(wait_delay)
frame_start = frame_end + 1
frame_end = frame_end + frame_length + 1
cv2.destroyAllWindows()
return