def compute_gradient_magnitude(ima, method='scharr'):
"""Compute gradient magnitude of images.
Parameters
----------
ima : np.ndarray
First image, which is often the intensity image (eg. T1w).
method : string
Gradient computation method. Available options are 'scharr',
'sobel', 'prewitt', 'numpy'.
Returns
-------
gra_mag : np.ndarray
Second image, which is often the gradient magnitude image
derived from the first image
"""
if method == 'sobel': # magnitude scale is similar to numpy method
kernel = create_3D_kernel(operator=method)
gra = np.zeros(ima.shape + (kernel.shape[0],))
for d in range(kernel.shape[0]):
gra[..., d] = convolve(ima, kernel[d, ...])
# compute generic gradient magnitude with normalization
gra_mag = np.sqrt(np.sum(np.power(gra, 2.), axis=-1))
return gra_mag
elif method == 'prewitt':
kernel = create_3D_kernel(operator=method)
gra = np.zeros(ima.shape + (kernel.shape[0],))
for d in range(kernel.shape[0]):
gra[..., d] = convolve(ima, kernel[d, ...])
# compute generic gradient magnitude with normalization
gra_mag = np.sqrt(np.sum(np.power(gra, 2.), axis=-1))
return gra_mag
elif method == 'scharr':
kernel = create_3D_kernel(operator=method)
gra = np.zeros(ima.shape + (kernel.shape[0],))
for d in range(kernel.shape[0]):
gra[..., d] = convolve(ima, kernel[d, ...])
# compute generic gradient magnitude with normalization
gra_mag = np.sqrt(np.sum(np.power(gra, 2.), axis=-1))
return gra_mag
elif method == 'numpy':
gra = np.asarray(np.gradient(ima))
gra_mag = np.sqrt(np.sum(np.power(gra, 2.), axis=0))
return gra_mag
else:
print 'Gradient magnitude method is invalid!'
评论列表
文章目录