def number_of_images(self, sourceposition):
        rc=self.radial_caustic()
        tc=self.tangential_caustic()

        if usePath:
        
            # New Matplotlib:
            rc=Path(rc)
            tc=Path(tc)
            if rc.contains_points(np.atleast_2d(sourceposition))[0]:
               if tc.contains_points(np.atleast_2d(sourceposition))[0]:
                   return 4
               return 2
            if tc.contains_points(np.atleast_2d(sourceposition))[0]:
               return 3
        
        else:
            # Old Matplotlib:
            if nxutils.points_inside_poly(np.atleast_2d(sourceposition),rc)[0]:
                if nxutils.points_inside_poly(np.atleast_2d(sourceposition),tc)[0]:
                    return 4
                return 2
            if nxutils.points_inside_poly(np.atleast_2d(sourceposition),tc)[0]:
                return 3

        return 1
Exemple #2
0
    def selectArea(self, ptlist, latlon=False, reduced=None):
        """Select an area of the grid.
        
        Parameters
        ----------
        ptlist : list
        latlon : bool
        reduced : int
            The amount by which the index array should be short (i.e., 1 for
            basic difference, 2 for center difference).
        """
        ptlist = np.asarray(ptlist)
        if latlon: 
            ptlist[:,0], ptlist[:,1] = self.basemap(ptlist[:,0], ptlist[:,1])
        # create the polygon
        path = Path(ptlist)

        if reduced is not None:
            X, Y = np.meshgrid(self.x[:-reduced], self.y[:-reduced])
            areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
            areaind = areaind.reshape((self.shape[0]-reduced,
                                       self.shape[1]-reduced))
        else:
            X, Y = np.meshgrid(self.x, self.y)
            areaind = path.contains_points(zip(X.flatten(), Y.flatten()))
            areaind = areaind.reshape(self.shape)
        # return array indices
        return areaind
def processPolygon(polygon, rows, columns, mode):
    """
    Finds the points within a particular polygon
    """
    length = len(polygon)
    polygon.append((0.0, 0.0))
    codes = [Path.MOVETO]
    for index in range(length - 1):
        codes.append(Path.LINETO)
    codes.append(Path.CLOSEPOLY)
    path = Path(polygon, codes)
    points = []
    if mode == 'V':
        for index in range(rows):
            row = [(x, index) for x in range(columns)]
            check = path.contains_points(row)
            temp_points = ([row[i] for i, j in enumerate(check) if j == True and not contains(row[i], polygon)])
            if (len(temp_points) > 0):
                points.append(temp_points)
    else:
        for index in range(columns):
            col = [(index, x) for x in range(rows)]
            check = path.contains_points(col)
            temp_points = ([col[i] for i, j in enumerate(check) if j == True and not contains(col[i], polygon)])
            if (len(temp_points) > 0):
                points.append(temp_points)
    return points
Exemple #4
0
def paths_in_shape(paths):

    shape = shape_(shape_path)
    
    minx, miny, maxx, maxy = shape.bounds
    
    #print minx; print miny; print maxx; print maxy
    #bounding_box = geometry.box(minx, miny, maxx, maxy)

    #generate random points within bounding box! 
    
    sf = shapefile.Reader(shape_path)
    
    shape = sf.shapes()[0]

    #find polygon nodes lat lons
    verticies = shape.points
    
    #convert to a matplotlib path class!
    polygon = Path(verticies)
    points_in_shape = polygon.contains_points(paths)
    
    points_in_shape = paths[points_in_shape == True]
    
    return points_in_shape
  def _gating(self,DF_array_data,x_ax,y_ax,coords):
 
      #np.ones(DF_array_data.shape[0],dtype=bool)
      gate=Path(coords,closed=True)
      projection=np.array(DF_array_data[[x_ax,y_ax]])
      index=gate.contains_points(projection)
      return index
Exemple #6
0
    def estimate_mean_extinction(self, poly):
        """Estimate the mean extinction Av in within a footprint.

        Parameters
        ----------
        poly : ndarray
            The RA,Dec polygon (a rectangle) defining the footprint.
        """
        sigma_dust = self._f[0].data
        ny, nx = sigma_dust.shape

        # Make a coordinate grid out of RA, Dec across the dust map
        y_image, x_image = np.mgrid[0:ny, 0:nx]
        y = y_image.reshape(nx * ny)
        x = x_image.reshape(nx * ny)
        ra, dec = self._wcs.all_pix2world(x, y, 0)
        points = np.vstack((ra, dec)).T

        # Find all pixels in the footprint
        path = Path(poly, closed=False)
        in_poly = path.contains_points(points)
        s = np.where(in_poly)[0]
        dust_pixels = sigma_dust[y[s], x[s]]
        mean = np.nanmean(dust_pixels)

        # Estimate Av from the Lewis et al attenuation law
        return 10. ** (-5.4) * mean
Exemple #7
0
    def _endGate(self, event):
        #draw gate rectangle
        start_x = self.start_x if self.start_x < event.xdata else event.xdata
        start_y = self.start_y if self.start_y < event.ydata else event.ydata
        width = np.absolute(event.xdata-self.start_x)
        height = np.absolute(event.ydata-self.start_y)
        rect = Rectangle((start_x, start_y), width, height, 
                         fill=False, ec='black', alpha=1, lw=2)
        self.ax.add_patch(rect)
        self.canvas.draw()

        #disable mouse events
        self.canvas.mpl_disconnect(self.buttonPress)
        self.canvas.mpl_disconnect(self.buttonRelease)
        self.canvas.get_tk_widget().config(cursor='arrow')
 
        #save cell gate
        gate = Path([[start_x, start_y], 
                     [start_x + width, start_y],
                     [start_x + width, start_y + height], 
                     [start_x, start_y + height],
                     [start_x, start_y]])
        gated_cells = self.scdata.tsne.index[gate.contains_points(self.scdata.tsne)]
        self.gates[self.gateName.get()] = gated_cells

        #replot tSNE w gate colored
        self.fig.clf()
        plt.scatter(self.scdata.tsne['x'], self.scdata.tsne['y'], s=10, edgecolors='none', color='lightgrey')
        plt.scatter(self.scdata.tsne.ix[gated_cells, 'x'], self.scdata.tsne.ix[gated_cells, 'y'], s=10, edgecolors='none')
        self.canvas.draw()

        self.setGateButton.config(state='disabled')
        self.visMenu.entryconfig(6, state='disabled')
 def onselect(self, verts):
     path = Path(verts)
     self.ind = np.nonzero(path.contains_points(self.xys))[0]
     self.fc[:, -1] = self.alpha_other
     self.fc[self.ind, -1] = 1
     self.collection.set_facecolors(self.fc)
     self.canvas.draw_idle()
