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

Python filter.canny函数代码示例

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

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



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

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


示例2: canny

def canny(data, sigma=1, sliceId=2):
    edges = np.zeros(data.shape, dtype=np.bool)
    if sliceId == 2:
        for idx in range(data.shape[2]):
            edges[:, :, idx] = skifil.canny(data[:, :, idx], sigma=sigma)
    elif sliceId == 0:
        for idx in range(data.shape[0]):
            edges[idx, :, :] = skifil.canny(data[idx, :, :], sigma=sigma)
    return edges
开发者ID:Trineon,项目名称:lisa,代码行数:9,代码来源:tools.py


示例3: _canny_edge_fired

 def _canny_edge_fired(self):
     self.im = self.orig
     r,g,b = np.rollaxis(self.im,axis=-1)
     edge_r = canny(tv_denoise(r, weight=1))
     edge_g = canny(tv_denoise(g, weight=1))
     edge_b = canny(tv_denoise(b, weight=1))
     edges = edge_r + edge_g + edge_b
     self.im = np.dstack((edges,edges,edges))
     self.im[self.im > 0.] = 1.
     try:
         self.axes.imshow(self.im)
         self.figure.canvas.draw()
     except:
         pass        
开发者ID:vlchen91,项目名称:ay250-hmwk,代码行数:14,代码来源:image_search.py


示例4: main

def main():
    plt.figure(figsize=(25, 24))
    planes = ['samolot00.jpg', 'samolot01.jpg', 'samolot03.jpg', 'samolot04.jpg', 'samolot05.jpg','samolot07.jpg',
              'samolot08.jpg', 'samolot09.jpg', 'samolot10.jpg', 'samolot11.jpg', 'samolot12.jpg', 'samolot13.jpg',
              'samolot14.jpg', 'samolot15.jpg', 'samolot16.jpg', 'samolot17.jpg', 'samolot18.jpg', 'samolot20.jpg']
    i = 1
    for file in planes:
        img = data.imread(file, as_grey=True)
        img2 = data.imread(file)
        ax = plt.subplot(6, 3, i)
        ax.axis('off')
        img **= 0.4
        img = filter.canny(img, sigma=3.0)
        img = morphology.dilation(img, morphology.disk(4))
        img = ndimage.binary_fill_holes(img)
        img = morphology.remove_small_objects(img, 1000)
        contours = measure.find_contours(img, 0.8)
        ax.imshow(img2, aspect='auto')
        for n, contour in enumerate(contours):
            ax.plot(contour[:, 1], contour[:, 0], linewidth=1.5)
            center = (sum(contour[:, 1])/len(contour[:, 1]), sum(contour[:, 0])/len(contour[:, 0]))
            ax.scatter(center[0], center[1], color='white')
        i += 1

    plt.savefig('zad2.pdf')
开发者ID:gracz21,项目名称:KCK,代码行数:25,代码来源:Zad_2.py


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


示例6: find_edges

    def find_edges(self,sigma=None):
        if sigma is not None:
            self.sigma = sigma

        print 'Identifying edges...'
        self.edges = filter.canny(self.data,sigma=self.sigma)
        return self.edges
开发者ID:TravGrah,项目名称:IRMOS-pipeline,代码行数:7,代码来源:rotate.py


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


示例8: canny

def canny(parameters):
    """Canny edge extraction filter.

    This wraps `skimage.filter.canny`. The `low_threshold`, `high_threshold`
    and `mask` options are not supported.

    The wrapped function returns a boolean array with pixel values True or
    False. Since it is not very convenient to pass such an array to other
    functions, the return value is cast to uint8, thus containing 0 or 1
    values.

    ..warning::

        During testing there have been some issues with the results. Check the
        corresponding test function for details.

    :param parameters['data'][0]: input image
    :type parameters['data'][0]: numpy.array
    :param parameters['sigma']: standard deviation of the gaussian filter,
                                defaults to 1.0
    :type parameters['sigma']: float

    :return: numpy.array, with dtype('uint8') containing 0 or 1 values

    """
    img = parameters['data'][0]
    sigma = parameters.get('sigma', 1.0)

    result = filter.canny(img, sigma=sigma)

    return result.astype('uint8')
