def opening(self, structure, iterations=1):
"""
This function ...
:param structure:
:param iterations:
:return:
"""
data = ndimage.binary_opening(self, structure, iterations)
# Return the new mask
#data, name=None, description=None
return Mask(data, name=self.name, description=self.description)
# -----------------------------------------------------------------
python类binary_opening()的实例源码
def opening(self, structure, iterations=1):
"""
This function ...
:param structure:
:param iterations:
:return:
"""
data = ndimage.binary_opening(self, structure, iterations)
# Return the new mask
#data, name=None, description=None
return Mask(data, name=self.name, description=self.description)
# -----------------------------------------------------------------
def _prepare_mask(mask, label, erode=True):
fgmask = mask.copy()
if np.issubdtype(fgmask.dtype, np.integer):
if isinstance(label, string_types):
label = FSL_FAST_LABELS[label]
fgmask[fgmask != label] = 0
fgmask[fgmask == label] = 1
else:
fgmask[fgmask > .95] = 1.
fgmask[fgmask < 1.] = 0
if erode:
# Create a structural element to be used in an opening operation.
struc = nd.generate_binary_structure(3, 2)
# Perform an opening operation on the background data.
fgmask = nd.binary_opening(fgmask, structure=struc).astype(np.uint8)
return fgmask
def get_centers_of_mass_from_blobs(segmentation_layer, iterations=3):
"""
Determine the centers of each object in an image
::param segmentation_layer: NxM ndarray image mask of all target objects
::param iterations: threshold for removal of small non-target objects
::return centers_of_mass: a np ndarray of x,y coordinates for the center of each target object
"""
segmentation_layer = ndimage.binary_opening(segmentation_layer, iterations=iterations) # remove small objects
labels, label_number = ndimage.measurements.label(segmentation_layer) # label remaining blobs
centers_of_mass = np.zeros((label_number, 2))
for i in range(label_number):
idx = np.where(labels == i+1) # calculate the center of mass for each blob
centers_of_mass[i, 1] = np.mean(idx[1].astype(float)) # must be float
centers_of_mass[i, 0] = np.mean(idx[0].astype(float)) # must be float
return centers_of_mass
def morphological_opening_background(x):
# Compute an opening, which is the combination of an erosion and a dilation (morphological operators).
for i in range(x.shape[0]):
background_predictions = x[i, BACKGROUND_CLASS, :, :, :]
binarized_predictions = np.array(background_predictions > 0, dtype=np.int32)
opened_predictions = binary_opening(binarized_predictions, np.ones((MORPHOLOGICAL_STRUCTURE_SIZE,) * 3))
x[i, BACKGROUND_CLASS, :, :, :] *= opened_predictions
return x
def granulometry(data, sizes=None):
s = max(data.shape)
if sizes == None:
sizes = range(1, s/2, 2)
granulo = [ndimage.binary_opening(data, \
structure=disk_structure(n)).sum() for n in sizes]
return granulo
def mask_binary(imageHDU,LowestContour,selem):
map = imageHDU[0].data
mask = binary_opening(map > LowestContour, selem)
MaskedMap = mask*map
imageHDU[0].data = MaskedMap
return imageHDU, mask
def _run_interface(self, runtime):
in_file = nb.load(self.inputs.in_file)
data = in_file.get_data()
mask = np.zeros_like(data, dtype=np.uint8)
mask[data <= 0] = 1
# Pad one pixel to control behavior on borders of binary_opening
mask = np.pad(mask, pad_width=(1,), mode='constant', constant_values=1)
# Remove noise
struc = nd.generate_binary_structure(3, 2)
mask = nd.binary_opening(mask, structure=struc).astype(
np.uint8)
# Remove small objects
label_im, nb_labels = nd.label(mask)
if nb_labels > 2:
sizes = nd.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
# Un-pad
mask = mask[1:-1, 1:-1, 1:-1]
# If mask is small, clean-up
if mask.sum() < 500:
mask = np.zeros_like(mask, dtype=np.uint8)
out_img = in_file.__class__(mask, in_file.affine, in_file.header)
out_img.header.set_data_dtype(np.uint8)
out_file = fname_presuffix(self.inputs.in_file,
suffix='_rotmask', newpath='.')
out_img.to_filename(out_file)
self._results['out_file'] = out_file
return runtime
def artifact_mask(imdata, airdata, distance, zscore=10.):
"""Computes a mask of artifacts found in the air region"""
from statsmodels.robust.scale import mad
if not np.issubdtype(airdata.dtype, np.integer):
airdata[airdata < .95] = 0
airdata[airdata > 0.] = 1
bg_img = imdata * airdata
if np.sum((bg_img > 0).astype(np.uint8)) < 100:
return np.zeros_like(airdata)
# Find the background threshold (the most frequently occurring value
# excluding 0)
bg_location = np.median(bg_img[bg_img > 0])
bg_spread = mad(bg_img[bg_img > 0])
bg_img[bg_img > 0] -= bg_location
bg_img[bg_img > 0] /= bg_spread
# Apply this threshold to the background voxels to identify voxels
# contributing artifacts.
qi1_img = np.zeros_like(bg_img)
qi1_img[bg_img > zscore] = 1
qi1_img[distance < .10] = 0
# Create a structural element to be used in an opening operation.
struc = nd.generate_binary_structure(3, 1)
qi1_img = nd.binary_opening(qi1_img, struc).astype(np.uint8)
qi1_img[airdata <= 0] = 0
return qi1_img
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 run(self, ips, snap, img, para = None):
strc = np.ones((para['h'], para['w']), dtype=np.uint8)
ndimg.binary_opening(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_opening(imgs, strc)
imgs *= 255
def plot_dust_overlay(nh3_image_fits,h2_image_fits,region,plot_param,v_min,v_max,maskLim,obsMaskFits):
text_size = 14
b18_text_size = 20
# Contour parameters (currently NH3 moment 0)
cont_color='black'
cont_lw = 0.6
cont_levs=2**np.arange( 0,20)*plot_param['w11_step']
# Masking of small (noisy) regions
selem = np.array([[0,1,0],[1,1,1],[0,1,0]])
LowestContour = cont_levs[0]*0.5
w11_hdu = fits.open(nh3_image_fits)
map = w11_hdu[0].data
mask = binary_opening(map > LowestContour, selem)
MaskedMap = mask*map
w11_hdu[0].data = MaskedMap
# Labels
if region == 'B18':
label_colour = 'white'
text_size = b18_text_size
else:
label_colour = 'white'
fig=aplpy.FITSFigure(h2_image_fits,figsize=(plot_param['size_x'], plot_param['size_y']))
fig.show_colorscale(cmap='hot',vmin=v_min,vmax=v_max,stretch='log',vmid=v_min-v_min*plot_param['vmid_scale'])
fig.set_nan_color('0.95')
# Observations mask contour
fig.show_contour(obsMaskFits,colors='white',levels=1,linewidths=1.5)
# NH3 moment contours
fig.show_contour(w11_hdu,colors=cont_color,levels=cont_levs,linewidths=cont_lw)
fig.axis_labels.set_font(family='sans_serif',size=text_size)
# Ticks
fig.tick_labels.set_font(family='sans_serif',size=text_size)
fig.ticks.set_color('white')
fig.tick_labels.set_xformat('hh:mm:ss')
fig.tick_labels.set_style('colons')
fig.tick_labels.set_yformat('dd:mm')
# Scale bar
# magic line of code to obtain scale in arcsec obtained from
# http://www.astropy.org/astropy-tutorials/Quantities.html
ang_sep = (plot_param['scalebar_size'].to(u.au)/plot_param['distance']).to(u.arcsec, equivalencies=u.dimensionless_angles())
fig.add_scalebar(ang_sep.to(u.degree))
fig.scalebar.set_font(family='sans_serif',size=text_size)
fig.scalebar.set_corner(plot_param['scalebar_pos'])
fig.scalebar.set(color='white')
fig.scalebar.set_label('{0:4.2f}'.format(plot_param['scalebar_size']))
fig.add_label(plot_param['label_xpos'], plot_param['label_ypos'],
'{0}\n{1}'.format(region,'500 $\mu$m'),
relative=True, color=label_colour,
horizontalalignment=plot_param['label_align'],
family='sans_serif',size=text_size)
fig.save( 'figures/{0}_continuum_image.pdf'.format(region),adjust_bbox=True,dpi=200)#, bbox_inches='tight')
fig.close()
def plot_abundance(nh3_cont_fits,nh3_col_hdu,h2_col_hdu,region,plot_pars,maskLim,obsMaskFits):
text_size = 14
b18_text_size = 20
if region == 'B18':
text_size = b18_text_size
# Get protostellar locations
ra_prot, de_prot = get_prot_loc(region)
# Contour parameters (currently NH3 moment 0)
cont_color='0.6'
cont_lw = 0.6
cont_levs=2**np.arange( 0,20)*plot_param['w11_step']
# Calculate abundance
log_xnh3 = nh3_col_hdu[0].data - np.log10(h2_col_hdu.data)
log_xnh3_hdu = fits.PrimaryHDU(log_xnh3,nh3_col_hdu[0].header)
log_xnh3_hdu.writeto('../testing/{0}/parameterMaps/{0}_XNH3_{1}.fits'.format(region,file_extension),clobber=True)
fig=aplpy.FITSFigure(log_xnh3_hdu,figsize=(plot_param['size_x'], plot_param['size_y']))
fig.show_colorscale(cmap='YlOrRd_r',vmin=plot_param['xnh3_lim'][0],vmax=plot_param['xnh3_lim'][1])
#fig.set_nan_color('0.95')
# Observations mask contour
fig.show_contour(obsMaskFits,colors='white',levels=1,linewidths=1.5)
# NH3 moment contours
# Masking of small (noisy) regions
selem = np.array([[0,1,0],[1,1,1],[0,1,0]])
LowestContour = cont_levs[0]*0.5
w11_hdu = fits.open(nh3_cont_fits)
map = w11_hdu[0].data
mask = binary_opening(map > LowestContour, selem)
MaskedMap = mask*map
w11_hdu[0].data = MaskedMap
fig.show_contour(w11_hdu,colors=cont_color,levels=cont_levs,linewidths=cont_lw)
# Ticks
fig.ticks.set_color('black')
fig.tick_labels.set_font(family='sans_serif',size=text_size)
fig.tick_labels.set_xformat('hh:mm:ss')
fig.tick_labels.set_style('colons')
fig.tick_labels.set_yformat('dd:mm')
# Scale bar
ang_sep = (plot_param['scalebar_size'].to(u.au)/plot_param['distance']).to(u.arcsec, equivalencies=u.dimensionless_angles())
fig.add_colorbar()
fig.colorbar.show(box_orientation='horizontal', width=0.1, pad=0.0, location='top',
ticks=[-10,-9.5,-9,-8.5,-8,-7.5,-7,-6.5])
fig.colorbar.set_font(family='sans_serif',size=text_size)
fig.add_scalebar(ang_sep.to(u.degree))
fig.scalebar.set_font(family='sans_serif',size=text_size)
fig.scalebar.set_corner(plot_param['scalebar_pos'])
fig.scalebar.set(color='black')
fig.scalebar.set_label('{0:4.2f}'.format(plot_param['scalebar_size']))
label_colour = 'black'
fig.add_label(plot_param['label_xpos'], plot_param['label_ypos'],
'{0}\n{1}'.format(region,r'$\mathrm{log} \ X(\mathrm{NH}_3)$'),
relative=True, color=label_colour,
horizontalalignment=plot_param['label_align'],
family='sans_serif',size=text_size)
fig.save( 'figures/{0}_xnh3_image.pdf'.format(region),adjust_bbox=True,dpi=200)#, bbox_inches='tight')
# Add protostars
fig.show_markers(ra_prot,de_prot,marker='*',s=50,
c='white',edgecolors='black',linewidth=0.5,zorder=4)
fig.save( 'figures/{0}_xnh3_image_prot.pdf'.format(region),adjust_bbox=True,dpi=200)
fig.close()