def get_mask_img(transform, target_bin, camera_model):
    """
    :param point: point that is going to be transformed
    :type point: PointStamped
    :param transform: camera_frame -> bbox_frame
    :type transform: Transform
    """
    # check frame_id of a point and transform just in case
    assert camera_model.tf_frame == transform.header.frame_id
    assert target_bin.bbox.header.frame_id == transform.child_frame_id

    transformed_list = [
            do_transform_point(corner, transform)
            for corner in target_bin.corners]
    projected_points = project_points(transformed_list, camera_model)

    # generate an polygon that covers the region
    path = Path(projected_points)
    x, y = np.meshgrid(
            np.arange(camera_model.width),
            np.arange(camera_model.height))
    x, y = x.flatten(), y.flatten()
    points = np.vstack((x, y)).T
    mask_img = path.contains_points(
            points).reshape(
                    camera_model.height, camera_model.width
                ).astype('bool')
    return mask_img
Exemple #10
0
def test_point_in_path_nan():
    box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
    p = Path(box)
    test = np.array([[np.nan, 0.5]])
    contains = p.contains_points(test)
    assert len(contains) == 1
    assert not contains[0]
Exemple #11
0
def Ablate_outside_area(n_pixels, contour_coords):
    ''' Function takes points from contour and returns list of coordinates
        lying outside of the contour - to be used to ablate image    '''
    
    #Search points outside and black them out:
    all_points = []
    for i in range(n_pixels):
        for j in range(n_pixels):
            all_points.append([i,j])

    all_points = np.array(all_points)
    vertixes = np.array(contour_coords) 
    vertixes_path = Path(vertixes)
    
    mask = vertixes_path.contains_points(all_points)
    ablate_coords=[]
    counter=0
    for i in range(n_pixels):
        for j in range(n_pixels):
            if mask[counter] == False:
                #images_processed[100][i][j]=0
                ablate_coords.append([i,j])
            counter+=1
            
    return ablate_coords
def get_path( img, verts ):
    #verts=array( verts, int)
    path1 = Path(verts)
    print path1
    dx,dy=img.shape
    data = zeros( [dx,dy,2])
    data[:,:,0]= range(dx)
    for i in range(dy):
        data[i,:,1] = i 
    #print data
    data=data.reshape( [dx*dy,2])
    #print data.shape
    #print path1,data
    index = path1.contains_points(data)
    print index.shape, len(where(index)[0])
    #print data[index, :2]
    
    #plot(data[:,0],data[:,1], 'b.')
    fig, ax = plt.subplots(nrows=1)
    vmin=img.min();vmax=img.max()
    ax.imshow( img,cmap=plt.get_cmap('winter'), vmin=vmin,vmax=vmax )
    #ax.set_xlim(0,dx-1)
    #ax.set_ylim(0,dy-1)
    patch = patches.PathPatch(path1, facecolor='orange', lw=2)
    gca().add_patch(patch)
    plot(data[index,0], data[index,1], 'r.')
    show() 
Exemple #13
0
 def subsample(self, vertices):
     xiyi = np.vstack((self.traj_lon[0,:], self.traj_lat[0,:])).T
     mpath = MplPath( vertices )
     outside_area = ~mpath.contains_points(xiyi)
     self.init_x, self.init_y, self.init_z, self.init_s, \
                self.traj_lon, self.traj_lat, self.traj_depth, self.traj_time, self.final_z = \
              [x.compress(outside_area,axis=-1)  for x in (self.init_x, self.init_y, self.init_z, self.init_s,
                self.traj_lon, self.traj_lat, self.traj_depth, self.traj_time, self.final_z)]
Exemple #14
0
def test_point_in_path():
    # Test #1787
    verts2 = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]

    path = Path(verts2, closed=True)
    points = [(0.5, 0.5), (1.5, 0.5)]

    assert np.all(path.contains_points(points) == [True, False])
Exemple #15
0
    def _spatial_selection(self, dataset):
        data_ra = dataset['ra']
        data_dec = dataset['dec']
        xy = np.vstack((data_ra, data_dec)).T
        print "xy.shape", xy.shape

        polygon = Path(self.poly, closed=False)
        inside = polygon.contains_points(xy)
        return dataset[inside == True]  # noqa