开发者ID:cpsaltis,项目名称:pythogram-core,代码行数:31,代码来源:edges.py


示例9: auto_canny

def auto_canny(array, average=None, gaussian_sigma=1, strongness=2.5):
    if average is None:
        average = array.size ** 0.5 / array.size
    array -= array.min()
    array /= array.max()

    def canny_average(hard_threshold):
        soft_threshold = hard_threshold / strongness
        edges = canny(array, gaussian_sigma, hard_threshold, soft_threshold)
        return edges.mean()

    hard_threshold = 0.4
    epsilon = 0.0001
    bottom, top = 0., 1.
    for iteration in xrange(20):
        current_average = canny_average(hard_threshold)
        print(hard_threshold, current_average)
        if abs(current_average - average) < epsilon:
            break
        elif current_average < average:
            top = hard_threshold   
            hard_threshold = (bottom + top) / 2
        else:
            bottom = hard_threshold
            hard_threshold = (bottom + top) / 2
    else:
        print("Agotados los intentos")

    soft_threshold = hard_threshold / strongness
    return canny(array, gaussian_sigma, hard_threshold, soft_threshold)
开发者ID:FacundoGFlores,项目名称:golsoft,代码行数:30,代码来源:image.py


示例10: CanNuc

def CanNuc(datatype, maxrange, outputfile, outputfiletype):
	h = open(outputfile, outputfiletype)
	TC = 0	
	for i in range(0, maxrange):
		A = datatype[i][0]
		T = mahotas.thresholding.otsu(A)
		C = A.copy()
		if T < 1:
			C[ C <= T ] = 0
			C[ C > T ] = 1
		else:
			C[ C < T ] = 0
			C[ C >= T ] = 1
		filled = scipy.ndimage.morphology.binary_fill_holes(C)
		filled = filled.astype(np.uint8)
		edges1 = filter.canny(filled, sigma=1)
		edges1 = edges1.astype(np.uint8)
		edges1 = np.where(edges1 == 1)
		TC += len(edges1[0])
		XY1 = np.vstack((edges1[0], edges1[1], [i*5]*len(edges1[0])))
		for p in range(0, len(XY1[0])):
			for yel in range(0, len(XY1)):
				h.write(str(XY1[yel][p]) + '\t')
			h.write('\n')
	h.write(str(TC) + '\n')
	h.write('.' + '\n')
	h.close()
开发者ID:giacomo21,项目名称:Image-analysis,代码行数:27,代码来源:nikhilanalysis60x.py


示例11: findPlantsCanny

def findPlantsCanny(stackVar, stackSum, showImages=True):
    edges = canny(stackVar)
    fill_stack = ndimage.binary_fill_holes(edges)
    label_objects, nb_labels = ndimage.label(fill_stack)
    sizes = np.bincount(label_objects.ravel())
    mask_sizes = sizes > 25
    
    for label in range(len(mask_sizes)):
        '''
        Get rid of lines in addition to the straight size threshold.
        '''
        pts = np.where(label_objects == label)
        xRange = (max(pts[0]) - min(pts[0]))
        yRange = (max(pts[1]) - min(pts[1]))
        areaCovered = float(len(pts[0])) / (xRange*yRange)
        if (areaCovered < .33) or (xRange < 3) or (yRange < 3):
            mask_sizes[label] = False

    mask_sizes[0] = 0
    plants_cleaned = mask_sizes[label_objects]
    labeled_plants, numPlants = ndimage.label(plants_cleaned)
    center = findCenters(labeled_plants, stackSum)
    
    if showImages:
        fig, axs = plt.subplots(1,3, figsize=(14,4), sharey=True)
        axs[0].imshow(stackVar)
        axs[1].imshow(stackVar, cmap=plt.cm.jet, interpolation='nearest') #@UndefinedVariable
        axs[1].contour(plants_cleaned, [0.5], linewidths=1.2, colors='y')
        axs[2].imshow(labeled_plants, cmap=plt.cm.spectral, interpolation='nearest') #@UndefinedVariable
        axs[2].scatter(np.array(center.tolist())[:,1], np.array(center.tolist())[:,0], 
                       color='grey')
        for ax in axs: ax.axis('off')
        fig.subplots_adjust(wspace=.01)
       
    return labeled_plants, center
