def image_gradient(in_file, snr, out_file=None):
"""Computes the magnitude gradient of an image using numpy"""
import os.path as op
import numpy as np
import nibabel as nb
from scipy.ndimage import gaussian_gradient_magnitude as gradient
if out_file is None:
fname, ext = op.splitext(op.basename(in_file))
if ext == '.gz':
fname, ext2 = op.splitext(fname)
ext = ext2 + ext
out_file = op.abspath('{}_grad{}'.format(fname, ext))
imnii = nb.load(in_file)
data = imnii.get_data().astype(np.float32) # pylint: disable=no-member
datamax = np.percentile(data.reshape(-1), 99.5)
data *= 100 / datamax
grad = gradient(data, 3.0)
gradmax = np.percentile(grad.reshape(-1), 99.5)
grad *= 100.
grad /= gradmax
nb.Nifti1Image(grad, imnii.get_affine(), imnii.get_header()).to_filename(out_file)
return out_file
python类gaussian_gradient_magnitude()的实例源码
def getGradientVideo(I, IDims, sigma = 1):
GV = np.zeros(I.shape)
for i in range(I.shape[0]):
X = np.reshape(I[i, :], IDims)
G = rgb2gray(X, False)
GM = gaussian_gradient_magnitude(G, sigma)
F = np.zeros(IDims)
for k in range(F.shape[2]):
F[:, :, k] = GM
GV[i, :] = F.flatten()
return GV
Modules.py 文件源码
项目:apparent-age-gender-classification
作者: danielyou0230
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def debug_analyse_image_texture(file, sigma=1.0):
image = cv2.imread(file, 0)
blur = gaussian_filter(input=image, sigma=sigma)
cv2.imshow('Image', image - blur)
#analysis = ndimage.gaussian_gradient_magnitude(image, sigma=sigma)
#cv2.imshow('Analysis', analysis * 10)
cv2.waitKey(0)
cv2.destroyAllWindows()
##########################################
def getGradientVideo(I, IDims, sigma = 1):
GV = np.zeros(I.shape)
for i in range(I.shape[0]):
X = np.reshape(I[i, :], IDims)
G = rgb2gray(X, False)
GM = gaussian_gradient_magnitude(G, sigma)
F = np.zeros(IDims)
for k in range(F.shape[2]):
F[:, :, k] = GM
GV[i, :] = F.flatten()
return GV
def set_rocks_in_grad(self, elevation, landcover):
""" Modify the land cover to create rocks in the large gradient pixels
(large steepness)
Position arguments:
elevation -- Elevation image
landcover -- Landcover to become edited
Returned value:
Edited landcover
"""
# Compute the steepness of each pixel
grad = gaussian_gradient_magnitude(elevation, 1.0)
grad /= self.mercator.Resolution(self.__zoom)
# Get the mask of rock (with a smooth transition)
mask = (grad >= ROCK_STEEPNESS).astype(np.float)
mask = gaussian_filter(mask, 3.0)
# Blend the images
dtype = landcover.dtype
rock_image = np.zeros(landcover.shape, dtype=dtype)
rock_image[:,:] = ROCK_COLOR
for i in range(3):
rock_image[:,:,i] = (mask * rock_image[:,:,i]).astype(dtype)
landcover[:,:,i] = ((1.0 - mask) * landcover[:,:,i]).astype(dtype)
landcover += rock_image
return landcover
def headmsk_wf(name='HeadMaskWorkflow', use_bet=True):
"""
Computes a head mask as in [Mortamet2009]_.
.. workflow::
from mriqc.workflows.anatomical import headmsk_wf
wf = headmsk_wf()
"""
has_dipy = False
try:
from dipy.denoise import nlmeans
has_dipy = True
except ImportError:
pass
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityInterface(fields=['in_file', 'in_segm']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(fields=['out_file']), name='outputnode')
if use_bet or not has_dipy:
# Alternative for when dipy is not installed
bet = pe.Node(fsl.BET(surfaces=True), name='fsl_bet')
workflow.connect([
(inputnode, bet, [('in_file', 'in_file')]),
(bet, outputnode, [('outskin_mask_file', 'out_file')])
])
else:
from niworkflows.nipype.interfaces.dipy import Denoise
enhance = pe.Node(niu.Function(
input_names=['in_file'], output_names=['out_file'], function=_enhance), name='Enhance')
estsnr = pe.Node(niu.Function(
input_names=['in_file', 'seg_file'], output_names=['out_snr'],
function=_estimate_snr), name='EstimateSNR')
denoise = pe.Node(Denoise(), name='Denoise')
gradient = pe.Node(niu.Function(
input_names=['in_file', 'snr'], output_names=['out_file'], function=image_gradient), name='Grad')
thresh = pe.Node(niu.Function(
input_names=['in_file', 'in_segm'], output_names=['out_file'], function=gradient_threshold),
name='GradientThreshold')
workflow.connect([
(inputnode, estsnr, [('in_file', 'in_file'),
('in_segm', 'seg_file')]),
(estsnr, denoise, [('out_snr', 'snr')]),
(inputnode, enhance, [('in_file', 'in_file')]),
(enhance, denoise, [('out_file', 'in_file')]),
(estsnr, gradient, [('out_snr', 'snr')]),
(denoise, gradient, [('out_file', 'in_file')]),
(inputnode, thresh, [('in_segm', 'in_segm')]),
(gradient, thresh, [('out_file', 'in_file')]),
(thresh, outputnode, [('out_file', 'out_file')])
])
return workflow
def gradient_threshold(in_file, in_segm, thresh=1.0, out_file=None):
""" Compute a threshold from the histogram of the magnitude gradient image """
import os.path as op
import numpy as np
import nibabel as nb
from scipy import ndimage as sim
struc = sim.iterate_structure(sim.generate_binary_structure(3, 2), 2)
if out_file is None:
fname, ext = op.splitext(op.basename(in_file))
if ext == '.gz':
fname, ext2 = op.splitext(fname)
ext = ext2 + ext
out_file = op.abspath('{}_gradmask{}'.format(fname, ext))
imnii = nb.load(in_file)
hdr = imnii.get_header().copy()
hdr.set_data_dtype(np.uint8) # pylint: disable=no-member
data = imnii.get_data().astype(np.float32)
mask = np.zeros_like(data, dtype=np.uint8) # pylint: disable=no-member
mask[data > 15.] = 1
segdata = nb.load(in_segm).get_data().astype(np.uint8)
segdata[segdata > 0] = 1
segdata = sim.binary_dilation(segdata, struc, iterations=2, border_value=1).astype(np.uint8) # pylint: disable=no-member
mask[segdata > 0] = 1
mask = sim.binary_closing(mask, struc, iterations=2).astype(np.uint8) # pylint: disable=no-member
# Remove small objects
label_im, nb_labels = sim.label(mask)
artmsk = np.zeros_like(mask)
if nb_labels > 2:
sizes = sim.sum(mask, label_im, list(range(nb_labels + 1)))
ordered = list(reversed(sorted(zip(sizes, list(range(nb_labels + 1))))))
for _, label in ordered[2:]:
mask[label_im == label] = 0
artmsk[label_im == label] = 1
mask = sim.binary_fill_holes(mask, struc).astype(np.uint8) # pylint: disable=no-member
nb.Nifti1Image(mask, imnii.get_affine(), hdr).to_filename(out_file)
return out_file