Exemple #16
0
class Poly(Shape):
    def __init__(self, name, coordinates, top=1e9, bottom=-1e9):
        super(Poly, self).__init__('POLY', name, coordinates, top, bottom)
        self.border = Path(np.reshape(coordinates, (len(coordinates) // 2, 2)))

    def checkInside(self, lat, lon, alt):
        points = np.vstack((lat,lon)).T
        inside = np.all((self.border.contains_points(points), self.bottom <= alt, alt <= self.top), axis=0)
        return inside
 def _gating(self, DF_array_data, x_ax, y_ax, coords):
     """
     Returns a logical index given set of gate coordinates
     """
     log.debug('Applying gate coords {} to axes {} and {}'.format(coords, x_ax, y_ax))
     gate = Path(coords, closed=True)
     projection = np.array(DF_array_data[[x_ax, y_ax]])
     index = gate.contains_points(projection)
     return index
def segments_in_polygon(segments, poly_verts):
    """Go to the centroid of each segment, see if it is in the polygon
    """
    segments = np.array(segments, dtype=float)
    pt1 = segments[:, 0]
    pt2 = segments[:, 1]
    centroids = (pt1 + pt2) / 2.
    p = Path(poly_verts)
    return p.contains_points(centroids)
Exemple #19
0
def _in_polygon(points, polygon):
    """Return the points that are inside a polygon."""
    from matplotlib.path import Path
    points = _as_array(points)
    polygon = _as_array(polygon)
    assert points.ndim == 2
    assert polygon.ndim == 2
    path = Path(polygon, closed=True)
    return path.contains_points(points)
 def _gating_box(self,DF_array_data,x_ax,y_ax,c):
     '''
     corners should be [x1,y1,x2,y2]
     '''
     coords=[(c[0],c[1]),(c[2],c[1]),(c[2],c[3]),(c[0],c[3]),(c[0],c[1])]
     gate=Path(coords,closed=True)
     projection=np.array(DF_array_data[[x_ax,y_ax]])
     index=gate.contains_points(projection)
     return index
Exemple #21
0
def test_point_in_path():
    # Test #1787
    verts2 = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]

    path = Path(verts2, closed=True)
    points = [(0.5, 0.5), (1.5, 0.5)]
    ret = path.contains_points(points)
    assert ret.dtype == 'bool'
    assert np.all(ret == [True, False])
Exemple #22
0
def xyz_in_rectangle(x, y, z, ll, lr, ur, ul):
    domain = Path([ll, lr, ur, ul, ll], [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])

    condition = domain.contains_points(list(zip(x, y)))
    xrect = np.extract(condition, x)
    yrect = np.extract(condition, y)
    zrect = np.extract(condition, z)

    return xrect, yrect, zrect
Exemple #23
0
 def frac_inside_poly(self, x,y,polyxy):
     """Calculate the fraction of points x,y inside polygon polyxy.
     
     polyxy -- list of x,y coordinates of vertices.
 
     """
     xy = numpy.vstack([x,y]).transpose()
     path = Path(polyxy) 
     return float(sum(path.contains_points(xy)))/len(x)
Exemple #24
0
    def pressContour(self, event):
        if event.inaxes==None: return
        if event.button != 1: return
        
        # new contour
        if self.poly is None:
            self.poly = Polygon( [(event.xdata , event.ydata)] , animated=False , alpha = .3 , color = 'g')
            self.ax.add_patch(self.poly)
            self.line, = self.ax.plot([event.xdata] , [event.ydata] , 
                                    color = 'g',
                                    linewidth = 2 ,
                                    marker = 'o' ,
                                    markerfacecolor='g', 
                                    animated=False)
            #~ self.canvas.draw()
            self.redraw()
            return
            
        

        # event near a point
        xy = asarray(self.poly.xy)
        xyt = self.poly.get_transform().transform(xy)
        xt, yt = xyt[:, 0], xyt[:, 1]
        
        print '#######'
        d = sqrt((xt-event.x)**2 + (yt-event.y)**2)
        indseq = nonzero(equal(d, amin(d)))[0]
        self._ind = indseq[0]
        if d[self._ind]>=self.epsilon:
            self._ind = None

        self.a=list(numpy.copy(self.poly.xy))
        for i,j in enumerate(self.a):
            self.a[i]=tuple(j)
        
        # new point
        if self._ind is None:
            b=float(event.xdata)
            c=float(event.ydata)
            d=(b,c)
            e=[d]
            #self.a=numpy.append(self.a,e)
            self.a.extend(e)
            self.line.set_xdata( list(self.line.get_xdata()) + [ event.xdata] )
            self.line.set_ydata( list(self.line.get_ydata()) + [ event.ydata] )
            
            #~ self.canvas.draw()
            self.redraw()

        #self.poly.xy=a
        print self.a, type(self.a)
        if self.a != None:    
            test=Path(self.a)
            self.actualSelection, = where(test.contains_points(dot( self.data, self.projection )))
            self.emit(SIGNAL('selectionChanged'))
def get_path2( data, verts ):
    path1 = Path(verts)
    index = path1.contains_points(data[:,:2])
    #print data[index, :2]
    
    plot(data[:,0],data[:,1], 'b.')
    patch = patches.PathPatch(path1, facecolor='orange', lw=2)
    gca().add_patch(patch)
    plot(data[index,0], data[index,1], 'r.')
    show()
 def select_within_polygon(self, poly_lons, poly_lats, select_type="any"):
     """
     Select within a polygon
     """
     polypath = Path(np.column_stack([poly_lons, poly_lats]))
     idx = pd.Series(polypath.contains_points(np.column_stack([
         self.catalogue.origins["longitude"].values,
         self.catalogue.origins["latitude"].values])))
     idx = idx & self.catalogue.origins["depth"].notnull()
     return self._select_by_origins(idx, select_type)
Exemple #27
0
class Poly:
    def __init__(self, coordinates, top=1e9, bottom=-1e9):
        self.border = Path(np.reshape(coordinates, (len(coordinates) / 2, 2)))
        self.top    = top
        self.bottom = bottom
            
    def checkInside(self, lat, lon, alt):
        points = np.vstack((lat,lon)).T         
        inside = self.border.contains_points(points) & (self.bottom <= alt) & (alt <= self.top)        
        return inside
def compute_grid(x, y, X, Y, xs, ys, data):
  print 'Computing grid with', len(x)*len(y), 'points and', len(data), 'contours.'
  grid = array([xs, ys]).T
  covered = zeros_like(xs)
  for icontour in xrange(len(data)):
    la, lo = data[['lons', 'lats']].values[icontour]
    vertices = array([la, lo]).T
    p = Path(vertices)
    covered += p.contains_points(grid)
  return covered
Exemple #29
0
 def _postLasso(self, verts):
     # Relsease and delele lasso
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self.lasso)
     del self.lasso
     # Create empty mask
     M = self.viewer.M
     N = self.viewer.N
     mask = np.zeros((M, N), dtype=np.bool)
     # Upsample vertices
     vertsPath = Path(verts).interpolated(100)
     verts = vertsPath.vertices
     verts = np.array(verts)
     # Fill mask
     idxR = np.round(verts[:,1]).astype(np.int32)
     idxC = np.round(verts[:,0]).astype(np.int32)
     idxR[idxR < 0] = 0
     idxC[idxC < 0] = 0
     idxR[idxR >= M] = M - 1
     idxC[idxC >= N] = N - 1
     mask[idxR, idxC] = True
     if self.maskParams['selectorType'] == 'pen':
         # Make dilation on mask
         d = self.maskParams['width'] + 2
         structure = np.ones((d,d), dtype=np.bool)
         mask = binary_dilation(mask, structure=structure)
     elif self.maskParams['selectorType'] == 'lasso':
         xMin, xMax = idxC.min(), idxC.max()
         yMin, yMax = idxR.min(), idxR.max()
         x = np.arange(xMin, xMax+1)
         y = np.arange(yMin, yMax+1)
         Np = x.shape[0] * y.shape[0]
         xv, yv = np.meshgrid(x, y)
         xv = np.reshape(xv.ravel(), (Np,1))
         yv = np.reshape(yv.ravel(), (Np,1))
         points = np.concatenate((xv,yv), axis=1).astype(np.int32)
         ind = vertsPath.contains_points(points)
         mask[points[ind,1], points[ind,0]] = True
     # Add/remove mask from current one if existing
     if self.viewer.ind in self.data:
         origMask = self.data[self.viewer.ind]
     else:
         origMask = np.zeros((self.viewer.M, self.viewer.N), dtype=np.bool)
     if self.mode == 'add':
         mask = origMask | mask
     else:
         idx = np.nonzero(mask)
         origMask[idx] = False
         mask = origMask
     # Assign new mask
     self.data[self.viewer.ind] = mask 
     # Show mask
     self.showData()
Exemple #30
0
def points_inside_poly(x, y, vx, vy):

    if x.dtype.kind == 'M' and vx.dtype.kind == 'M':
        vx = vx.astype(x.dtype).astype(float)
        x = x.astype(float)

    if y.dtype.kind == 'M' and vy.dtype.kind == 'M':
        vy = vy.astype(y.dtype).astype(float)
        y = y.astype(float)

    original_shape = x.shape

    x = unbroadcast(x)
    y = unbroadcast(y)

    x = x.astype(float)
    y = y.astype(float)

    x, y = np.broadcast_arrays(x, y)

    reduced_shape = x.shape

    x = x.flat
    y = y.flat

    from matplotlib.path import Path
    p = Path(np.column_stack((vx, vy)))

    keep = ((x >= np.min(vx)) &
            (x <= np.max(vx)) &
            (y >= np.min(vy)) &
            (y <= np.max(vy)))

    inside = np.zeros(len(x), bool)

    x = x[keep]
    y = y[keep]

    coords = np.column_stack((x, y))

    inside[keep] = p.contains_points(coords).astype(bool)

    good = np.isfinite(x) & np.isfinite(y)
    inside[keep][~good] = False

    inside = inside.reshape(reduced_shape)
    inside = broadcast_to(inside, original_shape)

    return inside
def generate_mask(filename, json_file):
    '''
    generates a binary mask as ground truth for each image.
    Args: json_file
    '''

    with open(json_file, "r") as read_file:
        data = json.load(read_file)
    shapes = data['shapes']

    polygons = dict()
    for polygon_index in range(len(shapes)):
        polygons[polygon_index] = shapes[polygon_index]['points']

    for points in polygons:
        for index in range(len(polygons[points])):
            polygons[points][index][0] = round(polygons[points][index][0])
            polygons[points][index][1] = round(polygons[points][index][1])
            polygons[points][index] = tuple(polygons[points][index])

    x, y = np.meshgrid(np.arange(config.IMG_WIDTH),
                       np.arange(config.IMG_HEIGHT))
    x, y = x.flatten(), y.flatten()
    points = np.vstack((x, y)).T
    grid = np.zeros(config.IMG_HEIGHT * config.IMG_WIDTH)
    for polygon in polygons:
        path = Path(polygons[polygon])
        grid = grid.astype(float)
        grid += path.contains_points(points).astype(float)

    grid = grid.reshape((config.IMG_HEIGHT, config.IMG_WIDTH))
    grid = grid.astype(bool).astype(float)

    filename = filename.split('/')[-1]
    mask_file_name = os.path.join(config.MASK_DIRECTORY,
                                  filename.split('.')[0] + '.npy')
    # print(mask_file_name)
    np.save(mask_file_name, grid)
Exemple #32
0
    def get_mask(self):
        from matplotlib.path import Path
        from numpy import meshgrid, zeros, array, where

        data = self.image
        mask = zeros(data.shape, dtype="uint8")

        if (len(self.y) > 2) & (len(self.x) > 2):

            points = list(zip(self.y, self.x))

            grid = meshgrid(range(data.shape[0]), range(data.shape[1]))
            coords = list(zip(grid[0].ravel(), grid[1].ravel()))

            path = Path(points)
            in_points = array(coords)[where(path.contains_points(coords))[0]]
            in_points = [tuple(x) for x in in_points]
            for t in in_points:
                mask[t] = 255
        else:
            print("Mask requires 3 or more points")

        return mask
def calculate_fluo_intensity(img, center, outline):

    imgpxl = img.shape[0]

    vertices = np.array([
        center[0] + np.append(outline[:, 0], outline[0, 0]),
        center[1] + np.append(outline[:, 1], outline[0, 1])
    ]).T

    p = Path(vertices)

    # create the mask (image full of 0 and 1, the 1s are wherethe cell is)
    points = [(i, j) for i in np.arange(imgpxl) for j in np.arange(imgpxl)]
    mask = p.contains_points(points).reshape(imgpxl, imgpxl).T

    # plt.figure()
    # plt.imshow(mask)
    # plt.show()
    # plt.figure()
    # plt.imshow(img)
    # plt.show()

    return np.sum(mask * img) / np.sum(mask)
Exemple #34
0
def get_polygons(point):
    global polygons
    ret_poly = []
    ret_in_poly = []
    for polygon in polygons:
        poly_path = Path(polygon)
        test = poly_path.contains_points([point])
        if test[0]:
            ret_poly.append(polygon)


#    for polygon in in_polygons:
#        poly_path=Path(polygon)
#        test = poly_path.contains_points([point])
#        if test[0]:
#            ret_in_poly.append(polygon)
#    return ret_poly, ret_in_poly
    value = mask_label[int(point[1]) - 1, int(point[0]) - 1]
    inret = []
    #print value
    if value != 0:
        inret = [value]
    return ret_poly, inret
Exemple #35
0
    def updateVsbOnImg(self, pt, gPt, img, vsbPolyDict):
        p = pt[0]
        g = gPt[0]
        p = Path(vsbPolyDict[(p[0], p[1])])
        points = CONST.GRID_CENTER_PTS
        grid = p.contains_points(points)
        mask = grid.reshape(CONST.MAP_SIZE, CONST.MAP_SIZE)
        # side of local visible area/2
        r = int((CONST.LOCAL_SZ - 1) / 2)
        lx = max(0, g[1] - r)
        hx = min(CONST.MAP_SIZE, r + g[1] + 1)
        ly = max(0, g[0] - r)
        hy = min(CONST.MAP_SIZE, r + g[0] + 1)
        tempMask = np.zeros_like(mask)
        tempMask[lx:hx, ly:hy] = 1

        mask = np.where(tempMask == 0, False, mask)
        vsbGrid = mask.T
        temp = np.copy(img)

        temp = np.where(vsbGrid, 255, temp)

        return temp
Exemple #36
0
    def getMaskEllipse(self, frame):
        try:
            mask = self.db.getMask(frame=frame).data
            im = self.db.getImages(frame=frame)[0]
        except AttributeError:
            mask_shape = (self.ny, self.nx)
            mask = np.zeros(mask_shape, dtype=np.uint8)
            img_o = self.db.getImage(frame=frame)
            q_polys = self.db.getPolygons(image=img_o)
            for pol in q_polys:
                if np.shape(pol)[0] != 0:
                    polygon = np.array([[pol.points]])
                    if np.sum(
                            polygon.shape
                    ) > 7:  # single point polygon can happen on accident when clicking
                        path = Path(polygon.squeeze())
                        grid = path.contains_points(self.points)
                        grid = grid.reshape(mask_shape)
                        mask += grid

        cells = mask_to_cells(mask, im.data, self.config, self.r_min,
                              self.frame_data, self.edge_dist)
        return mask, cells
Exemple #37
0
 def check_coverage(cls, tens):
     areas = Utils.get_areas()
     arr2 = torch.zeros(len(areas), len(areas[0])).tolist()
     size = tens.size()
     for i in range(len(areas)):
         for j in range(len(areas[i])):
             ar = areas[i][j]
             if ar is None:
                 continue
             color_differences = tens.clone()
             x, y = np.meshgrid(np.arange(size[1]), np.arange(size[0]))
             x, y = x.flatten(), y.flatten()
             path1 = Path(ar)
             points = np.vstack((x, y)).T
             grid = path1.contains_points(points)
             mask = torch.from_numpy(
                 grid.reshape((size[0], size[1])).astype(float)).float()
             color_differences = color_differences * mask
             _sum = mask.sum().item()
             cnt = color_differences[color_differences != 0].numel()
             diff = cnt / _sum
             arr2[i][j] = (diff, mask)
     return arr2
Exemple #38
0
    def get_inside_polygon_cells(self, geometry: Geometry, points):
        """
        :param geometry: Geometry to use
        :param points: Vertices of polygon
        :return: Returns matrix with 1 for cell inside polygon from points, 0 otherwise
        """
        inside = np.zeros_like(self.inside_cells)

        verts = []
        for coord in points:
            verts.append((coord[0], coord[1]))

        p = Path(verts, closed=True)

        points = np.vstack((self.gridX.flatten(), self.gridY.flatten())).T

        inside_points = p.contains_points(points)
        mask = inside_points.reshape(self.gridX.shape[0], self.gridX.shape[1])

        mask = np.logical_and(mask, self.inside_cells == 1)
        inside[mask] = 1

        return inside
Exemple #39
0
def main(sb_img, img, bow):
    centre = peak_local_max(sb_img, min_distance=15)
    centre = centre[0]
    theta = np.rad2deg(np.arctan2(bow[:, 0] - centre[0],
                                  bow[:, 1] - centre[1]))
    theta[theta < 0] += 360
    rad = np.mean(np.linalg.norm(bow - centre, axis=1))
    w1 = patches.Wedge((centre[1], centre[0]),
                       1.2 * rad,
                       theta.min(),
                       theta.max(),
                       color='w',
                       alpha=0.4)

    X, Y = np.mgrid[0:img.shape[1], 0:img.shape[0]]
    points = np.vstack((X.ravel(), Y.ravel())).T

    path = Path(w1.properties()['path'].vertices)
    grid = path.contains_points(points).reshape(img.shape)
    wedge = img * grid.T
    wedge[wedge == 0] = np.nan
    profile = radial_profile(wedge, centre)
    plt.plot(np.arange(len(profile)), profile)
Exemple #40
0
def PolyCrop(Img, ind):

    from matplotlib.path import Path
    from numpy import array, dstack, amax, meshgrid, linspace, hstack

    # Istack = dstack(array(I)
    # imshow(Img)
    #
    # ind = ginput(n=0,timeout=0)
    #
    # close()

    ind = array(ind)
    ind = ind.astype('int')

    I = Img.copy()

    I = I[ind[:, 1].min():ind[:, 1].max(), ind[:, 0].min():ind[:, 0].max()]

    ind[:, 1] = ind[:, 1] - ind[:, 1].min()
    ind[:, 0] = ind[:, 0] - ind[:, 0].min()

    p = Path(ind)

    Ish = I.shape

    ix, iy = meshgrid(linspace(0, Ish[1] - 1, Ish[1]),
                      linspace(0, Ish[0] - 1, Ish[0]))

    sel = hstack((ix.reshape(
        (Ish[1] * Ish[0], 1)), iy.reshape((Ish[0] * Ish[1], 1))))

    mask = p.contains_points(sel).reshape(Ish)

    I = I * mask.astype(int)

    return I
Exemple #41
0
def points_inside_poly(x, y, vx, vy):

    original_shape = x.shape

    x = unbroadcast(x)
    y = unbroadcast(y)
    x, y = np.broadcast_arrays(x, y)

    reduced_shape = x.shape

    x = x.flat
    y = y.flat

    from matplotlib.path import Path
    p = Path(np.column_stack((vx, vy)))

    keep = ((x >= np.min(vx)) &
            (x <= np.max(vx)) &
            (y >= np.min(vy)) &
            (y <= np.max(vy)))

    inside = np.zeros(len(x), bool)

    x = x[keep]
    y = y[keep]

    coords = np.column_stack((x, y))

    inside[keep] = p.contains_points(coords).astype(bool)

    good = np.isfinite(x) & np.isfinite(y)
    inside[keep][~good] = False

    inside = inside.reshape(reduced_shape)
    inside = broadcast_to(inside, original_shape)

    return inside
Exemple #42
0
def inpoly(x, y, pgcoords):
    """Returns bool array of shame shape as x telling which grid points are inside polygon
    parameters:
    -----------
        x, y: ndarrays of the same shape or arraylike
              shape of x and y must be the same.
        pgcoords: sequence of coordinate tuples or array of vertices of the
                  shape. (like it comes from a shape file.)
    return:
    -------
    boolean array, True if point x.flatten()[i], y.flatten()[i] inside shape.
        boolean array has the same shape as x
    @TO 20170315
    """
    try:
        isinstance(pgcoords, (list, tuple, np.ndarray))
        len(pgcoords[0]) == 2
        pgon = Polygon(pgcoords)
    except:
        print('pgcoords must be like [(0, 0), (1, 0), ..] or\n' +
              'an np.ndarray of shape [Np, 2]')
        raise TypeError("Can't create polygon, pgcoords error")

    try:
        x = np.array(x, dtype=float)
        y = np.array(y, dtype=float)
        x.shape == y.shape
    except:
        raise TypeError("x and y not np.ndarrays with same shape.")

    if len(x.shape) == 1 and len(y.shape) == 2:
        X, Y = np.meshgrid(x, y)
    else:
        X = x
        Y = y
    xy = np.vstack((X.ravel(), Y.ravel())).T
    return pgon.contains_points(xy).reshape(X.shape)
def get_nodule_mask(img, rois):
    """
    Given an image and its roi (list of contour boundary points), returns a
    2D binary mask for the image

    :param img: 2D numpy array of CT image
    :param rois: 1D numpy array of list of boundary points defining ROI
    returns: 2D numpy array of image's binary contour
    """
    x, y = np.mgrid[:img.shape[1], :img.shape[0]]

    # mesh grid to a list of points
    points = np.vstack((x.ravel(), y.ravel())).T

    # empty mask
    mask = np.zeros(img.shape[0] * img.shape[1])

    try:
        # iteratively add roi regions to mask
        for roi in rois:
            # from roi to a matplotlib path
            path = Path(roi)
            xmin, ymin, xmax, ymax = np.asarray(path.get_extents(),
                                                dtype=int).ravel()

            # add points to mask included in the path
            mask = np.logical_or(mask, np.array(path.contains_points(points)))

    # except if image is w/o ROIs (empty mask)
    except TypeError:
        pass

    # reshape mask
    mask = np.array([float(m) for m in mask])
    img_mask = mask.reshape(x.shape).T

    return img_mask
def create_masks(img_name, df, img_h, img_w, loc):
    path = '/home/umfarooq0/RooftopSolar/'
    # input id/image name
    # df is the 'sample data frame', houses all the image names and the corresponding RLE's
    data = df[df['image_name'] == img_name]
    # this will give us all the RLE's related that image name
    rle_size = len(data)
    # we need to loop through each set of RLE and create a list of all the points
    RLE = data['join'].reset_index(drop=True)

    x, y = np.meshgrid(np.arange(img_h),
                       np.arange(img_w))  # make a canvas with coordinates
    x, y = x.flatten(), y.flatten()
    points = np.vstack((x, y)).T
    if rle_size == 0:
        return

    for i in range(rle_size):
        print(i)

        RLE_string = RLE[i]
        rlen = [int(float(numstring)) for numstring in RLE_string.split(' ')]
        rlePairs = np.array(rlen).reshape(-1, 2)
        p = Path(rlePairs)  # make a polygon
        grid = p.contains_points(points)
        if i == 0:
            grid_ = np.zeros((img_h * img_w))
            grid_ = grid + grid_
        else:
            grid_ += grid

    mask = grid_.reshape(img_h, img_w)

    filename_save = path + loc + img_name + '.txt'
    np.savez_compressed(filename_save, mask)

    return mask
Exemple #45
0
    def onselect(self, verts):

        # Get vertices of lasso
        path = Path(verts)

        #        for i in range(0,len(self.collection)):
        #            self.fc[i] = self.ec[i]
        #            self.ind[i] = np.nonzero(path.contains_points(self.xys[i]))[0]
        #            self.fc[i][self.ind[i],0] = 1
        #            self.fc[i][self.ind[i],1] = 0
        #            self.fc[i][self.ind[i],2] = 0
        #            self.collection[i].set_edgecolors(self.fc[i][:,:])
        #        # endFor

        self.ind = []
        self.ind = np.nonzero(path.contains_points(self.xys))[0]
        fc = self.fc
        fc[:, :] = self.baseColor
        fc[self.ind, 0] = 1
        fc[self.ind, 1] = 0
        fc[self.ind, 2] = 0
        self.collection.set_edgecolors(fc)
        self.canvas.blit(self.ax.bbox)
        self.active = True
Exemple #46
0
 def getObstacleMap(self, emptyMap, obstacleSet):
     obsList = obstacleSet
     vsb  = Visibility(emptyMap.shape[0], emptyMap.shape[1])
     for obs, isHole in obsList:
         vsb.addGeom2Arrangement(obs)
     
     isHoles = [obs[1] for obs in obsList]
     if any(isHoles) == True:
         pass
     else:
         vsb.boundary2Arrangement(vsb.length, vsb.height)
     
     # get obstacle polygon
     points = CONST.GRID_CENTER_PTS
     img = np.zeros_like(emptyMap, dtype = bool)
     for obs, isHole in obsList:
         p = Path(obs)
         grid = p.contains_points(points)
         mask = grid.reshape(CONST.MAP_SIZE,CONST.MAP_SIZE)
         img = np.logical_or(img , (mask if not isHole else np.logical_not(mask)))
        
     img = img.T
     img = np.where(img,150,emptyMap)
     return img, vsb
Exemple #47
0
def addCylinder2Mod(xc, zc, r, modd, sigCylinder):

    # Get points for cylinder outline
    cylinderPoints = getCylinderPoints(xc, zc, r)
    mod = copy.copy(modd)

    verts = []
    codes = []
    for ii in range(0, cylinderPoints.shape[0]):
        verts.append(cylinderPoints[ii, :])

        if (ii == 0):
            codes.append(Path.MOVETO)
        elif (ii == cylinderPoints.shape[0] - 1):
            codes.append(Path.CLOSEPOLY)
        else:
            codes.append(Path.LINETO)

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    # #Check selected cell centers by plotting
    # # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-40,40)
    # ax.set_ylim(-35,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[insideInd] = sigCylinder
    return mod
def image_cropping(farm_coordinates,img_file,npath):
    elem = gdal.Open(npath + img_file)               
    crop_pixel = [coordi_to_pixel(elem,lon,lat) for lat,lon in farm_coordinates ]
    lat1 = farm_coordinates[0][0]
    lon1 = farm_coordinates[0][1]
    new_name = img_file.split(".")[0]
    if not os.path.exists(npath+'cropped_images_'+str(lon1)+'_'+str(lat1)+'/'+new_name+'.TIFF'):  
        cv_open = cv2.imread(npath+img_file)
        arr = np.zeros(cv_open.shape[0:2])
        # masking according to pixel_coordinates.
        points = np.indices(arr.shape).reshape(2, -1).T
        path = Path(crop_pixel)   
        mask = path.contains_points(points)
        mask = mask.reshape(arr.shape).astype(arr.dtype)
        mask1 = np.dstack((mask,mask))
        mask = np.dstack((mask1,mask))
        final_pixels = cv_open*mask
        x_values = [x for x,y in crop_pixel ]
        y_values = [y for x,y in crop_pixel ]
        xmin,ymin,xmax,ymax = [np.min(x_values),np.min(y_values),np.max(x_values),np.max(y_values)]
        final_image =final_pixels[(xmin-2):(xmax+2),(ymin-2):(ymax+2)]
        if not os.path.exists(npath+'cropped_images_'+str(lon1)+'_'+str(lat1)):
            os.makedirs(npath+'cropped_images_'+str(lon1)+'_'+str(lat1))     
        cv2.imwrite(npath+'cropped_images_'+str(lon1)+'_'+str(lat1)+'/'+new_name+'.TIFF',final_image)
    def onselect(verts):
        # Select elements in original array bounded by selector path.
        verts = np.array(verts)
        p = Path(verts)
        ind = p.contains_points(pix, radius=1)
        selected = np.copy(image)
        selected[:, :, 0].flat[ind] = image[:, :, 0].flat[ind] * 0.8
        selected[:, :, 1].flat[ind] = image[:, :, 1].flat[ind] * 0.8
        selected[:, :, 2].flat[ind] = image[:, :, 2].flat[ind] * 0.8

        nonlocal output
        b = path_bbox(verts)
        ymin, ymax = int(min(b[:, 1])), int(max(b[:, 1])) + 1
        xmin, xmax = int(min(b[:, 0])), int(max(b[:, 0])) + 1
        alpha_mask = np.zeros((height, width))
        alpha_mask.flat[ind] = 1.0
        alpha_mask = alpha_mask[ymin:ymax, xmin:xmax]
        output = np.dstack((image[ymin:ymax, xmin:xmax], alpha_mask))

        ax.clear()
        ax.imshow(selected)
        ax.set_title(TITLE)
        ax.plot(*p.vertices.T, scalex=False, scaley=False)
        fig.canvas.draw_idle()
def createPlateMod(xc, zc, dx, dz, rotAng, sigplate, sighalf):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc, zc, dx, dz, rotAng)

    verts = [
        (plateCorners[0, :]),  # left, top
        (plateCorners[1, :]),  # right, top
        (plateCorners[3, :]),  # right, bottom
        (plateCorners[2, :]),  # left, bottom
        (plateCorners[0, :]),  # left, top (closes polygon)
    ]

    codes = [
        Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY
    ]

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    # Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mtrue = sighalf * np.ones([mesh.nC])
    mtrue[insideInd] = sigplate
    mtrue = np.log(mtrue)
    return mtrue