开发者ID:theandygross,项目名称:Luc,代码行数:35,代码来源:__init__.py


示例12: getVoidBorder

    def getVoidBorder(self):
        """Create boolean array where border points are True and all others
        False.
     
        Input:
            - none
 
        Example:
            >>> import pycoresis as pcs
            >>> fid = r'C:\YOUR\FILE\HERE.txt'
            >>> crs = pcs.corescan(fid)
            >>> crs.getVoidBorder()
            Number of border points : 2449
            Number of border points : 3245
            array([[ True,  True,  True, ...,  True,  True,  True],
                   [ True, False, False, ..., False, False,  True],
                   [ True, False, False, ..., False, False,  True],
                   ..., 
                   [ True, False, False, ..., False, False,  True],
                   [ True, False, False, ..., False, False,  True],
                   [ True,  True,  True, ...,  True,  True,  True]], dtype=bool)
        """
 
        self.voidedges = filter.canny(self.data)
        point_num = np.where(self.voidedges==True)
        self.pointnum = np.size(point_num[0])
        print "Number of border points :", self.pointnum
        return self.voidedges
开发者ID:AlisonMergaman,项目名称:Foamed-Cement,代码行数:28,代码来源:pycoresis.py


示例13: get_edge

def get_edge(name, sig = 8):
	im = ndimage.imread(name, True)
	edge = filter.canny(im, sigma = sig)
	modded = (255.0 / edge.max() * (edge - edge.min())).astype(np.uint8)
	edged = Image.fromarray(modded)
	edged.save("photos/edge.png")
	return edged
开发者ID:madisonmay,项目名称:Image2ASCII,代码行数:7,代码来源:edge_test.py


示例14: encode

	def encode(self):

		data_array = np.array(self.image)#data).reshape((28,28))

		edges = filt.canny(data_array, sigma=3)

		def linear_mapping(data): # using principal components analysis
			pca = decomposition.PCA(n_components=784)
			pca.fit(data)
			mapping = pca.transform(data)

			return mapping

		# encoded = linear_mapping(edges)

		encoded = np.array(edges).reshape(784)

		# encoded = []

		# for d in self.data:
		# 	if (d > 45):
		# 		encoded.append(1)
		# 	else:
		# 		encoded.append(0)

		return encoded
开发者ID:ajaykarpur,项目名称:tempotron-classifier,代码行数:26,代码来源:classes.py


示例15: _get_canny_image

 def _get_canny_image(self):
     ci = canny(
         self.original_image, sigma=self.canny_sigma,
         low_threshold=self.canny_low_threshold,
         high_threshold=self.canny_high_threshold,
     )
     return ci
开发者ID:5n1p,项目名称:enaml,代码行数:7,代码来源:processing_model.py


示例16: detect_edges

def detect_edges(image_array):
    """ Detect edges in a given image
    Takes a numpy.array representing an image,
    apply filters and edge detection and return a numpy.array

    Parameters
    ----------
    image_array : ndarray (2D)
        Image data to be processed. Detect edges on this 2D array representing the image

    Returns
    -------
    edges : ndarray (2D)
        Edges of an image.
    """
    #Transform image into grayscale
    img = rgb2gray(image_array)
    #Remove some noise from the image
    img = denoise_tv_chambolle(img, weight=0.55)
    #Apply canny
    edges = filter.canny(img, sigma=3.2)
    #Clear the borders
    clear_border(edges, 15)
    #Dilate edges to make them more visible and connected
    edges = binary_dilation(edges, selem=diamond(3))
    return edges
开发者ID:Pat-rice,项目名称:automated_testing_image_classifiers,代码行数:26,代码来源:image_processing.py


示例17: label_particles_edge

