• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python morphology.closing函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中skimage.morphology.closing函数的典型用法代码示例。如果您正苦于以下问题:Python closing函数的具体用法?Python closing怎么用?Python closing使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了closing函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: 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


示例2: close_image

def close_image(img, mask_length):
    # Morphological closing on greyscale/binary image
    
    img = img.astype(np.uint8)
    img = closing(img, rectangle(mask_length,1))
    
    return(img)
开发者ID:ogencoglu,项目名称:Templates,代码行数:7,代码来源:image_processing.py


示例3: getRegions

def getRegions():
    """Geocode address and retreive image centered
    around lat/long"""
    address = request.args.get('address')
    results = Geocoder.geocode(address)
    lat, lng = results[0].coordinates
    zip_code = results[0].postal_code

    map_url = 'https://maps.googleapis.com/maps/api/staticmap?center={0},{1}&size=640x640&zoom=19&sensor=false&maptype=roadmap&&style=visibility:simplified|gamma:0.1'
    request_url = map_url.format(lat, lng)
    req = urllib.urlopen(request_url)
    img = io.imread(req.geturl(),flatten=True)
    labels, numobjects = ndimage.label(img)
    image = filter.canny(img, sigma=3)
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(image_label_overlay)
开发者ID:frenchja,项目名称:SunnySideUp,代码行数:29,代码来源:views.py


示例4: segment_out_cells

def segment_out_cells(base):
    # TODO: try using OTSU for GFP thresholding

    sel_elem = disk(2)
    gfp_collector = np.sum(base, axis=0)
    gfp_clustering_markers = np.zeros(gfp_collector.shape, dtype=np.uint8)
    # random walker segment
    gfp_clustering_markers[gfp_collector > np.mean(gfp_collector) * 2] = 2
    gfp_clustering_markers[gfp_collector < np.mean(gfp_collector) * 0.20] = 1
    labels = random_walker(gfp_collector, gfp_clustering_markers, beta=10, mode='bf')
    # round up the labels and set the background to 0 from 1
    labels = closing(labels, sel_elem)
    labels -= 1
    # prepare distances for the watershed
    distance = ndi.distance_transform_edt(labels)
    local_maxi = peak_local_max(distance,
                                indices=False,  # we want the image mask, not peak position
                                min_distance=10,  # about half of a bud with our size
                                threshold_abs=10,  # allows to clear the noise
                                labels=labels)
    # we fuse the labels that are close together that escaped the min distance in local_maxi
    local_maxi = ndi.convolve(local_maxi, np.ones((5, 5)), mode='constant', cval=0.0)
    # finish the watershed
    expanded_maxi_markers = ndi.label(local_maxi, structure=np.ones((3, 3)))[0]
    segmented_cells_labels = watershed(-distance, expanded_maxi_markers, mask=labels)

    # log debugging data
    running_debug_frame.gfp_collector = gfp_collector
    running_debug_frame.gfp_clustering_markers = gfp_clustering_markers
    running_debug_frame.labels = labels
    running_debug_frame.segmented_cells_labels = segmented_cells_labels

    return gfp_collector, segmented_cells_labels
开发者ID:chiffa,项目名称:Chromo_vision,代码行数:33,代码来源:layered_zstack_processing.py


示例5: Mask_ROI_cl

def Mask_ROI_cl(im,disk_size,thresh=None,black_spots=None,with_morph=False):
    l=np.array([0,0])
    if not isinstance(im,l.__class__):
        numpy_array=np.array(im)
    else:
        numpy_array=im 
    if len(numpy_array.shape)==3:
        numpy_array=numpy_array[:,:,0:3].mean(axis=2)

    selem = disk(disk_size)
    closed = closing(numpy_array, selem)
    if thresh is None:
        thresh = threshold_otsu(closed)
    binary = closed > thresh
    if binary.dtype=='bool':
        binary=binary+0
    if black_spots is not None:    
        binary2 = closed > black_spots
        binary2 = binary2 + 0
        binary = binary - binary2 
    else:
        binary -=1
    binary=binary * -1
    if with_morph:
        return(binary,closed)
    else:
        return(binary)
开发者ID:PeterJackNaylor,项目名称:challengecam,代码行数:27,代码来源:BasicOperations.py


示例6: closing