Exemple #51
0
 def handle_onselect(vertices):
     path = Path(vertices)
     values, (x0, x1), (y0, y1) = self.visible()
     x, y = np.meshgrid(self.x[x0:x1], self.y[y0:y1])
     x, y = x.ravel(), y.ravel()
     xy = np.stack([x, y]).T
     indices = np.nonzero(path.contains_points(xy))[0]
     x = indices // values.shape[0]
     y = indices % values.shape[0]
     x, y = y, x
     # fig, ax = plt.subplots()
     # m = np.zeros_like(values)
     # m[x, y] = values[x, y]
     xm, ym = centerofmass(values, x, y)
     xm = int(xm + x0)
     ym = int(ym + y0)
     self.add_rectangles(x, y)
     scat = self.ax.scatter(self.x[xm],
                            self.y[ym],
                            color="r",
                            marker="x")
     self.patches[-1].append(scat)
     self.ax.figure.canvas.draw_idle()
     self.add_peak([xm, ym])
Exemple #52
0
def polygon_to_points(coords, z=None):
    """
    Given a list of pairs of points which define a polygon,
    return a list of points interior to the polygon
    """

    bounds = array(coords).astype('int')

    bmax = bounds.max(0)
    bmin = bounds.min(0)

    path = Path(bounds)

    grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1))

    grid_flat = zip(grid[0].ravel(), grid[1].ravel())

    points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int')
    points = where(points)
    points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist()
    if z is not None:
        points = map(lambda p: [p[0], p[1], z], points)

    return points
