当前位置: 首页>>代码示例>>Python>>正文


Python measure.find_contours函数代码示例

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


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

示例1: main

def main():
    parser = argparse.ArgumentParser()
    parser_io = parser.add_argument_group(description = "==== I/O parameters ====")
    parser_io.add_argument("-i","--infile",required=True)
    parser_io.add_argument("-o","--baseoutfilename",default="out")
    parser_io.add_argument("-v","--verbose",action="store_true",default=False)
    parser_io.add_argument("-S","--OutputSinglestrainNullclines",action="store_true",default=False)

    parser = gc.AddLatticeParameters(parser)
    parser = gc.AddDilutionParameters(parser)

    args=parser.parse_args()

    g     = gc.LoadGM(**vars(args))
    dlist = gc.getDilutionList(**vars(args))

    # get new axes, which depends on parameters above (in lattice parameter group)
    axis1,axis2 = gc.getInoculumAxes(**vars(args)) # either (n,x) or [ (n1,n2) if args.AbsoluteCoordinates == True ]
    shape       = (len(axis1),len(axis2))

    # loaded from pickle file
    m1,m2       = g.growthmatrixgrid
    gm1         = g.growthmatrix[:,:,0]
    gm2         = g.growthmatrix[:,:,1]

    # matrices to store averages
    g1          = np.zeros(shape,dtype=np.float64) # avg'd growth strain 1
    g2          = np.zeros(shape,dtype=np.float64) # avg'd growth strain 2
    rr1         = np.zeros(shape,dtype=np.float64) # avg'd ratio of strains at end
    r1          = np.zeros(shape,dtype=np.float64) # avg'd ratio of strains at beginning
    sn1         = np.zeros(shape,dtype=np.float64) # number of cells of strain 1 in new matrix shape
    sn2         = np.zeros(shape,dtype=np.float64) # number of cells of strain 1 in new matrix shape

    # get all averages and store them in the appropriate matrices
    for i,a1 in enumerate(axis1):
        for j,a2 in enumerate(axis2):
            sn1[i,j],sn2[i,j] = gc.TransformInoculum([a1,a2],inabs = args.AbsoluteCoordinates, outabs = True)
            g1[i,j] = gc.SeedingAverage(gm1, [sn1[i,j],sn2[i,j]])
            g2[i,j] = gc.SeedingAverage(gm2, [sn1[i,j],sn2[i,j]])

    rr1[g1+g2>0]  = (g1[g1+g2>0])/((g1+g2)[g1+g2>0])
    r1[sn1+sn2>0] = (sn1[sn1+sn2>0])/((sn1+sn2)[sn1+sn2>0])

    # output
    if args.verbose:
        sys.stdout.write('\n computing nullcline for fraction of strains\n')
    cont_xx = measure.find_contours(rr1 - r1,0)
    write_contours_to_file(cont_xx,args.baseoutfilename + '_X',axis1,axis2)

    for dilution in dlist:
        if args.verbose:
            sys.stdout.write(' computing nullclines for dilution D = {:.4e}\n'.format(dilution))
        cont_nn = measure.find_contours((g1 + g2) * dilution - sn1 - sn2,0)
        write_contours_to_file(cont_nn,args.baseoutfilename + '_N_D{:.3e}'.format(dilution),axis1,axis2)
        if args.OutputSinglestrainNullclines:
            cont_n1 = measure.find_contours(g1 * dilution - sn1,0)
            cont_n2 = measure.find_contours(g2 * dilution - sn2,0)
            write_contours_to_file(cont_n1,args.baseoutfilename + '_1_D{:.3e}'.format(dilution),axis1,axis2)
            write_contours_to_file(cont_n2,args.baseoutfilename + '_2_D{:.3e}'.format(dilution),axis1,axis2)
开发者ID:lukasgeyrhofer,项目名称:millifluidics,代码行数:59,代码来源:mixingcycles_Isoclines.py

示例2: find_contours

def find_contours(path, low=0.1, high=0.8):
    """Find contours in an image at path
    """
    img = imread(path, flatten=True)
    
    # Find contours at a constant value of 0.1 and 0.8
    dark = measure.find_contours(img, low)
    light = measure.find_contours(img, high)
    return img, dark, light
开发者ID:Carreau,项目名称:ngcm-tutorial,代码行数:9,代码来源:images_common.py