def closing(gray_img, kernel=None):
    """Wrapper for scikit-image closing functions. Opening can remove small dark spots (i.e. pepper).

    Inputs:
    gray_img = input image (grayscale or binary)
    kernel   = optional neighborhood, expressed as an array of 1s and 0s. If None, use cross-shaped structuring element.

    :param gray_img: ndarray
    :param kernel = ndarray
    :return filtered_img: ndarray
    """

    params.device += 1

    # Make sure the image is binary/grayscale
    if len(np.shape(gray_img)) != 2:
        fatal_error("Input image must be grayscale or binary")

    # If image is binary use the faster method
    if len(np.unique(gray_img)) == 2:
        bool_img = morphology.binary_closing(image=gray_img, selem=kernel)
        filtered_img = np.copy(bool_img.astype(np.uint8) * 255)
    # Otherwise use method appropriate for grayscale images
    else:
        filtered_img = morphology.closing(gray_img, kernel)

    if params.debug == 'print':
        print_image(filtered_img, os.path.join(params.debug_outdir, str(params.device) + '_opening' + '.png'))
    elif params.debug == 'plot':
        plot_image(filtered_img, cmap='gray')

    return filtered_img
开发者ID:danforthcenter,项目名称:plantcv,代码行数:32,代码来源:closing.py


示例7: test_large_radius

def test_large_radius():
    ''' Compare execution time against scikit: single closing case
    Here, our implementation does not take advantage of smaller radius results
    so ours is slower than scikit, but it uses significantly less memory.
    '''
    base_dir = '/home/omar/data/DATA_NeoBrainS12/'
    neo_subject = '30wCoronal/example2/'

    # Read subject files
    t2CurrentSubjectName  = base_dir + 'trainingDataNeoBrainS12/'+neo_subject+'T2_1-1.nii.gz'
    t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data()
    affineT2CS            = nib.load(t2CurrentSubjectName).get_affine()
    zoomsT2CS             = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3]
    # Step 1.4 - Resampling for isotropic voxels

    n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0])
    t2CurrentSubject_data,affineT2CS = reslice(t2CurrentSubject_data,affineT2CS,zoomsT2CS,n_zooms)

    S = t2CurrentSubject_data.astype(np.float64)

    ###########compare times#########
    # in-house
    radius = 15
    start = time.time()
    d = isotropic_dilation(S, radius)
    c = isotropic_erosion(d, radius)
    end = time.time()
    print('Elapsed (in-home): %f'%(end-start,))

    # scikit
    start = time.time()
    expected = closing(S, ball(radius))
    end = time.time()
    print('Elapsed (scikit): %f'%(end-start,))
开发者ID:ulisesrdom,项目名称:segmentation,代码行数:34,代码来源:test_fast_morph.py


示例8: threshold_image

def threshold_image(image, threshold=0):
	"""
	This function takes out any values in an image's RGB matrix that are
	below the threshold value.

	Inputs:
	- image: a matrix describing an image with only one channel represented.
	- threshold: a value, between 0 and 1, for which if an image matrix's
				 value is below, will be set to 0, and if above, will be 
				 set to 1.

				 If the threshold is set to 0, then an Otsu thresholding will
				 be returned.

	Outputs:
	- thresholded_image: a matrix representation of the thresholded image.
						 this is essentially a black and white image.
	- thresh: the threshold value

	To screen: the black-and-white image representation.
	- 
	"""
	if threshold == 0:
		thresh = threshold_otsu(image)

	if threshold != 0:
		thresh = threshold

	thresholded_image = closing(image > thresh, square(3), out=None)
	imshow(thresholded_image)

	return thresholded_image, thresh
开发者ID:runstadler-lab,项目名称:Seal-H3N8-Image-Analysis,代码行数:32,代码来源:rgprocessing.py


示例9: 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


示例10: morphOps

 def morphOps( imgIn, sizeSE, sizeCC ):
     imgOut = imgIn.astype(bool) #boolean image
     imgOut = ~imgOut #img negative
     imgOut = morphology.remove_small_objects( imgOut, sizeCC ) #cclargest
     SE = morphology.selem.disk( sizeSE ) #structuring element
     imgOut = morphology.closing(imgOut, SE)
     return imgOut
开发者ID:vsimonis,项目名称:worm1,代码行数:7,代码来源:imgProc.py


示例11: get_valley_image

    def get_valley_image(self, image):
        valley_img = np.zeros_like(image)
        for z in range(0, image.shape[0]):
            valley_img[z, :, :] = closing(image[z, :, :], disk(5))
        valley_img -= image

        return valley_img
开发者ID:elpisco,项目名称:hip-dysplasia,代码行数:7,代码来源:image_processing.py


示例12: smooth

