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


Python numpy.int_函数代码示例

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


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

示例1: _find_nearest_node_ndarray

def _find_nearest_node_ndarray(rmg, coords, mode='raise'):
    column_indices = np.int_(
        np.around((coords[0] - rmg.node_x[0]) / rmg.node_spacing))
    row_indices = np.int_(
        np.around((coords[1] - rmg.node_y[0]) / rmg.node_spacing))

    return rmg.grid_coords_to_node_id(row_indices, column_indices, mode=mode)
开发者ID:brigidlynch,项目名称:landlab,代码行数:7,代码来源:raster_funcs.py

示例2: Init

        def Init(self):
                #boundary and domain condition
                self.lat  = io.read_PETSc_vec(self.config["-Metos3DBoundaryConditionInputDirectory"][0] + self.config["-Metos3DLatitudeFileFormat"][0])
                dz        = io.read_PETSc_vec(self.config["-Metos3DDomainConditionInputDirectory"][0] + self.config["-Metos3DLayerHeightFileFormat"][0])
                z         = io.read_PETSc_vec(self.config["-Metos3DDomainConditionInputDirectory"][0] + self.config["-Metos3DLayerDepthFileFormat"][0])
                self.lsm  = io.read_PETSc_mat(self.config["-Metos3DProfileInputDirectory"][0] + self.config["-Metos3DProfileMaskFile"][0])
                self.fice = np.zeros((self.profiles,np.int_(self.config["-Metos3DIceCoverCount"][0])),dtype=np.float_)
                for i in range(np.int_(self.config["-Metos3DIceCoverCount"][0])):
                        self.fice[:,i] = io.read_PETSc_vec(self.config["-Metos3DBoundaryConditionInputDirectory"][0] + (self.config["-Metos3DIceCoverFileFormat"][0] % i))

                self.bc         = np.zeros(2,dtype=np.float_)
                self.dc         = np.zeros((self.ny,2),dtype=np.float_)
                self.dc[:,0]    = z
                self.dc[:,1]    = dz

                self.u          = np.array(self.config["-Metos3DParameterValue"],dtype=np.float_)
                self.dt         = np.float_(self.config["-Metos3DTimeStep"][0])
                self.nspinup    = np.int_(self.config["-Metos3DSpinupCount"][0])
                self.ntimestep  = np.int_(self.config["-Metos3DTimeStepCount"][0])


                self.matrixCount  = np.int_(self.config["-Metos3DMatrixCount"][0])
                self.U_PODN        = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'N/'+ self.config["-Metos3DMatrixPODFileFormat"][0])
                self.U_PODDOP       = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'DOP/'+ self.config["-Metos3DMatrixPODFileFormat"][0])
                self.U_DEIMN       = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'N/'+ self.config["-Metos3DMatrixDEIMFileFormat"][0])
                self.U_DEIMDOP       = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'DOP/'+ self.config["-Metos3DMatrixDEIMFileFormat"][0])
                self.DEIM_IndicesN = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'N/'+ self.config["-Metos3DDEIMIndicesFileFormat"][0])
                self.DEIM_IndicesDOP = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'DOP/'+ self.config["-Metos3DDEIMIndicesFileFormat"][0])

                

                self.AN = np.ndarray(shape=(self.matrixCount,self.U_PODN.shape[1],self.U_PODN.shape[1]), dtype=np.float_, order='C')
                self.ADOP = np.ndarray(shape=(self.matrixCount,self.U_PODDOP.shape[1],self.U_PODDOP.shape[1]), dtype=np.float_, order='C')

                for i in range(0,self.matrixCount):
                        self.AN[i] = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'N/'+ self.config["-Metos3DMatrixReducedFileFormat"][0] % i)
                        self.ADOP[i] = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'DOP/'+ self.config["-Metos3DMatrixReducedFileFormat"][0] % i)
        
                self.PN = np.ndarray(shape=(self.matrixCount,self.U_PODN.shape[1],self.U_DEIMN.shape[1]), dtype=np.float_, order='C')
                self.PDOP = np.ndarray(shape=(self.matrixCount,self.U_PODDOP.shape[1],self.U_DEIMDOP.shape[1]), dtype=np.float_, order='C')
                for i in range(0,self.matrixCount):
                        self.PN[i] = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'N/'+ self.config["-Metos3DMatrixReducedDEINFileFormat"][0] % i)
                        self.PDOP[i] = np.load(self.config["-Metos3DMatrixInputDirectory"][0] +'DOP/'+ self.config["-Metos3DMatrixReducedDEINFileFormat"][0] % i)

                #precomputin the interplaton indices for a year         
                [self.interpolation_a,self.interpolation_b,self.interpolation_j,self.interpolation_k] = util.linearinterpolation(2880,12,0.0003472222222222)

                self.yN     = np.ones(self.ny,dtype=np.float_) * np.float_(self.config["-Metos3DTracerInitValue"])[0]
                self.yDOP     = np.ones(self.ny,dtype=np.float_) * np.float_(self.config["-Metos3DTracerInitValue"])[1]
                self.y_redN = np.dot(self.U_PODN.T,self.yN)
                self.y_redDOP = np.dot(self.U_PODDOP.T,self.yDOP)

                self.qN     = np.zeros(self.DEIM_IndicesN.shape[0],dtype=np.float_)
                self.qDOP     = np.zeros(self.DEIM_IndicesDOP.shape[0],dtype=np.float_)

                self.J,self.PJ = util.generateIndicesForNonlinearFunction(self.lsm,self.profiles,self.ny)

                self.out_pathN     = self.config["-Metos3DTracerOutputDirectory"][0] +self.config["-Metos3DSpinupMonitorFileFormatPrefix"][0] + self.config["-Metos3DSpinupMonitorFileFormatPrefix"][1] +self.config["-Metos3DTracerOutputFile"][0]
                self.out_pathDOP     = self.config["-Metos3DTracerOutputDirectory"][0] +self.config["-Metos3DSpinupMonitorFileFormatPrefix"][0] + self.config["-Metos3DSpinupMonitorFileFormatPrefix"][1] +self.config["-Metos3DTracerOutputFile"][1]
                self.monitor_path = self.config["-Metos3DTracerMointorDirectory"][0] +self.config["-Metos3DSpinupMonitorFileFormatPrefix"][0] + self.config["-Metos3DSpinupMonitorFileFormatPrefix"][1] +self.config["-Metos3DTracerOutputFile"][0]