示例3: compute_contours

    def compute_contours(self):
        graph = self.graph
        if graph is None or not self.x2_variable:
            return

        for plot in self._contour_plots:
            self.graph.remove_plot(plot)

        plots = self._contour_plots = []
        data = np.clip(self._yvals, self.y_start, self.y_end)
        xscale = (self.end - self.start) / self.num_points
        x2scale = (self.x2_end - self.x2_start) / self.num_points
        color = next(self.colors)

        for val in np.linspace(self.y_start, self.y_end, self.num_contours):
            contours = measure.find_contours(data, val)
            for contour in contours:
                contour[:, 0] *= xscale
                contour[:, 0] += self.start
                contour[:, 1] *= x2scale
                contour[:, 1] += self.x2_start

                plot = MeshLinePlot(color=color)
                plots.append(plot)
                graph.add_plot(plot)
                plot.points = contour
开发者ID:matham,项目名称:Ceed,代码行数:26,代码来源:optics.py

示例4: tracestackedslab

def tracestackedslab(infile,depthinc=5,llinc=((6371*np.pi)/360),cval=0.5):
	'''
	Takes a netcdf file containing a stacked, normed profiles and attempts to contour what might be a slab - can use this to estimate dip, profile etc
	The values of depthinc and llinc are defaults from the Ritsema code, which creates slices over angles of 180 degrees
	and with a depth increment of 5 km

	This produces a map showing the slice and contours in stacked velocity perturbation at a chosen level (typically 0.5)
	'''

	Mantlebase = 2895

	infile = Dataset(infile, model='r')

	filevariables = infile.variables.keys()

	#Get data from the netCDF file
	depths = infile.variables['y'][:]
	lengths = infile.variables['x'][:]
	data = infile.variables['z'][:][:]

	infile.close()

	#print np.shape(data)
	#print np.shape(lengths)
	#print np.shape(depths)

	#Use image processing suite to find contours
	contours = measure.find_contours(data,cval)

	#Various plotting commands to produce the figure
	fig, ax = plt.subplots()

	thousandkm = int((Mantlebase-1000)/depthinc)
	sixsixtykm = int((Mantlebase-660)/depthinc)

	plt.set_cmap('jet_r')

	ax.imshow(data, interpolation='linear',aspect='auto')

	ax.plot([0,len(lengths)],[thousandkm,thousandkm],'k--',label='1000km')
	ax.plot([0,len(lengths)],[sixsixtykm,sixsixtykm],'k-',label='660km')

	for n, contour in enumerate(contours):
		if n == 0:
			ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2,label='contour at %g' %cval)
		else:
			ax.plot(contour[:, 1], contour[:, 0], 'r-', linewidth=2)


	ax.set_ylim([0,len(depths)])
	ax.set_xlim([len(lengths),0])
	ax.set_title('Stacked slab image from netCDF')
	plt.xlabel('Cross section x increment')
	plt.ylabel('Cross section depth increment')
	plt.legend(loc='best')

	#plt.gca().invert_yaxis()
	#plt.gca().invert_xaxis()

	plt.show(block=False)
开发者ID:rmartinshort,项目名称:slabpy,代码行数:60,代码来源:Tomo_slice_manipulation_tools.py

示例5: edge_detect

def edge_detect(im, hdr):
    w = WCS(hdr)
    ra = []
    dec = []
    exclude_RA = np.NaN
    exclude_DEC = np.NaN
    contours = measure.find_contours(im,0.5,fully_connected='high')
    x_pix = contours[0][:,0]
    y_pix = im.shape[1] - contours[0][:,1] - 1
    exclude_reg = np.array(contours).shape[0] - 1
    if exclude_reg > 0:
        i = 1
        exclude_RA = []
        exclude_DEC = []
        while i <= exclude_reg:
            x_excl = contours[i][:,0]
            y_excl = im.shape[1] - contours[i][:,1] - 1
            tmp_RA = []
            tmp_DEC = []
            for j in np.arange(len(x_excl)):
                x, y = w.wcs_pix2world(y_excl[j], x_excl[j], 0)
                tmp_RA.append(x.tolist())
                tmp_DEC.append(y.tolist())
            exclude_RA.append(tmp_RA)
            exclude_DEC.append(tmp_DEC)
            i += 1
    for i in np.arange(len(x_pix)):
        x, y = w.wcs_pix2world(y_pix[i], x_pix[i], 0)
        ra.append(x.tolist())
        dec.append(y.tolist())

    return ra, dec, exclude_RA, exclude_DEC
开发者ID:gogrean,项目名称:BokehAstroMaps,代码行数:32,代码来源:edge_detector.py