Exemple #53
0
    def one_hot_encoding(self, buildings_dict):
        """
    Helper method only called in convert_json that takes a dictionary of
      building coordinates and creates a one-hot encoding for each pixel 
      for an image { "annotation" : [pixel-wise encoding] }
    Also resizes the mask to IMAGE_SIZE x IMAGE_SIZE before returning the one-hot encoding.
    Assumes: only one class.
    Reference: https://stackoverflow.com/questions/21339448/how-to-get-list-of-points-inside-a-polygon-in-python
    """
        # Image size of tiles.
        w, h, _ = self.get_img_size()  # Right order?

        # make a canvas with pixel coordinates
        x, y = np.meshgrid(np.arange(w), np.arange(h))
        x, y = x.flatten(), y.flatten()
        # A list of all pixels in terms of indices
        all_pix = np.vstack((x, y)).T

        # Single, w*h 1d array of all pixels in image initialised to 0s. This will accumulate
        # annotation markings for each building.
        pixel_annotations = np.zeros((w * h), dtype=bool)
        for building, nodes in buildings_dict.items():
            p = Path(nodes)
            one_building_pixels = p.contains_points(all_pix)

            pixel_annotations = np.logical_or(pixel_annotations,
                                              one_building_pixels)
            pixel_annotations = np.array(pixel_annotations)

        pixel_annotations = np.array(pixel_annotations,
                                     dtype=np.uint8).reshape((w, h))
        pixel_annotations = scipy.misc.imresize(pixel_annotations,
                                                (IMAGE_SIZE, IMAGE_SIZE))
        pixel_annotations = np.array(pixel_annotations, dtype=bool)

        return {"annotation": pixel_annotations.tolist()}
