def process_failure(name):
name = name.replace("mask","truth")
name2 = name.replace("truth","")
image,_,_ = image_read_write.load_itk_image(name2)
#image_cropped = image[:,120:420,60:460]
image_mask = np.zeros(image.shape)
center = 256
cc,rr = circle(center+20,center,160)
image_mask[:,cc,rr] = 1
image[image>threshold]=0
image[image!=0]=1
image = image*image_mask
#image_cropped[image_cropped>threshold]=0
#image_cropped[image_cropped!=0]=1
kernel20 = np.zeros((15,15))
cc,rr = circle(7,7,8)
kernel20[cc,rr]=1
image = binary_closing(image, [kernel20],1)
#image[:,:,:]=0
#image[:,120:420,60:460]=image_cropped
truth,_,_ = image_read_write.load_itk_image(name)
print evaluator.calculate_dice(image,truth,name)
image = np.array(image,dtype=np.int8)
#LoadImages.save_itk(image,name)
python类binary_closing()的实例源码
def process_failure(name):
name = name.replace("mask","truth")
name2 = name.replace("truth","")
image,_,_ = image_read_write.load_itk_image(name2)
#image_cropped = image[:,120:420,60:460]
image_mask = np.zeros(image.shape)
center = 256
cc,rr = circle(center+20,center,160)
image_mask[:,cc,rr] = 1
image[image>threshold]=0
image[image!=0]=1
image = image*image_mask
#image_cropped[image_cropped>threshold]=0
#image_cropped[image_cropped!=0]=1
kernel20 = np.zeros((15,15))
cc,rr = circle(7,7,8)
kernel20[cc,rr]=1
image = binary_closing(image, [kernel20],1)
#image[:,:,:]=0
#image[:,120:420,60:460]=image_cropped
truth,_,_ = image_read_write.load_itk_image(name)
print evaluator.calculate_dice(image,truth,name)
image = np.array(image,dtype=np.int8)
#LoadImages.save_itk(image,name)
def find_facade_cuts(facade_sig, dilation_amount=60):
edges = facade_sig > facade_sig.mean() + facade_sig.std()
edges = binary_closing(edges, structure=np.ones(dilation_amount))
run, start, val = run_length_encode(edges)
result = []
for s, e in zip(start[val], start[val] + run[val]):
result.append(s + facade_sig[s:e].argmax())
result = [0] + result + [len(facade_sig) - 1]
result = np.unique(result)
return np.array(result)
def process_image(name, do_closing, closing_structure):
image_train,_,_ = image_read_write.load_itk_image(name)
name = name.replace("mask","truth")
image_truth,_,_ = image_read_write.load_itk_image(name)
truth = np.zeros(image_truth.shape, dtype=np.uint8)
truth[image_truth >0]=1
if do_closing:
image_train = binary_closing(image_train, closing_structure,1)
image_train = binary_closing(image_train, [[[1]],[[1]],[[1]],[[1]],[[1]]],1)
score = calculate_dice(image_train,truth, name)
return score
def closed(self, structure, iterations=1):
"""
This function ...
:param structure:
:return:
"""
data = ndimage.binary_closing(self, structure, iterations)
# Return the new mask
#data, name=None, description=None
return Mask(data, name=self.name, description=self.description)
# -----------------------------------------------------------------
def closed(self, structure, iterations=1):
"""
This function ...
:param structure:
:return:
"""
data = ndimage.binary_closing(self, structure, iterations)
# Return the new mask
#data, name=None, description=None
return Mask(data, name=self.name, description=self.description)
# -----------------------------------------------------------------
def localization(x, y):
"""Simple post-processing and get IVDs positons.
Return:
positons: calculated by `ndimage.measurements.center_of_mass`
y: after fill holes and remove small objects.
"""
labels, nums = label(y, return_num=True)
areas = np.array([prop.filled_area for prop in regionprops(labels)])
assert nums >= 7, 'Fail in this test, should detect at least seven regions.'
# Segment a joint region which should be separate (if any).
while np.max(areas) > 10000:
y = ndimage.binary_opening(y, structure=np.ones((3, 3, 3)))
areas = np.array([prop.filled_area for prop in regionprops(label(y))])
# Remove small objects.
threshold = sorted(areas, reverse=True)[7]
y = morphology.remove_small_objects(y, threshold + 1)
# Fill holes.
y = ndimage.binary_closing(y, structure=np.ones((3, 3, 3)))
y = morphology.remove_small_holes(y, min_size=512, connectivity=3)
positions = ndimage.measurements.center_of_mass(x, label(y), range(1, 8))
return np.array(positions), y
def main(args):
if args.threshold is None:
print("Please provide a binarization threshold")
return 1
data, hdr = read(args.input, inc_header=True)
mask = data >= args.threshold
if args.minvol is not None:
mask = binary_volume_opening(mask, args.minvol)
if args.fill:
mask = binary_fill_holes(mask)
if args.extend is not None and args.extend > 0:
if args.relion:
se = binary_sphere(args.extend, False)
mask = binary_dilation(mask, structure=se, iterations=1)
else:
dt = distance_transform_edt(~mask)
mask = mask | (dt <= args.edge_width)
if args.close:
se = binary_sphere(args.extend, False)
mask = binary_closing(mask, structure=se, iterations=1)
final = mask.astype(np.single)
if args.edge_width is not None:
dt = distance_transform_edt(~mask) # Compute *outward* distance transform of mask.
idx = (dt <= args.edge_width) & (dt > 0) # Identify edge points by distance from mask.
x = np.arange(1, args.edge_width + 1) # Domain of the edge profile.
if "sin" in args.edge_profile:
y = np.sin(np.linspace(np.pi/2, 0, args.edge_width + 1)) # Range of the edge profile.
f = interp1d(x, y[1:])
final[idx] = f(dt[idx]) # Insert edge heights interpolated at distance transform values.
write(args.output, final, psz=hdr["xlen"] / hdr["nx"])
return 0
def process_image(name, do_closing, closing_structure):
image_train,_,_ = image_read_write.load_itk_image(name)
name = name.replace("mask","truth")
image_truth,_,_ = image_read_write.load_itk_image(name)
truth = np.zeros(image_truth.shape, dtype=np.uint8)
truth[image_truth >0]=1
if do_closing:
image_train = binary_closing(image_train, closing_structure,1)
image_train = binary_closing(image_train, [[[1]],[[1]],[[1]],[[1]],[[1]]],1)
score = calculate_dice(image_train,truth, name)
return score
def run(self, ips, snap, img, para = None):
strc = np.ones((para['h'], para['w']), dtype=np.uint8)
ndimg.binary_closing(snap, strc, output=img)
img *= 255
def run(self, ips, imgs, para = None):
strc = np.ones((para['r'], para['r'], para['r']), dtype=np.uint8)
imgs[:] = ndimg.binary_closing(imgs, strc)
imgs *= 255
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