开发者ID:neeljp,项目名称:pod_deim,代码行数:60,代码来源:ROM_ndop.py

示例3: add_pbc_jncol

def add_pbc_jncol(data,rand):
   '''If the input is a periodic box and los is along z axis then jacknife region is simply equal area region in the x-y space which can be done in using this function and not needed to be supplied with data file make sure that njn is a perfect square'''

   #adding jacknife regions
   if(args.njn>0 and args.los==1):
      POS_min,POS_max, blen=getminmax(data,rand=rand)
      NJNx=np.int(np.sqrt(args.njn))
      NJNy=np.int(args.njn/NJNx)
      for ii in (0,2):
	 if(ii==0): mat=data
	 else: mat=rand
	 
         #get the x and y indx as integers
	 indx=np.int_(NJNx*(mat[:,0]-POS_min[0])/blen[0])
	 indy=np.int_(NJNy*(mat[:,1]-POS_min[1])/blen[1])
         #apply modulo operation on x an y index
	 indx=np.mod(indx,NJNx)
	 indy=np.mod(indy,NJNy)

	 #convert index to integers
	 #indx.astype(np.int64); indy.astype(np.int64);
	 jnreg=NJNy*indx+indy
	 mat=np.column_stack([mat,jnreg])

         if(ii==0): data=mat
	 else: rand=mat

      return data,rand
   else:
      print('not appropriate input to add jacknife internally')
      sys.exit()
      return 0
开发者ID:desihub,项目名称:LSS,代码行数:32,代码来源:Runme_Correlation.py

示例4: initialize