Exemple #54
0
    def get_DVH_pts(self,grid=0.25):
        """Calculate DVH calculation co-ordinates for this structure.
        Generates a grid of points at the specified resolution within
        the structure.

        Args:
            grid: grid size for calculation (default 2.5mm)
        """
        self.dvhpts = []
        if self.name.lower() not in ['body','external']:
            if len(self.coords) > 50:
                slices = sorted(list(set(self.coords[:,1])))
                sthick = slices[1] - slices[0]
                for sli in slices:
                    xy = self.coords[np.where(self.coords[:,1] == sli)][:,(0,2)]
                    minx = xy[:,0].min()-0.5
                    maxx = xy[:,0].max()+0.5
                    miny = xy[:,1].min()-0.5
                    maxy = xy[:,1].max()+0.5
                    calcgrid = [[x, y] for y in np.arange(miny,maxy,grid) for x in np.arange(minx,maxx,grid)]
                    cPath = Path(xy)
                    inPath = cPath.contains_points(calcgrid)
                    calcpts = [calcgrid[i] for i in np.where(inPath)[0]]
                    self.dvhpts.extend([[pt[0], sli, pt[1]] for pt in calcpts])
Exemple #55
0
def inpoly(x, y, pgcoords):
    """Returns bool array [Ny, Nx] telling which grid points are inside polygon

    """
    try:
        isinstance(pgcoords, (list, tuple, np.ndarray))
        len(pgcoords[0]) == 2
        pgon = Polygon(pgcoords)
    except:
        print('pgcoords must be like [(0, 0), (1, 0), ..] or\n' +
              'an np.ndarray of shape [Np, 2]')
        raise TypeError("Can't create polygon, pgcoords error")

    try:
        x = np.array(x, dtype=float)
        y = np.array(y, dtype=float)
        x.shape == y.shape
    except:
        raise TypeError("x and y are not np.ndarrays with same shape.")

    if len(x.shape) == 1:
        X, Y = np.meshgrid(x, y)
    xy = np.vstack((X.ravel(), Y.ravel())).T
    return pgon.contains_points(xy).reshape(X.shape)