def smooth(image):
  filename_split = os.path.splitext(image)
  filename_zero, fileext = filename_split
  basename = os.path.basename(filename_zero)
  im = np.array(Image.open(image))
  with rasterio.open(image) as r:
    im = r.read()
    p = r.profile
  im = im.squeeze()
  selem = disk(1)
  print("image min and max: ", im.min(),im.max())
  dilated = skimage.morphology.dilation(im, selem)
  print("dilated image min and max: ", dilated.min(),dilated.max())
  eroded = skimage.morphology.erosion(im, selem)
  print("eroded image min and max: ", eroded.min(),eroded.max())
  opened = opening(im, selem)
  print("opened image min and max: ", opened.min(),opened.max())
  closed = closing(im, selem)
  print("closed image min and max: ", closed.min(),closed.max())
  #im[im==1]=0
  #im[im==2]=1
  median = cv2.medianBlur(im,9)
  average = cv2.blur(im,(9,9))
  #gaussian = cv2.GaussianBlur(im,(9,9),0)
  gaussian = cv2.GaussianBlur(dilated,(9,9),0)
  #bilateral = cv2.bilateralFilter(im,9,75,75)
  bilateral = cv2.bilateralFilter(gaussian,9,75,75)
  with rasterio.open(outPath+basename+fileext, 'w', **p) as dst:
      dst.write(bilateral, 1)
  color_outPath = outPath+'color/'
  if not os.path.exists(color_outPath):
        os.mkdir(color_outPath) 
  colored_image = color_outPath+basename+'.png'
  os.system("gdaldem color-relief", bilateral, colorfile, colored_image)
  return im, dilated, eroded, opened, closed, median, average, gaussian, bilateral
开发者ID:lillythomas,项目名称:ML_tools,代码行数:35,代码来源:PostProc_FCN.py


示例13: upsample_smooth

def upsample_smooth(image):
  filename_split = os.path.splitext(image)
  filename_zero, fileext = filename_split
  basename = os.path.basename(filename_zero)
  upsampleRes = int(upsampleRes)
  upsampled_image = outPath+basename+'_cubicSpline.png'
  os.system("gdalwarp -tr", upsample_res, upsample_res," -r cubicspline ", image, upsampled_image)
  im = np.array(Image.open(upsampled_image))
  with rasterio.open(image) as r:
    im = r.read()
    p = r.profile
  im = im.squeeze()
  selem = disk(1)
  print("image min and max: ", im.min(),im.max())
  dilated = skimage.morphology.dilation(im, selem)
  print("dilated image min and max: ", dilated.min(),dilated.max())
  eroded = skimage.morphology.erosion(im, selem)
  print("eroded image min and max: ", eroded.min(),eroded.max())
  opened = opening(im, selem)
  print("opened image min and max: ", opened.min(),opened.max())
  closed = closing(im, selem)
  print("closed image min and max: ", closed.min(),closed.max())
  dilated = Image.fromarray(dilated)
  dilated.save(outPath+basename+'.png')
  with rasterio.open(outPath+basename+fileext, 'w', **p) as dst:
      dst.write(dilated, 1)
  color_outPath = outPath+'color/'
  if not os.path.exists(color_outPath):
        os.mkdir(color_outPath) 
  colored_image = color_outPath+basename+'.png'
  os.system("gdaldem color-relief", dilated, colorfile, colored_image)
  return im, dilated, eroded, opened, closed
开发者ID:lillythomas,项目名称:ML_tools,代码行数:32,代码来源:PostProc_FCN.py


示例14: scikit_example_plot_label

def scikit_example_plot_label():
    image = data.coins()[50:-50, 50:-50]
    
    # apply threshold
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))
    
    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)
    
    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(label_image, cmap='jet')
    
    for region in regionprops(label_image, ['Area', 'BoundingBox']):
    
        # skip small images
        if region['Area'] < 100:
            continue
    
        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region['BoundingBox']
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)
    
    plt.show()
开发者ID:bchoatejr,项目名称:math,代码行数:32,代码来源:image_label.py


示例15: test_accuracy

