本文整理汇总了Python中scipy.ndimage.binary_fill_holes函数的典型用法代码示例。如果您正苦于以下问题:Python binary_fill_holes函数的具体用法?Python binary_fill_holes怎么用?Python binary_fill_holes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了binary_fill_holes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: binaryFillHoles
def binaryFillHoles(binarydata, kernel=np.ones((3, 3, 3))):
result = np.zeros_like(binarydata)
if kernel is None:
ndimage.binary_fill_holes(binarydata, output=result)
else:
ndimage.binary_fill_holes(binarydata, structure=kernel, output=result)
return result
开发者ID:tkuhlengel,项目名称:Fish,代码行数:9,代码来源:processing.py
示例2: obj_fill_holes
def obj_fill_holes(array, labelled=True):
"""
Fills holes within objects.
"""
if labelled:
fill = ndimage.binary_fill_holes(array > 0)
#holes = fill - array
else:
fill = ndimage.binary_fill_holes(array)
return fill
开发者ID:sixy6e,项目名称:stash,代码行数:11,代码来源:segmentation.py
示例3: pestFeatureExtraction
def pestFeatureExtraction(filename):
selem = disk(8)
image = data.imread(filename,as_grey=True)
thresh = threshold_otsu(image)
elevation_map = sobel(image)
markers = np.zeros_like(image)
if ((image<thresh).sum() > (image>thresh).sum()):
markers[image < thresh] = 1
markers[image > thresh] = 2
else:
markers[image < thresh] = 2
markers[image > thresh] = 1
segmentation = morphology.watershed(elevation_map, markers)
segmentation = dilation(segmentation-1, selem)
segmentation = ndimage.binary_fill_holes(segmentation)
segmentation = np.logical_not(segmentation)
image[segmentation]=0;
hist = np.histogram(image.ravel(),256,[0,1])
hist = list(hist[0])
hist[:] = [float(x) / (sum(hist) - hist[0]) for x in hist]
hist.pop(0)
features = np.empty( (1, len(hist)), 'float' )
a = np.array(list(hist))
f = a.astype('float')
features[0,:]=f[:]
return features
开发者ID:SPKhan,项目名称:sarai-pest-diseases,代码行数:34,代码来源:api.py
示例4: main
def main():
for file_path in glob.glob("/home/lucas/Downloads/Lucas/GSK 10uM/*.JPG"):
img = data.imread(file_path, as_grey=True)
img = transform.resize(img, [600, 600])
img_color = transform.resize(data.imread(file_path), [600, 600])
img[img >img.mean()-0.1] = 0
# io.imshow(img)
# io.show()
#
edges = canny(img)
bordas_fechadas = closing(img > 0.1, square(15)) # fechando gaps
fill_cells = ndi.binary_fill_holes(bordas_fechadas)
# io.imshow(fill_cells)
# io.show()
img_label = label(fill_cells, background=0)
n= 0
for x in regionprops(img_label):
if x.area < 2000 and x.area > 300:
n +=1
print x.area
minr, minc, maxr, maxc = x.bbox
try:
out_path_name = file_path.split("/")[-1].rstrip(".JPG")
io.imsave("out/cell_{}_pic_{}_area_{}.png".format(n, out_path_name, str(round(x.area))),img_color[minr-3: maxr+3, minc-3: maxc+3])
#io.show()
except:
pass
开发者ID:LucasSilvaFerreira,项目名称:egg_finder,代码行数:31,代码来源:microscopia_eggs.py
示例5: clean_by_area
def clean_by_area(self, binary_image):
image = binary_image.copy()
image = ndi.binary_fill_holes(image)
label_image = label(binary_image)
initial_label = regionprops(label_image[0, :, :])[0].label
for z in range(0, image.shape[0]):
regions = regionprops(label_image[z, :, :])
for region in regions:
if region.label != initial_label:
for coords in region.coords:
image[z, coords[0], coords[1]] = 0
for z in range(0, image.shape[0]):
label_image = label(image[z, :, :], connectivity=1)
regions = regionprops(label_image)
if len(regions) > 1:
max_area = np.max([r.area for r in regions])
for region in regions:
if region.centroid[1] > 120 and region.area < max_area:
for coords in region.coords:
image[z, coords[0], coords[1]] = 0
return image
开发者ID:elpisco,项目名称:hip-dysplasia,代码行数:25,代码来源:image_processing.py
示例6: segment
def segment(self, src):
ndsrc = src.ndarray / 255.
edges = canny(ndsrc,
# low_threshold=0.001,
# high_threshold=0.1,
# low_threshold=self.canny_low_threshold,
# high_threshold=self.canny_high_threshold,
sigma=self.canny_sigma)
filled = ndimage.binary_fill_holes(edges)
filled = invert(filled) * 255
# label_objects, _ = ndimage.label(filled)
# sizes = bincount(label_objects.ravel())
#
# mask_sizes = sizes > 1
# mask_sizes[0] = 0
# cleaned = mask_sizes[label_objects]
# cleaned = asarray(cleaned, 'uint8')
# cleaned = closing(cleaned, square(5))
# self._locate_helper(invert(cleaned), **kw)
nsrc = asarray(filled, 'uint8')
return nsrc
开发者ID:softtrainee,项目名称:arlab,代码行数:25,代码来源:edge.py
示例7: readBinIm
def readBinIm(path):
"""
desc:
Reads an image, converts to binary (0 for background, 1 for shape), and
fills any internal holes.
arguments:
path:
desc: The image path.
type: [str, unicode]
returns:
desc: An image array.
type: ndarray
"""
im = ndimage.imread(path, flatten=True)
i1 = np.where(im == 255)
i2 = np.where(im != 255)
im[i1] = 0
im[i2] = 1
im = ndimage.binary_fill_holes(im)
return im
开发者ID:lvanderlinden,项目名称:004,代码行数:25,代码来源:shape.py
示例8: get_segmented_lungs
def get_segmented_lungs(im):
binary = im < -320
cleared = clear_border(binary)
cleared=morph(cleared,5)
label_image = label(cleared)
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < areas[-2]:
for coordinates in region.coords:
label_image[coordinates[0], coordinates[1]] = 0
binary = label_image > 0
selem = disk(2)
binary = binary_erosion(binary, selem)
selem = disk(10)
binary = binary_closing(binary, selem)
edges = roberts(binary)
binary = ndi.binary_fill_holes(edges)
get_high_vals = binary == 0
im[get_high_vals] = 0
binary = morphology.dilation(binary,np.ones([5,5]))
return binary
开发者ID:skconsulting,项目名称:ild,代码行数:28,代码来源:data_roifull1.py
示例9: load_scenes
def load_scenes(filename):
zipped_scenes = []
print 'Working on: ' + filename
img = data.imread('scenes/' + filename, as_grey=True)
tmp = img
tmp = filter.canny(tmp, sigma=2.0)
tmp = ndimage.binary_fill_holes(tmp)
#tmp = morphology.dilation(tmp, morphology.disk(2))
tmp = morphology.remove_small_objects(tmp, 2000)
contours = measure.find_contours(tmp, 0.8)
ymin, xmin = contours[0].min(axis=0)
ymax, xmax = contours[0].max(axis=0)
if xmax - xmin > ymax - ymin:
xdest = 1000
ydest = 670
else:
xdest = 670
ydest = 1000
src = np.array(((0, 0), (0, ydest), (xdest, ydest), (xdest, 0)))
dst = np.array(((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)))
tform3 = tf.ProjectiveTransform()
tform3.estimate(src, dst)
warped = tf.warp(img, tform3, output_shape=(ydest, xdest))
tmp = filter.canny(warped, sigma=2.0)
tmp = morphology.dilation(tmp, morphology.disk(2))
descriptor_extractor.detect_and_extract(tmp)
obj_key = descriptor_extractor.keypoints
scen_desc = descriptor_extractor.descriptors
zipped_scenes.append([warped, scen_desc, obj_key, filename])
return zipped_scenes
开发者ID:gracz21,项目名称:KCK,代码行数:30,代码来源:image.py
示例10: applyMorphologicalCleaning
def applyMorphologicalCleaning(self, image):
"""
Applies a variety of morphological operations to improve the detection
of worms in the image.
Takes 0.030 s on MUSSORGSKY for a typical frame region
Takes 0.030 s in MATLAB too
"""
# start with worm == 1
image = image.copy()
segmentation.clear_border(image) # remove objects at edge (worm == 1)
# fix defects in the thresholding by closing with a worm-width disk
# worm == 1
wormSE = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
(self.wormDiskRadius+1,
self.wormDiskRadius+1))
imcl = cv2.morphologyEx(np.uint8(image), cv2.MORPH_CLOSE, wormSE)
imcl = np.equal(imcl, 1)
# fix defects by filling holes
imholes = ndimage.binary_fill_holes(imcl)
imcl = np.logical_or(imholes, imcl)
# fix barely touching regions
# majority with worm pixels == 1 (median filter same?)
imcl = nf.median_filter(imcl, footprint=[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# diag with worm pixels == 0
imcl = np.logical_not(bwdiagfill(np.logical_not(imcl)))
# open with worm pixels == 1
openSE = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
imcl = cv2.morphologyEx(np.uint8(imcl), cv2.MORPH_OPEN, openSE)
return np.equal(imcl, 1)
开发者ID:stephenhelms,项目名称:WormTracker,代码行数:31,代码来源:wormimageprocessor.py
示例11: segmentation
def segmentation(file_name):
data_x, data_y, data_z = get_data(file_name)
shape_x = len(np.unique(data_x))
shape_y = len(np.unique(data_y))
X = data_x.reshape(shape_x, shape_y)
Y = data_y.reshape(shape_x, shape_y)
Z = data_z.reshape(shape_x, shape_y)
markers = np.zeros_like(Z)
markers[Z < 0.15] = 1
markers[Z > 0.3] = 2
elevation_map = roberts(Z)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharex=True, sharey=True)
# ax.imshow(Z)
# ax.imshow(elevation_map, cmap=plt.cm.jet, interpolation='nearest')
segmentation = watershed(elevation_map, markers)
ax2.imshow(segmentation, interpolation='nearest')
# ax.axis('off')
# ax.set_title('segmentation')
segmentation = ndi.binary_fill_holes(segmentation - 1)
labeled_coins, _ = ndi.label(segmentation)
ax1.imshow(Z, cmap=plt.cm.gray, interpolation='nearest')
ax1.contour(segmentation, [0.5], linewidths=1.2, colors='y')
ax1.axis('off')
ax1.set_adjustable('box-forced')
plt.show()
开发者ID:tinaswang,项目名称:Other-Python-Files,代码行数:27,代码来源:image_segmentation.py
示例12: footprint_fitness_error
def footprint_fitness_error(self, points):
temp_footprint = np.zeros(self.FOOTPRINT_added_boundary.shape, dtype=np.uint8)
len_points = len(points)
for idx1 in xrange(0, len_points):
rr,cc = line(points[idx1][0], points[idx1][1], points[idx1-1][0],points[idx1-1][1])
temp_footprint[rr,cc] = 1
temp_footprint = ndimage.binary_fill_holes(temp_footprint)
temp_footprint = temp_footprint * 1
rr,cc = np.nonzero(temp_footprint)
#RATIO OF ZEROS AND ONES SA LOOB
zero_counter = 0.0
nonzero_counter = 0.0
for point in zip(rr,cc):
if self.FOOTPRINT_added_boundary[point[0]][point[1]] == 0:
zero_counter += 1.0
else:
nonzero_counter += 1.0
footprint_copy = copy.deepcopy(self.FOOTPRINT_added_boundary)
footprint_copy[rr,cc] = 0
nonzero = len(footprint_copy[footprint_copy != 0])
total = (len(footprint_copy[footprint_copy == 0]) + nonzero) * 1.0
return (nonzero / total) + (zero_counter / (nonzero_counter + zero_counter))
开发者ID:ivancheesecake,项目名称:Bertud,代码行数:29,代码来源:Building.py
示例13: im_proc
def im_proc(im):
"""Apply series of morphological procedures on image."""
th = threshold_otsu(im)
im_bin = im > th
return(ndi.binary_fill_holes(
morphology.closing(
im_bin,np.ones((3,3)))))
开发者ID:julionaojulho,项目名称:image-analysis,代码行数:7,代码来源:inthei.py
示例14: compute_mask
def compute_mask(self, params):
"""Creates the mask for the base image.
Needs the base image, an instance of imageloaderparams
and the clip area, which should be already defined
by the load_base_image method.
Creates the mask by improving the base mask created by the
compute_base_mask method. Applies the mask closing, dilation and
fill holes parameters.
"""
self.compute_base_mask(params)
mask = np.copy(self.base_mask)
closing_matrix = np.ones((params.mask_closing, params.mask_closing))
if params.mask_closing > 0:
# removes small dark spots and then small white spots
mask = img_as_float(morphology.closing(
mask, closing_matrix))
mask = 1 - \
img_as_float(morphology.closing(
1 - mask, closing_matrix))
for f in range(params.mask_dilation):
mask = morphology.erosion(mask, np.ones((3, 3)))
if params.mask_fill_holes:
# mask is inverted
mask = 1 - img_as_float(ndimage.binary_fill_holes(1.0 - mask))
self.mask = mask
self.overlay_mask_base_image()
开发者ID:brunomsaraiva,项目名称:eHooke_1.0,代码行数:32,代码来源:images.py
示例15: test_02_02_one_worm
def test_02_02_one_worm(self):
'''Find a single worm'''
image = np.zeros((20, 20), bool)
index, count, i, j = get_line_pts(
np.array([1,6,19,14]),
np.array([5,0,13,18]),
np.array([6,19,14,1]),
np.array([0,13,18,5]))
image[i,j] = True
image = binary_fill_holes(image)
workspace, module = self.make_workspace(image)
module.worm_length.value = 12
module.worm_width.value = 5
module.angle_count.value = 16
module.run(workspace)
m = workspace.measurements
self.assertTrue(isinstance(m, cpmeas.Measurements))
count = m.get_current_image_measurement(
'_'.join((ID.I.C_COUNT, OBJECTS_NAME)))
self.assertEqual(count, 1)
x = m.get_current_measurement(OBJECTS_NAME,
ID.I.M_LOCATION_CENTER_X)
self.assertEqual(len(x), 1)
self.assertAlmostEqual(x[0], 9., 1)
y = m.get_current_measurement(OBJECTS_NAME,
ID.I.M_LOCATION_CENTER_Y)
self.assertEqual(len(y), 1)
self.assertAlmostEqual(y[0], 10., 1)
a = m.get_current_measurement(OBJECTS_NAME,
ID.M_ANGLE)
self.assertEqual(len(a), 1)
self.assertAlmostEqual(a[0], 135, 0)
开发者ID:LeeKamentsky,项目名称:CellProfiler,代码行数:32,代码来源:test_identifydeadworms.py
示例16: get_segmented_lungs
def get_segmented_lungs(im, plot=False):
# Step 1: Convert into a binary image.
binary = im < -400
# Step 2: Remove the blobs connected to the border of the image.
cleared = clear_border(binary)
# Step 3: Label the image.
label_image = label(cleared)
# Step 4: Keep the labels with 2 largest areas.
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < areas[-2]:
for coordinates in region.coords:
label_image[coordinates[0], coordinates[1]] = 0
binary = label_image > 0
# Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
selem = disk(2)
binary = binary_erosion(binary, selem)
# Step 6: Closure operation with a disk of radius 10. This operation is to keep nodules attached to the lung wall.
selem = disk(10) # CHANGE BACK TO 10
binary = binary_closing(binary, selem)
# Step 7: Fill in the small holes inside the binary mask of lungs.
edges = roberts(binary)
binary = ndi.binary_fill_holes(edges)
# Step 8: Superimpose the binary mask on the input image.
get_high_vals = binary == 0
im[get_high_vals] = -2000
return im, binary
开发者ID:ericsolo,项目名称:python,代码行数:29,代码来源:helpers.py
示例17: detect_clouds
def detect_clouds(self,k=np.array([[-1,-2,-1],[0,0,0],[1,2,1]]),
umbral=40):
'Descripcion: Obtiene los bordes de una imagen entregada \n'\
'puede retornar los bordes y entregar la imagen rellenada \n'\
'\n'\
'Parametros\n'\
'----------\n'\
'imageIn : Imagen raster con informacion de Z o de ref.\n'\
'k : forma del filtro que se utiliza para obtener los bordes.\n'\
'umbral : Umbral utilizado para determinar si un objeto es o no.\n'\
' un borde.\n'\
'\n'\
'Retornos\n'\
'----------\n'\
'borders : Matriz con los bordes detectados.\n'\
'binario : Matriz binaria con los bordes rellenos.\n'\
'\n'\
'Ejemplo\n'\
'----------\n'\
'borders,binario=detect_clouds(Z).\n'\
#Obtiene el gradiente, y el binario
gradiente=radar_f90.detect_clouds(self.Z,k,k.T,radar_f90.ncols,radar_f90.nrows)
bordes=np.zeros(gradiente.shape)
bordes[gradiente>umbral]=1
#Llena el binario y quita el ruido
binario=nd.binary_fill_holes(bordes)*1
#Retorna lo obtenido
self.borders=bordes
self.binario=binario
开发者ID:nicolas998,项目名称:Radar,代码行数:30,代码来源:radar.py
示例18: clean_classified_image
def clean_classified_image(self):
"""
clean the binary image resulting from pixel classification using morphological operators
"""
if self.class_image is None:
self.classify_image()
bim = self.class_image
feature_mask = self.features_object.mask_image
if feature_mask is not None:
bim = bim & feature_mask
bim = ni.binary_fill_holes(bim)
min_gap = 0
for n in range(min_gap):
bim = ni.binary_dilation(bim)
#bim = ni.binary_closing(bim)
#bim = ni.binary_fill_holes(bim)
min_radius = 8
for n in range(min_radius):
bim = ni.binary_erosion(bim)
#bim = ni.binary_opening(bim)
for n in range(min_radius):
bim = ni.binary_dilation(bim)
#bim = ni.binary_dilation(bim)
#bim = ni.binary_erosion(bim)
self.clean_class_image = bim.astype(np.uint8) * 255
开发者ID:janfrs,项目名称:kwc-ros-pkg,代码行数:27,代码来源:texseg.py
示例19: _segment_watershed
def _segment_watershed(image):
elevation_map = sobel(image)
markers = np.zeros(image.shape) # initialize markers as zero array
# determine thresholds for markers
sorted_pixels = np.sort(image, axis=None)
max_int = np.mean(sorted_pixels[-10:])
min_int = np.mean(sorted_pixels[:10])
#max_int = np.max(orig_image)
#min_int = np.min(orig_image)
alpha_min = 0.01
alpha_max = 0.4
thresh_background = (1-alpha_min)*min_int + alpha_min*max_int
thresh_spots = (1-alpha_max)*min_int + alpha_max*max_int
markers[image < thresh_background] = 1 # mark background
markers[image > thresh_spots] = 2 # mark background
segmentation = watershed(elevation_map, markers)
segmentation = segmentation-1
segmentation = ndi.binary_fill_holes(segmentation) # fill holes
return segmentation
开发者ID:afrutig,项目名称:Moloreader,代码行数:25,代码来源:detection.py
示例20: alg
def alg(ring):
# fill holes in binary objects and then see if anything got filled
xor = scipy.logical_xor(ring, ndimage.binary_fill_holes(ring))
if xor.any():
return True
else:
return False
开发者ID:AlexanderRuesch,项目名称:medpy,代码行数:7,代码来源:count_holes_in_rings.py
注:本文中的scipy.ndimage.binary_fill_holes函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论