Exemple #56
0
def crop_image(part, link):
    vertices = part

    image = cv2.imread(link)
    img = imutils.resize(image, width=500)

    # from vertices to a matplotlib path
    path = Path(vertices)

    # create a mesh grid for the whole image, you could also limit the
    # grid to the extents above, I'm creating a full grid for the plot below
    x, y = np.mgrid[:img.shape[1], :img.shape[0]]
    # mesh grid to a list of points
    points = np.vstack((x.ravel(), y.ravel())).T

    # select points included in the path
    mask = path.contains_points(points)

    # reshape mask for display
    img_mask = mask.reshape(x.shape).T

    # masked image
    img *= img_mask[..., None]
    return img
Exemple #57
0
def polygon_to_mask(coords, dims, z=None):
    """
    Given a list of pairs of points which define a polygon, return a binary
    mask covering the interior of the polygon with dimensions dim
    """

    bounds = array(coords).astype('int')
    path = Path(bounds)

    grid = meshgrid(range(dims[1]), range(dims[0]))
    grid_flat = zip(grid[0].ravel(), grid[1].ravel())

    mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int')

    if z is not None:
        if len(dims) < 3:
            raise Exception('Dims must have three-dimensions for embedding z-index')
        if z >= dims[2]:
            raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2]))
        tmp = zeros(dims)
        tmp[:, :, z] = mask
        mask = tmp

    return mask