def initialize(video_capture,rot_angle, pt1, pt2, ppl_width):
    #read image
    ret, image = video_capture.read()    
    
    (hh, ww) = image.shape[:2]
    
    #rotate
    M = None;
    if (rot_angle != 0):
        center = (ww / 2, hh / 2)
        M = cv2.getRotationMatrix2D(center, rot_angle, 1.0)    
    
    image = imutils.resize(image, width=min(400, image.shape[1]))
    
    ##mask after resize
    resize_ratio = image.shape[1] / float(ww) 
    
    #max_min_ppl_size  
    ppl_size=[50,100]
    ppl_size[0] = np.ceil(ppl_width * resize_ratio * 1.4)
    ppl_size[1] = np.ceil(ppl_width * resize_ratio * 0.8)
    #print max_ppl_size
    
    ROI_1 = np.int_(np.dot(pt1,resize_ratio))   
    ROI_2 = np.int_(np.dot(pt2,resize_ratio))
    
    
    return [ww, hh, M, ppl_size, ROI_1, ROI_2]
开发者ID:ChuaKhangHui,项目名称:Raspi,代码行数:28,代码来源:pb_combine.py

示例5: DepositDataToGrid3D

def DepositDataToGrid3D(data, coords, N, hsml, gridres, rmax, griddata):
    norm =  2.5464790894703255 #8/np.pi for 3D
    grid_dx = 2*rmax/(gridres-1)
    zSqr = coords[:,2]*coords[:,2]
    hsml_plane = np.sqrt(hsml[:]*hsml[:] - zSqr)
    shift_coords = coords[:,:2] + rmax
    
    gxmin = np.int_((shift_coords[:,0] - hsml_plane[:])/grid_dx + 0.5)
    gxmax = np.int_((shift_coords[:,0] + hsml_plane[:])/grid_dx)
    gymin = np.int_((shift_coords[:,1] - hsml_plane[:])/grid_dx + 0.5)
    gymax = np.int_((shift_coords[:,1] + hsml_plane[:])/grid_dx)
    
    for i in xrange(N):
        h = hsml[i]
        mh3 = data[i,:]/h**3
        z2 = zSqr[i]
    
        if gxmin[i] < 0:
            gxmin[i] = 0
        if gxmax[i] > gridres - 1:
            gxmax[i] = gridres - 1
        if gymin[i] < 0:
            gymin[i] = 0
        if gymax[i] > gridres - 1:
            gymax[i] = gridres - 1
        for gx in xrange(gxmin[i], gxmax[i]+1):
            for gy in xrange(gymin[i], gymax[i]+1):
                q = np.sqrt((shift_coords[i,0] - gx*grid_dx)**2 + (shift_coords[i,1] - gy*grid_dx)**2 + z2)/h
                if q <= 0.5:
                    griddata[gy, gx,:] += (1 - 6*q**2 + 6*q**3) * mh3
                elif q <= 1.0:
                    griddata[gy, gx,:] += (2*(1-q)**3) * mh3

    griddata[:] = norm*griddata[:]
开发者ID:omgspace,项目名称:GHOST,代码行数:34,代码来源:GridDeposit.py

示例6: get_many_patches