示例6: __call__

    def __call__(self, level, minDensity, keepSourceWindow=False):
        self.start(keepSourceWindow)
        if self.tif.dtype == np.float16:
            g.alert("Adaptive Threshold does not support float16 type arrays")
            return
        for roi in self.ROIs:
            roi.cancel()
        self.ROIs = []

        im = g.win.image if g.win.image.ndim == 2 else g.win.image[g.win.currentIndex]
        im = scipy.ndimage.morphology.binary_closing(im)
        if np.any(im < 0) or np.any(im > 1):
            raise Exception("The current image is not a binary image. Threshold first")

        thresholded_image = np.squeeze(im)
        labelled=measure.label(thresholded_image)
        ROIs = []
        for i in range(1, np.max(labelled)+1):
            if np.sum(labelled == i) >= minDensity:
                im = scipy.ndimage.morphology.binary_dilation(scipy.ndimage.morphology.binary_closing(labelled == i))
                outline_coords = measure.find_contours(im, level)
                if len(outline_coords) == 0:
                    continue
                outline_coords = outline_coords[0]
                new_roi = makeROI("freehand", outline_coords)
                ROIs.append(new_roi)
开发者ID:flika-org,项目名称:flika,代码行数:26,代码来源:binary.py

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

示例8: getGeneralStatistics

 def getGeneralStatistics(self):
     area = np.sum(self.image)
     perimeterArray = [len(x) for x in measure.find_contours(self.image, 0.5)]
     perimeter = max(perimeterArray) if len(perimeterArray) != 0 else 0
     roundness = 4 * area * pi / (perimeter * perimeter) if perimeter != 0 else 0
     finalStatistics = [area, perimeter, roundness, len(self.getCenters())]
     return finalStatistics
开发者ID:kosklain,项目名称:MitosisDetection,代码行数:7,代码来源:ImageWorker.py

示例9: contours

def contours(data):
    """Get zero contours from x, y, z data

    Args:
      data: dictionary with (x, y, z, dx) keys

    Returns:
      a list of (N, 2) numpy arrays representing the contours
    """
    def linspace_(arr, spacing):
        """Calcuate the linspace based on a spacing
        """
        return pipe(
            arr,
            juxt(min, max),
            tlam(lambda x_, y_: np.linspace(x_, y_, (y_ - x_) / spacing))
        )

    return pipe(
        data,
        lambda x: dict(xi=linspace_(x['x'], x['dx']),
                       yi=linspace_(x['y'], x['dx']),
                       **x),
        lambda x: griddata((x['y'], x['x']),
                           x['z'],
                           (x['yi'][None, :], x['xi'][:, None]),
                           method='cubic'),
        lambda x: measure.find_contours(x, 0.0),
        map(lambda x: float(data['dx']) * x)
    )
开发者ID:wd15,项目名称:extremefill2D,代码行数:30,代码来源:plot.py

示例10: find_image_contours

def find_image_contours(image):
    """Find contours in image."""
    # level = np.ptp(image) / 2
    level = 1050  # TODO: Different contour levels for ADC and T2w.
    kwargs = dict(fully_connected='low', positive_orientation='low')
    # kwargs = dict(fully_connected='high', positive_orientation='high')
    return measure.find_contours(image, level, **kwargs)
开发者ID:jupito,项目名称:dwilib,代码行数:7,代码来源:detectlesion.py

示例11: find_roi_edge

def find_roi_edge(mask):
    '''
    Finds the outline of a mask, using the find_contour function from
    skimage.measure.

    Parameters
    ----------
    mask : array_like
        the mask, a binary array

    Returns
    -------
    Array with coordinates of pixels in the outline of the mask
    '''

    # Ensure array_like input is a numpy.ndarray
    mask = np.asarray(mask)

    # Pad with 0s to make sure that edge ROIs are properly estimated
    mask_shape = np.shape(mask)
    padded_shape = (mask_shape[0] + 2, mask_shape[1] + 2)
    padded_mask = np.zeros(padded_shape)
    padded_mask[1:-1, 1:-1] = mask

    # detect contours
    outline = find_contours(padded_mask, level=0.5)

    # update coordinates to take into account padding and set so that the
    # coordinates are defined from the corners (as in the mask2poly function
    # in SIMA https://github.com/losonczylab/sima/blob/master/sima/ROI.py)
    for i in range(len(outline)):
        outline[i] -= 0.5

    return outline
开发者ID:atranvan,项目名称:fissa,代码行数:34,代码来源:roitools.py

示例12: contour