def clip_points(points, bounding_shape):
    """
    Clip points outside of the bounding shape.
    Parameters
    ----------
    points : (Mx3) array
        The coordinates of the points.
    bounding_shape : Polygon
        A bounding shape defined by a shapely Polygon.
    Returns
    -------
    points : (Mx3) array
        The coordinates of the clipped points.
    """
    if len(bounding_shape.interiors) > 0:
        mask = [bounding_shape.contains(Point(p)) for p in points]
    else:
        bounding_path = Path(np.array(bounding_shape.exterior.coords)[:, :2],
                             closed=True)
        mask = bounding_path.contains_points(points[:, :2])

    clipped_points = points[mask]

    return clipped_points
    def get_coordinates_in_polygon(self, polygon):
        # Start = time.time()
        p1 = self.polygon1
        if (polygon.area <= p1.area * 0.02):
            return -1
        polygon = loads(dumps(polygon, rounding_precision=0))
        rectangle = polygon.exterior.coords
        bounds = self.canvas.bounds
        height = int(bounds[3]) - int(bounds[1])
        width = int(bounds[2]) - int(bounds[0])
        p = Path(rectangle)
        x, y = np.meshgrid(np.arange(height),
                           np.arange(width))  # make a canvas with coordinates
        x, y = x.flatten(), y.flatten()
        points = np.vstack((y, x)).T

        grid = p.contains_points(points)
        mask = grid.reshape(width, height)
        coords = np.nonzero(mask)
        coords = np.array(coords)
        # coordsInTupples = list(tuple(map(tuple, coords.transpose())))
        # end = time.time()
        # print("geting the coornates: ",end-Start,"\n\n" )
        return LineString(coords.T)
Exemple #60
0
def points_in_shape(shape_path, N):

    shape = shape_(shape_path)

    minx, miny, maxx, maxy = shape.bounds

    #print minx; print miny; print maxx; print maxy
    #bounding_box = geometry.box(minx, miny, maxx, maxy)

    #generate random points within bounding box!

    N_total = 130**2

    sf = shapefile.Reader(shape_path)
    shape = sf.shapes()[0]

    #find polygon nodes lat lons
    verticies = shape.points

    #convert to a matplotlib path class!
    polygon = Path(verticies)

    #points_in_shape = polygon.contains_points(coords)
    #coords = coords[points_in_shape == True][0:N-1]

    X = abs(maxx - minx) * np.random.rand(N_total, 1) + minx

    Y = abs(maxy - miny) * np.random.rand(N_total, 1) + miny

    coords = np.column_stack((X, Y))

    points_in_shape = polygon.contains_points(coords)

    coords = coords[points_in_shape == True][0:N]

    return coords