def get_many_patches(image, patch_shape, centers,
                     flat=True, step=1, force_pure_python=False):
    """Return the patches at given centers"""
    
    patch_shape = tuple(patch_shape)
    centers = np.reshape(np.asarray(centers, dtype=np.int_), (-1, len(patch_shape)))
    
    ndims = len(patch_shape)
    if ndims in [2,3] and "_get_many_patches" in globals() and not force_pure_python:
        # 3d version (efficient Cython implementation)
        patches = _get_many_patches(ndims, image, patch_shape, centers, step)
    else:
        # Extract patches (pure Python version)
        grid_slices = tuple(slice(-(i//2), i-i//2, step) for i in patch_shape)
        grid = np.reshape(np.mgrid[grid_slices], (len(patch_shape), -1))
        points = tuple(np.int_(centers.T[:,:,np.newaxis]) + np.int_(grid[:,np.newaxis,:]))
        patches = image[points]
    
    # Compute the final patch shape taking into acount the step
    final_shape = tuple((sh - 1)/step + 1 for sh in patch_shape)
    
    channels = image.shape[len(patch_shape):]
    if not flat:
        patches = np.reshape(patches, (-1,) + tuple(final_shape) + channels)
    else:
        patches = np.reshape(patches, (len(patches), np.prod(final_shape + channels)))
    return patches
开发者ID:cjaques,项目名称:ilastik,代码行数:27,代码来源:patch_utils.py

示例7: azimToBeam

    def azimToBeam(self, azim):
        ''' Get azimuth of given beam.  Return a negative beam number (offset by
        one instead of zero) if the azimuth corresponds to the back lobe.
        Return np.nan if the azimuth is not covered by any beam.

        **Args**: 
            * **azim** (float): beam azimuth [deg. East]
        **Returns**:
            * **beam** (int): beam number
        '''
        import numpy as np

        # Assume the azimuth comes from the front lobe
        phi = np.radians(azim - self.boresite)
        delta = np.degrees(np.arctan2(np.sin(phi), np.cos(phi)))
        beam = np.round(delta / self.bmsep + (self.maxbeam - 1) / 2.)

        if beam < 0.0 or beam > self.maxbeam:
            # This azimuth lies outside the front lobe
            phi = np.radians(self.boresite - azim - 180.0)
            delta = np.degrees(np.arctan2(np.sin(phi), np.cos(phi)))
            beam = np.round(delta / self.bmsep + (self.maxbeam - 1) / 2.)

            # Seperate back lobe azimuths from azimuths outside of either
            # field-of-view
            if beam >= 0 and beam < self.maxbeam:
                beam = -np.int_(beam + 1)
            else:
                beam = np.nan
        else:
            beam = np.int_(beam)

        return beam
开发者ID:doby123,项目名称:davitpy,代码行数:33,代码来源:radStruct.py

示例8: EField

def EField(X,Q,gamma,kern,steps):
    N=X.shape[0];
    X[:,2]=X[:,2]*gamma
    X=X/steps
    X_min=np.min(X,axis=0)
    X_mid=np.dot(Q,X)/np.sum(Q);
    X_off=np.floor(X_min-X_mid)+X_mid;
    X=X-X_off  
    nx,ny,nz=np.int_(3+np.floor(np.max(X,axis=0)))
    nzny=nz*ny
    Xi=np.int_(np.floor(X)+1)
    inds=np.int_(Xi[:,0]*nzny+Xi[:,1]*nz+Xi[:,2]) # 3d -> 1d
    q=np.bincount(inds,Q,nzny*nx)
    print len(q), nx*ny*nz
    
    q=q.reshape(nx,ny,nz)
    #t0=time.time()   
    print q.shape, steps
    p,kern=Phi(q,kern,steps)
    #t1=time.time(); print t1-t0
    Ex=np.zeros(p.shape);Ey=np.zeros(p.shape);Ez=np.zeros(p.shape);
    Ex[:nx-1,:,:]=(p[:nx-1,:,:]-p[1:nx,:,:])/steps[0]
    Ey[:,:ny-1,:]=(p[:,:ny-1,:]-p[:,1:ny,:])/steps[1]
    Ez[:,:,:nz-1]=(p[:,:,:nz-1]-p[:,:,1:nz])/steps[2]
    Exyz=np.zeros((N,3))
    Exyz[:,0]=ndimage.map_coordinates(Ex,np.c_[X[:,0],X[:,1]+0.5,X[:,2]+0.5].T,order=1)*gamma
    Exyz[:,1]=ndimage.map_coordinates(Ey,np.c_[X[:,0]+0.5,X[:,1],X[:,2]+0.5].T,order=1)*gamma
    Exyz[:,2]=ndimage.map_coordinates(Ez,np.c_[X[:,0]+0.5,X[:,1]+0.5,X[:,2]].T,order=1)
    #t1=time.time();    print t1-t0
    return Exyz
开发者ID:iagapov,项目名称:desy,代码行数:30,代码来源:space_charge_ver05.py

示例9: totalPower

def totalPower(latitude, timeTuple):
	global shell_normal
	global shell_faceO
	global shell_vertO
	matrixImport()
	month = timeTuple[1]
	day = timeTuple[2]
	hour = timeTuple[3]
	heading = 85 # Moving SSE
	shell_heading = heading
	shell_azimuths = 180/math.pi*numpy.arctan2(-shell_normal[:,1] ,shell_normal[:,0]) + heading
	shell_tilts = 90 - 180/math.pi*numpy.arcsin(shell_normal[:,2])
	a = shell_vertO[numpy.int_(shell_faceO[:,0]),:]
	b = shell_vertO[numpy.int_(shell_faceO[:,1]),:]
	c = shell_vertO[numpy.int_(shell_faceO[:,2]),:]
	v1 = b - a
	v2 = c - a
	temp = numpy.cross(v1,v2)**2
	temp = numpy.sum(temp, 1)
	shell_Area = 0.5*temp**0.5
	#shell_area = numpy.sum(shell_Area)
	shell_flux = incident_radiation(month, day, hour, shell_tilts, shell_azimuths, latitude)
	shell_power = numpy.dot(shell_flux,shell_Area)
	#shell_fluxavg = shell_power/shell_area
	#return shell_fluxavg
	return shell_power
开发者ID:kagelump,项目名称:calsol,代码行数:26,代码来源:Predictor.py

示例10: _find_nearest_node_ndarray

def _find_nearest_node_ndarray(rmg, coords, mode='raise'):
    """Find the node nearest to a point.

    Parameters
    ----------
    rmg : RasterModelGrid
        A RasterModelGrid.
    coords : tuple of float
        Coordinates of test points as *x*, then *y*.
    mode : {'raise', 'wrap', 'clip'}, optional
        What to do with out-of-bounds indices (as with
        numpy.ravel_multi_index).

    Returns
    -------
    ndarray
        Nodes that are closest to the points.

    Examples
    --------
    >>> from landlab.grid.raster_funcs import _find_nearest_node_ndarray
    >>> from landlab import RasterModelGrid
    >>> import numpy as np
    >>> grid = RasterModelGrid((4, 5))
    >>> _find_nearest_node_ndarray(grid, (.25, 1.25))
    5
    >>> _find_nearest_node_ndarray(grid, (.75, 2.25))
    11
    """
    column_indices = np.int_(
        np.around((coords[0] - rmg.node_x[0]) / rmg.node_spacing))
    row_indices = np.int_(
        np.around((coords[1] - rmg.node_y[0]) / rmg.node_spacing))

    return rmg.grid_coords_to_node_id(row_indices, column_indices, mode=mode)
开发者ID:jennyknuth,项目名称:landlab,代码行数:35,代码来源:raster_funcs.py

示例11: getSuperPixelColorHistogram

def getSuperPixelColorHistogram(superpixels, image):
    colors = []
    #newIm = image
    numSuperpixels = np.max(superpixels)+1
    for i in xrange(0,numSuperpixels):
        temp = np.zeros((1,64),dtype = float)
        indices = np.where(superpixels==i)
        color = image[indices]
        for j in xrange(0,color.shape[0]):
            r = np.int_(color[j][0]/0.25)
            g = np.int_(color[j][1]/0.25)
            b = np.int_(color[j][2]/0.25)
            if r ==4:
                r = 3
            if g == 4:
                g = 3
            if b == 4:
                b = 3
            x = 16*r+4*g+b*1
            temp[0][x] = temp[0][x]+1
        #min_max_scaler = preprocessing.MinMaxScaler()
        #t = min_max_scaler.fit_transform(temp[0])
        #print t
        colors.append(temp[0])
    #showPlots(newIm, numSuperpixels, superpixels)
    return np.array(colors)
开发者ID:HastyJ,项目名称:Road-Estimation,代码行数:26,代码来源:superpixel.py

示例12: main

def main():
    # объект dtype=float32
    f = np.float32(1.0)
    print('Объект: {}\nТип данных: {}'.format(f, type(f)))

    # объект np.ndarray, полученный из python списка, с автоматическим определеникм dtype
    ar = np.array([1, 2, 3])
    print('Массив: {}\nТип данных массива (dtype): {}\nТип данных элемента массива: {}'.format(ar, type(ar), type(ar[0])))

    # объект np.ndarray, полученный из python списка
    ar_int32 = np.array([1, 2, 3], dtype=np.int32)
    print('Массив: {}\nТип данных массива (dtype): {}\nТип данных элемента массива: {}'.format(ar_int32, type(ar_int32), type(ar_int32[0])))

    # объект np.ndarray, полученный при помощи конструктора типа dtype
    i_int = np.int_(10)
    print('Объект: {}\nТип данных: {}'.format(i_int, type(i_int)))

    ar_int = np.int_([10, 20, 30])
    print('Массив: {}\nТип данных масива (dtype: {}\nТип данных элемента массива: {}'.format(ar_int, type(ar_int), type(ar_int[0])))

    ar_bool = np.bool_([0, 1, 0, 0, 1, 1, 1])
    print('Тип данных массива: {}'.format(ar_bool.dtype))

    ar_int64 = np.array(range(100), dtype=np.int_)
    print('Тип данных массива: {}'.format(ar_int64.dtype))

    ar_float = np.array([1.03, 1, -5.9, 4.6], dtype=np.float16)
    print('Массив ndarray: {}'.format(ar_float))
    print('Тип данных массива: {}'.format(type(ar_float)))

    ar_scalar = ar_float[3]
    print('Значение скаляра массива: {}'.format(ar_scalar))
    print('Тип данных скаляра массива: {}'.format(ar_scalar.dtype))
开发者ID:arheo,项目名称:python_core,代码行数:33,代码来源:data_type.py

示例13: project_lane_lines

def project_lane_lines(img,left_fitx,right_fitx,yvals):
    
    # Create an image to draw the lines on
    color_warp = np.zeros_like(img).astype(np.uint8)

    # Recast the x and y points into usable format for cv2.fillPoly()
    pts_left = np.array([np.transpose(np.vstack([left_fitx, yvals]))])
    pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, yvals])))])
    pts = np.hstack((pts_left, pts_right))

    # Draw the lane onto the warped blank image
    cv2.polylines(color_warp, np.int_([pts]), isClosed=False, color=(255,0,0), thickness=20)
    cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))
    
    
        
    undist = undistort(img)  
    #sp = (550, 310) 
    #ep = (700, 460)
    #for i in range(4):
        #center = ((ep[0] + sp[0])/2 , )
        #cv2.rectangle(undist, (550, 310), (700, 460), (0,0,255), 4)
    unwarp,Minv = warp(img,bird_view=False)

    

    # Warp the blank back to original image space using inverse perspective matrix (Minv)
    newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) 
    # Combine the result with the original image
    result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)
    return result