def contour():
	from skimage.filters import gaussian
	from skimage.segmentation import active_contour
	import scipy
	from skimage import measure
	from skimage import img_as_float

	image = io.imread(path + "bibme0.png")
	image = rgb2gray(image)
	#image = img_as_float(image)
	#print image

	##### OPTION 1

	contours = measure.find_contours(image,0.9)
	#print size(contours)
	#toprint(contours,'bibme0_contours.png')
	fig, ax = plt.subplots()
	#ax.imshow(contours, interpolation='nearest', cmap=plt.cm.gray)

	for n, contour in enumerate(contours):
	    ax.plot(contour[:,0], contour[:,1], linewidth=0.5)
	#print len(contours)

	ax.axis('image')
	ax.set_xticks([])
	ax.set_yticks([])

	fig.savefig(out_path + 'bibme0_contours.png')
	#plt.show()
	rotate90()
开发者ID:eason001,项目名称:imBot,代码行数:31,代码来源:imgpro.py

示例13: __transform

    def __transform(self):
        self.__img_gray = io.imread(self.__img_path, True)

        self.__otsu = filter.threshold_otsu(self.__img_gray) #Aplicar otsu para binarizar a imagem
        self.__img_gray = self.__img_gray < self.__otsu

        # Find contours at a constant value of 0.5
        self.__contours = measure.find_contours(self.__img_gray, 0.5)

        self.__arclen = 0.0
        for n, contour in enumerate(self.__contours):
            arclenTemp=0.0
            for indice, valor in enumerate(contour):
               if indice > 0:
                    d1 = math.fabs(round(valor[0]) - round(contour[indice-1,0]))
                    d2 = math.fabs(round(valor[1]) - round(contour[indice-1,1]))
                    if d1+d2>1.0:
                        arclenTemp+=math.sqrt(2)
                    elif d1+d2 == 1:
                        arclenTemp+=1

            if arclenTemp > self.__arclen:
                self.__arclen = arclenTemp
                self.__bestn = n
        #self.__bestn = 0
        print self.__contours[0]
开发者ID:glesio,项目名称:visaocomputacional,代码行数:26,代码来源:contorno.py

示例14: get_image_words

def get_image_words(image):
    # 删除包含的区域,返回正确的区域
    def remove_range(cells):
        # b in a
        def range_include(a, b):
            return b.up >= a.up and b.down <= a.down and b.left >= a.left and b.right <= a.right

        def range_cmp(range_data_a, range_data_b):
            return -1 if range_data_a.down - range_data_a.up < range_data_b.down - range_data_b.up else 1

        cells.sort(range_cmp)
        n = len(cells)
        ok = [True] * n
        for i in xrange(1, n):
            for j in xrange(i):
                if ok[j] and range_include(cells[i], cells[j]):
                    ok[j] = False
        new_cells = [cells[i] for i in xrange(n) if ok[i]]
        return new_cells

        # 单词排序

    def mycmp(range_data_a, range_data_b):
        return -1 if range_data_a.left < range_data_b.left else 1

    contours = measure.find_contours(image, 0.8)
    cells = []
    for contour in contours:
        up, down, left, right = min(contour[:, 0]), max(contour[:, 0]), min(contour[:, 1]), max(contour[:, 1])
        if down - up >= wordSpace or right - left >= wordSpace:
            cells.append(RangeData(up, down, left, right))

    cells = remove_range(cells)
    cells.sort(mycmp)
    return cells
开发者ID:hrwhisper,项目名称:Handwriting-recognition,代码行数:35,代码来源:OneWordSolve.py

示例15: loadmydata

def loadmydata():
    alla, allb, allc, alll = [], [], [], []
    indd=1
    for k in labels:
      for j in dataset[k]:
        im = imread(j)
        im = leaf_image_preprocess(im)
        img_filt = extract_leaf_stem(im)
        contours = measure.find_contours(img_filt, 0.8)
        a,b,c=parametrize(get_largest(contours))
        alla.append(a)
        allb.append(b)
        allc.append(c)
        alll.append(k)
#         fig = plt.figure()
#         ax = fig.add_subplot(111)
#         cwtmatr = signal.cwt(signal.decimate(a,4),signal.ricker, np.linspace(0.0001,1,200))
        #toplt=[]
        #for x in cwtmatr: 
            #if any(x[x>2]):
                #toplt.append(np.mean(x[x>2]))
            #else:
                #toplt.append(0)
        #ax.set_xlim([0,160])
        #ax.set_ylim([-3,7])
        print j 
    return alla, allb, allc, alll
开发者ID:scidam,项目名称:leafparam,代码行数:27,代码来源:main.py


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