def label_particles_edge(im, sigma=2, closing_size=0, **extra_args):
    """ Segment image using Canny edge-finding filter.

        parameters
        ----------
        im : image in which to find particles
        sigma : size of the Canny filter
        closing_size : size of the closing filter

        returns
        -------
        labels : an image array of uniquely labeled segments
    """
    from skimage.morphology import square, binary_closing, skeletonize
    if skimage_version < StrictVersion('0.11'):
        from skimage.filter import canny
    else:
        from skimage.filters import canny
    edges = canny(im, sigma=sigma)
    if closing_size > 0:
        edges = binary_closing(edges, square(closing_size))
    edges = skeletonize(edges)
    labels = sklabel(edges)
    print "found {} segments".format(labels.max())
    # in ma.array mask, False is True, and vice versa
    labels = np.ma.array(labels, mask=edges == 0)
    return labels
开发者ID:leewalsh,项目名称:square-tracking,代码行数:27,代码来源:positions.py


示例18: update_image

    def update_image(self, event=None):

        self.imgview.image = canny(self.original_image,
                                   sigma=self.sigma,
                                   low_threshold=self.low,
                                   high_threshold=self.high)
        self.imgview.redraw()
开发者ID:NeilYager,项目名称:skloupe,代码行数:7,代码来源:edgedetector.py


示例19: find_iris

def find_iris(image, pupil, **kwargs):
    buffer = 20
    # run canny
    image = filter.canny(image, sigma=1, low_threshold=10, high_threshold=50)
    cx, cy, radius = pupil

    segments = get_segments(400, step=0.01)
    # get ray directions
    directions = zip(map(cos, segments[0]), map(sin, segments[0]))
    shape = image.shape
    points = []
    for d in directions:
        start = (cx + (radius + buffer) * d[0], cy + (radius + buffer)*d[1])
        ray = Ray(image, start, d)
        point = ray.fire()
        if point != None:
            points.append(point)

    for p in points:
        x, y = circle_perimeter(int(p[0]), int(p[1]), 3)
        x = x[x < rgb.shape[0]]
        y = y[y < rgb.shape[1]]
        rgb[x,y] = (220, 40, 40)

    e = Ellipse().fit_with_center(None, points)
    return image, points, e
开发者ID:michellehwang,项目名称:biome,代码行数:26,代码来源:iris.py


示例20: get_gravatar_array

def get_gravatar_array(email, sz=100, edge=(5, 20, 2, 2), mask=((0, 10), (80, 90)), shrink=0.0):
    g = hashlib.md5(email.lower()).hexdigest() + ".jpg"
    fname = "/tmp/" + g
    url = "http://www.gravatar.com/avatar/" + g
    os.system("curl -s -o %s %s" % (fname, url))
    g = scipy.misc.imread(fname, flatten=True)[5:75, 5:75]
    g = 255 - scipy.misc.imresize(g, (sz, sz))
    if edge:
        (sigma, hi, low, sigma2) = edge
        g = 255 * canny(g, sigma, hi, low)
        g = (ndimage.gaussian_filter(g, sigma=sigma2) > 25) * 255
    if mask:
        ((r1, c1), (r2, c2)) = mask
        g[r2:, :] = 0
        g[:r1, :] = 0
        g[:, :c1] = 0
        g[:, c2:] = 0
    if shrink > 0.0:
        (nx, ny) = g.shape
        px = int(nx * shrink / 2)
        py = int(ny * shrink / 2)
        g = concatenate((zeros((py, nx), dtype=g.dtype), g, zeros((py, nx), dtype=g.dtype)), axis=0)
        g = concatenate((zeros((ny + 2 * py, px), dtype=g.dtype), g, zeros((ny + 2 * py, px), dtype=g.dtype)), axis=1)
        g = scipy.misc.imresize(g, (sz, sz))
    g = g.flatten()
    return g
开发者ID:pnf,项目名称:unicon,代码行数:26,代码来源:unicon.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python filter.sobel函数代码示例发布时间:2022-05-27
下一篇:
Python peak.peak_local_max函数代码示例发布时间: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