开发者ID:dvu4,项目名称:CarND-Advanced-Lane-Lines,代码行数:31,代码来源:README.py

示例14: get_data_set

def get_data_set():
    data_set = [] 
    categories = {}
    next_cat_index = 1
    first_line = True
    with open ('original_data/numerai_training_data.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile)
        for row in spamreader:
            if not first_line: #Skip first line
                data_set_item = np.int_(row[0:14]).astype(np.int)
                category = row[14]
                try:
                    #if KeyError add a new category
                    cat_index = categories[category] 
                except KeyError as e:
                    categories[category] = next_cat_index
                    next_cat_index += 1
                    cat_index = categories[category]
                data_set_item = np.append(data_set_item, np.int_([cat_index]))
                data_set_item = np.append(data_set_item, np.int_(row[15:]).astype(np.int))
                data_set.append(data_set_item)
            else:
                first_line = False 
    data_set = np.int_(data_set)
    return (data_set, categories)
开发者ID:rob-nn,项目名称:numerai,代码行数:25,代码来源:read.py

示例15: draw_hough_line

def draw_hough_line(image, dist, theta, color=0):
    """
    Draws a line described by the hough transform to an image

    :param image: Image to draw on
    :param dist: Hough transform distance
    :param theta: Hough transform angle
    :param color: intensity to draw line
    """

    rows, cols = image.shape

    if abs(theta) < pi/4:
        # Find the x (col) intercepts
        x0 = int_(dist/cos(theta))
        x1 = int_(x0 - rows * sin(theta))
        intercepts = (0, x0, rows, x1)

    else:
        # Find the y (row) intercepts
        y0 = int_(dist/sin(theta))
        y1 = int_(y0 + cols * cos(theta))
        intercepts = (y0, 0, y1, cols)

    r, c = line(*intercepts)

    # Check to make sure each point stays in the image bounds and draw it
    for n in range(r.size):
        if r[n] >= 0 and c[n] >= 0:
            if r[n] < rows and c[n] < cols:
                image[r[n], c[n]] = color
开发者ID:danlopez00,项目名称:crop_predict,代码行数:31,代码来源:segmentation.py


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