def test_accuracy():
    ''' Verify that our implementation returns exactly the same as scikit
    '''
    base_dir = '/home/omar/data/DATA_NeoBrainS12/'
    neo_subject = '30wCoronal/example2/'

    # Read subject files
    t2CurrentSubjectName  = base_dir + 'trainingDataNeoBrainS12/'+neo_subject+'T2_1-1.nii.gz'
    t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data()
    affineT2CS            = nib.load(t2CurrentSubjectName).get_affine()
    zoomsT2CS             = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3]

    n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0])
    t2CurrentSubject_data,affineT2CS = reslice(t2CurrentSubject_data,affineT2CS,zoomsT2CS,n_zooms)

    S = t2CurrentSubject_data.astype(np.float64)

    max_radius = 4
    D = SequencialSphereDilation(S)
    for r in range(1, 1+max_radius):
        D.expand(S)
        expected = dilation(S, ball(r))
        actual = D.get_current_dilation()
        assert_array_equal(expected, actual)
        expected = closing(S, ball(r))
        actual = D.get_current_closing()
        assert_array_equal(expected, actual)
开发者ID:ulisesrdom,项目名称:segmentation,代码行数:27,代码来源:test_fast_morph.py


示例16: removeChessboard

def removeChessboard(img):

    # Get the major lines in the image
    edges, dilatedEdges, (h, theta, d) = findLines(img)

    # Create image with ones to fill inn lines
    lines = np.ones(img.shape[:2])

    # Add lines to image as zeroes
    for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
        y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
        y1 = (dist - img.shape[1] * np.cos(angle)) / np.sin(angle)
        x, y = line(int(y1), 0, int(y0), img.shape[1] - 1)
        x = np.clip(x, 0, img.shape[0] - 1)
        y = np.clip(y, 0, img.shape[1] - 1)
        lines[x, y] = 0

    # Remove border edges from image with all edges
    w = 4
    edges = np.pad(edges[w:img.shape[0] - w, w:img.shape[1] - w], w, mode='constant')

    # Erode the lines bigger, such that they cover the original lines
    lines = erosion(lines, square(13))

    # Remove major lines and close shape paths
    removedChessboard = closing(edges * lines, square(8))

    return removedChessboard
开发者ID:niklasmh,项目名称:ntnu,代码行数:28,代码来源:task5a.py


示例17: Image_ws_tranche

def Image_ws_tranche(image):
    
    laser = Detect_laser(image)
    laser_tranche = tranche_image(laser,60)
    
    image_g = skimage.color.rgb2gray(image)
    image_g = image_g * laser_tranche
    
    image_med = rank2.median((image_g*255).astype('uint8'),disk(8))
    
    image_clahe = exposure.equalize_adapthist(image_med, clip_limit=0.03)
    image_clahe_stretch = exposure.rescale_intensity(image_clahe, out_range=(0, 256))

    image_grad = rank2.gradient(image_clahe_stretch,disk(3))
    
    image_grad_mark = image_grad<20
    image_grad_forws = rank2.gradient(image_clahe_stretch,disk(1))
    
    image_grad_mark_closed = closing(image_grad_mark,disk(1))
    
    Labelised = (skimage.measure.label(image_grad_mark_closed,8,0))+1
    Watersheded  = watershed(image_grad_forws,Labelised)
    
    cooc = coocurence_liste(Watersheded,laser,3)
    
    x,y = compte_occurences(cooc)
    
    return x,y
开发者ID:elekhac,项目名称:Projet_Polype,代码行数:28,代码来源:Fonctions_Analyse.py


示例18: 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


示例19: plot_preprocessed_image

    def plot_preprocessed_image(self):
        """
        plots pre-processed image. The plotted image is the same as obtained at the end
        of the get_text_candidates method.
        """
        image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
        thresh = threshold_otsu(image)
        bw = closing(image > thresh, square(2))
        cleared = bw.copy()

        label_image = measure.label(cleared)
        borders = np.logical_xor(bw, cleared)

        label_image[borders] = -1
        image_label_overlay = label2rgb(label_image, image=image)

        fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
        ax.imshow(image_label_overlay)

        for region in regionprops(label_image):
            if region.area < 10:
                continue

            minr, minc, maxr, maxc = region.bbox
            rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                      fill=False, edgecolor='red', linewidth=2)
            ax.add_patch(rect)

        plt.show()
开发者ID:kmiddleton,项目名称:ImageTextRecognition,代码行数:29,代码来源:userimageski.py


示例20: roofRegion

def roofRegion(edge):
    """Estimate region based on edges of roofRegion
    """
    # apply threshold
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(image_label_overlay)

    for region in regionprops(label_image):

        # skip small images
        if region.area < 100:
            continue

        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region.bbox
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)

    plt.show()
开发者ID:frenchja,项目名称:SunnySideUp,代码行数:33,代码来源:gmaps.py



注:本文中的skimage.morphology.closing函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python morphology.convex_hull_image函数代码示例发布时间:2022-05-27
下一篇:
Python morphology.binary_dilation函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap