本文整理汇总了Python中scipy.signal.convolve2d方法的典型用法代码示例。如果您正苦于以下问题:Python signal.convolve2d方法的具体用法?Python signal.convolve2d怎么用?Python signal.convolve2d使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.signal
的用法示例。
在下文中一共展示了signal.convolve2d方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_diffraction_test_image
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def get_diffraction_test_image(self, dtype=np.float32):
image_x, image_y = self.image_x, self.image_y
cx, cy = image_x / 2, image_y / 2
image = np.zeros((image_y, image_x), dtype=np.float32)
iterator = zip(self._x_list, self._y_list, self._intensity_list)
for x, y, i in iterator:
if self.diff_intensity_reduction is not False:
dr = np.hypot(x - cx, y - cy)
i = self._get_diff_intensity_reduction(dr, i)
image[y, x] = i
disk = morphology.disk(self.disk_r, dtype=dtype)
image = convolve2d(image, disk, mode="same")
if self.rotation != 0:
image = rotate(image, self.rotation, reshape=False)
if self.blur != 0:
image = gaussian_filter(image, self.blur)
if self._background_lorentz_width is not False:
image += self._get_background_lorentz()
if self.intensity_noise is not False:
noise = np.random.random((image_y, image_x)) * self.intensity_noise
image += noise
return image
示例2: init_parameters
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def init_parameters(self):
# Init weights
if self.init_method == 'x': # Xavier
torch.nn.init.xavier_uniform_(self.weight)
elif self.init_method == 'k': # Kaiming
torch.nn.init.kaiming_uniform_(self.weight)
elif self.init_method == 'p': # Poisson
mu=self.kernel_size[0]/2
dist = poisson(mu)
x = np.arange(0, self.kernel_size[0])
y = np.expand_dims(dist.pmf(x),1)
w = signal.convolve2d(y, y.transpose(), 'full')
w = torch.Tensor(w).type_as(self.weight)
w = torch.unsqueeze(w,0)
w = torch.unsqueeze(w,1)
w = w.repeat(self.out_channels, 1, 1, 1)
w = w.repeat(1, self.in_channels, 1, 1)
self.weight.data = w + torch.rand(w.shape)
# Init bias
self.bias = torch.nn.Parameter(torch.zeros(self.out_channels)+0.01)
# Non-negativity enforcement class
示例3: navg_layer
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1,
padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
weights = navg.weight
if initalizer == 'x': # Xavier
torch.nn.init.xavier_uniform(weights)
elif initalizer == 'k':
torch.nn.init.kaiming_uniform(weights)
elif initalizer == 'p':
mu=kernel_size[0]/2
dist = poisson(mu)
x = np.arange(0, kernel_size[0])
y = np.expand_dims(dist.pmf(x),1)
w = signal.convolve2d(y, y.transpose(), 'full')
w = torch.FloatTensor(w).cuda()
w = torch.unsqueeze(w,0)
w = torch.unsqueeze(w,1)
w = w.repeat(out_channels, 1, 1, 1)
w = w.repeat(1, in_channels, 1, 1)
weights.data = w + torch.rand(w.shape).cuda()
return navg
示例4: py_conv_scipy
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def py_conv_scipy(img, kern, mode, subsample):
assert img.shape[1] == kern.shape[1]
if mode == 'valid':
outshp = (img.shape[0], kern.shape[0],
img.shape[2] - kern.shape[2] + 1,
img.shape[3] - kern.shape[3] + 1)
else:
outshp = (img.shape[0], kern.shape[0],
img.shape[2] + kern.shape[2] - 1,
img.shape[3] + kern.shape[3] - 1)
out = numpy.zeros(outshp, dtype='float32')
for b in xrange(out.shape[0]):
for k in xrange(out.shape[1]):
for s in xrange(img.shape[1]):
#convolve2d or correlate
out[b, k, :, :] += convolve2d(img[b, s, :, :],
kern[k, s, :, :],
mode)
return out[:, :, ::subsample[0], ::subsample[1]]
示例5: test_marginal_convolution
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def test_marginal_convolution():
rng = np.random.RandomState(42)
convolution_filters = rng.randn(6, 4, 5).astype(np.float32)
images = np.arange(
3 * 2 * 10 * 10).reshape(3, 2, 10, 10).astype(np.float32)
for border_mode in ['full', 'valid']:
conv = MarginalConvolution(convolution_filters,
border_mode=border_mode,
activation=None)
conv_func = theano.function([conv.input_],
conv.expression_)
convolved = conv_func(images)
convolutions = np.array([
[[convolve2d(img, convolution_filter,
mode=border_mode)
for convolution_filter in convolution_filters]
for img in imgs]
for imgs in images])
convolutions = convolutions.reshape(images.shape[0], -1,
convolutions.shape[-2],
convolutions.shape[-1])
assert_array_almost_equal(convolved, convolutions, decimal=3)
示例6: gridsmooth
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def gridsmooth(Z, span):
""" Smooths values on 2D rectangular grid
"""
import warnings
warnings.filterwarnings('ignore')
x = np.linspace(-2.*span, 2.*span, 2.*span + 1.)
y = np.linspace(-2.*span, 2.*span, 2.*span + 1.)
(X, Y) = np.meshgrid(x, y)
mu = np.array([0., 0.])
sigma = np.diag([span, span])**2.
F = gauss2(X, Y, mu, sigma)
F = F/np.sum(F)
W = np.ones(Z.shape)
Z = _signal.convolve2d(Z, F, 'same')
W = _signal.convolve2d(W, F, 'same')
Z = Z/W
return Z
示例7: test_fillvalue_deprecations
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def test_fillvalue_deprecations(self):
# Deprecated 2017-07, scipy version 1.0.0
with suppress_warnings() as sup:
sup.filter(np.ComplexWarning, "Casting complex values to real")
r = sup.record(DeprecationWarning, "could not cast `fillvalue`")
convolve2d([[1]], [[1, 2]], fillvalue=1j)
assert_(len(r) == 1)
warnings.filterwarnings(
"error", message="could not cast `fillvalue`",
category=DeprecationWarning)
assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
fillvalue=1j)
with suppress_warnings():
warnings.filterwarnings(
"always", message="`fillvalue` must be scalar or an array ",
category=DeprecationWarning)
assert_warns(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
fillvalue=[1, 2])
warnings.filterwarnings(
"error", message="`fillvalue` must be scalar or an array ",
category=DeprecationWarning)
assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
fillvalue=[1, 2])
示例8: test_valid_mode2
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def test_valid_mode2(self):
# See gh-5897
e = [[1, 2, 3], [3, 4, 5]]
f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]]
expected = [[62, 80, 98, 116, 134]]
out = convolve2d(e, f, 'valid')
assert_array_equal(out, expected)
out = convolve2d(f, e, 'valid')
assert_array_equal(out, expected)
e = [[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]]
f = [[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]]
expected = [[27 - 1j, 46. + 2j]]
out = convolve2d(e, f, 'valid')
assert_array_equal(out, expected)
# See gh-5897
out = convolve2d(f, e, 'valid')
assert_array_equal(out, expected)
示例9: extract_sift_patches
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def extract_sift_patches(self, image, grid_h, grid_w):
"""extracts the sift descriptor of patches
in positions (grid_h, grid_w) in the image"""
h, w = image.shape
n_patches = grid_h.size
feat_arr = np.zeros((n_patches, n_samples * n_angles))
# calculate gradient
gh, gw = gen_dgauss(self.sigma)
ih = signal.convolve2d(image, gh, mode='same')
iw = signal.convolve2d(image, gw, mode='same')
i_mag = np.sqrt(ih ** 2 + iw ** 2)
i_theta = np.arctan2(ih, iw)
i_orient = np.zeros((n_angles, h, w))
for i in range(n_angles):
i_orient[i] = i_mag * np.maximum(np.cos(i_theta - angles[i]) ** alpha, 0)
for i in range(n_patches):
curr_feature = np.zeros((n_angles, n_samples))
for j in range(n_angles):
curr_feature[j] = np.dot(self.weights, i_orient[j, grid_h[i]:grid_h[i] + self.ps,
grid_w[i]:grid_w[i] + self.ps].flatten())
feat_arr[i] = curr_feature.flatten()
# feaArr contains each descriptor in a row
feat_arr = self.normalize_sift(feat_arr)
return feat_arr
示例10: CFAR_2D
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def CFAR_2D(X, fw, gw, thresh = None):
'''constant false alarm rate target detection
Parameters:
fw: CFAR kernel width
gw: number of guard cells
thresh: detection threshold
Returns:
X with CFAR filter applied'''
Tfilt = np.ones((fw,fw))/(fw**2 - gw**2)
e1 = (fw - gw)//2
e2 = fw - e1 + 1
Tfilt[e1:e2, e1:e2] = 0
CR = normalize(X) / (signal.convolve2d(X, Tfilt, mode='same', boundary='wrap') + 1e-10)
if thresh is None:
return CR
else:
return CR > thresh
示例11: compute_pairwise_distribution
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def compute_pairwise_distribution(joint, cond_j):
"""
This computes a single histogram for a pair of (joint, cond_joint), and applies gaussian smoothing
:param joint: e.g. 'lsho'
:param cond_j: e.g. 'nose'
:return: 120 x 180 pairwise distribution
"""
hp_height = y_train.shape[1]
hp_width = y_train.shape[2]
pd = np.zeros([hp_height * 2, hp_width * 2]) # the pairwise distribution is twice the size of the heat map
# print(pd.shape)
for i in range(y_train.shape[0]): # for every single image, we note the distance between the joint and cond_j
img_j = y_train[i, :, :, joint_ids.index(joint)]
img_cj = y_train[i, :, :, joint_ids.index(cond_j)]
xj, yj = np.where(img_j == np.max(img_j))
xcj, ycj = np.where(img_cj == np.max(img_cj))
pd[hp_height + (xj - xcj), hp_width + (yj - ycj)] += 1 # count for the histgram
pd = pd / np.float32(np.sum(pd))
pd = signal.convolve2d(pd, kernel, mode='same', boundary='fill', fillvalue=0)
return pd
示例12: update_rows_and_gol_state
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def update_rows_and_gol_state(self):
# Update `rows` (the state of the 2D cellular automaton).
rule_index = signal.convolve2d(self.row[None, :],
self.row_neighbors[None, :],
mode='same', boundary='wrap')
self.row = self.rule_kernel[rule_index[0]]
transfer_row = self.rows[:1]
self.rows = np.concatenate((
self.rows[1:],
self.row[None, self.row_padding:-self.row_padding]
))
# Update `gol_state` (the state of the 3D cellular automaton).
num_neighbors = signal.convolve2d(self.gol_state, self.gol_neighbors,
mode='same', boundary='wrap')
self.gol_state = np.logical_or(num_neighbors == 3,
np.logical_and(num_neighbors == 2,
self.gol_state)
).astype(np.uint8)
self.gol_state = np.concatenate((
np.zeros((1, self.gol_state_width), np.uint8),
self.gol_state[1:-1],
transfer_row
))
示例13: _execute
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def _execute(self, x):
is_2d = x.ndim==2
output_shape, input_shape = self._output_shape, self._input_shape
filters = self.filters
nfilters = filters.shape[0]
# XXX depends on convolution
y = numx.empty((x.shape[0], nfilters,
output_shape[0], output_shape[1]), dtype=self.dtype)
for n_im, im in enumerate(x):
if is_2d:
im = im.reshape(input_shape)
for n_flt, flt in enumerate(filters):
if self.approach == 'fft':
y[n_im,n_flt,:,:] = signal.fftconvolve(im, flt, mode=self.mode)
elif self.approach == 'linear':
y[n_im,n_flt,:,:] = signal.convolve2d(im, flt,
mode=self.mode,
boundary=self.boundary,
fillvalue=self.fillvalue)
# reshape if necessary
if self.output_2d:
y.resize((y.shape[0], self.output_dim))
return y
示例14: airy_convolve
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def airy_convolve(array,radius,kernel_radius=25):
kernel = generate_kernel(radius * SPECTRUM , kernel_radius)
out = np.zeros((array.shape[0],array.shape[1],3))
for i in range(3):
out[:,:,i] = convolve2d(array[:,:,i],kernel[:,:,i],mode='same',boundary='symm')
return out
示例15: kernelFromTrajectory
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import convolve2d [as 别名]
def kernelFromTrajectory(x):
h = 5 - log(rand()) / 0.15
h = round(min([h, 27])).astype(int)
h = h + 1 - h % 2
w = h
k = zeros((h, w))
xmin = min(x[0])
xmax = max(x[0])
ymin = min(x[1])
ymax = max(x[1])
xthr = arange(xmin, xmax, (xmax - xmin) / w)
ythr = arange(ymin, ymax, (ymax - ymin) / h)
for i in range(1, xthr.size):
for j in range(1, ythr.size):
idx = (
(x[0, :] >= xthr[i - 1])
& (x[0, :] < xthr[i])
& (x[1, :] >= ythr[j - 1])
& (x[1, :] < ythr[j])
)
k[i - 1, j - 1] = sum(idx)
if sum(k) == 0:
return
k = k / sum(k)
k = convolve2d(k, fspecial_gauss(3, 1), "same")
k = k / sum(k)
return k