コード例 #1
0
ファイル: Prediction.py プロジェクト: asbaker/CSE555-Nowcast
  def makePrediction(self):

    for blob in self.blobs:
      dxs = []
      dys = []
      #magnitudes = []
      #angles = []

      for motion in self.motions:
        if nx.pnpoly(motion.x, motion.y, blob.contour()):
          #dxs.append(motion.dx)
          #dys.append(motion.dy)
          (uvx, uvy) = motion.vector()
          dxs.append(uvx)
          dys.append(uvy)
          #angles.append(np.rad2deg(np.arctan(uvy/uvx)))
          #magnitudes.append(motion.magnitude())

      #if not math.isnan(np.mean(magnitudes)):
      if not math.isnan(np.mean(dxs)):
        mean_dx = np.mean(dxs)
        mean_dy = np.mean(dys)
        print("mean_dx" + str(mean_dx))
        print("mean_dy" + str(mean_dy))

        blob_img = blob.blobImage()
        (size_x, size_y) = blob_img.size()

        new_x = int(blob.x + mean_dx) - size_x/2
        new_y = int(blob.y + mean_dy) - size_y/2 

        alpha_mask = blob_img.binarize().invert()
        self.image = self.image.blit(blob_img, pos=(new_x, new_y), alphaMask=alpha_mask)
コード例 #2
0
    def makePrediction(self):

        for blob in self.blobs:
            dxs = []
            dys = []
            #magnitudes = []
            #angles = []

            for motion in self.motions:
                if nx.pnpoly(motion.x, motion.y, blob.contour()):
                    #dxs.append(motion.dx)
                    #dys.append(motion.dy)
                    (uvx, uvy) = motion.vector()
                    dxs.append(uvx)
                    dys.append(uvy)
                    #angles.append(np.rad2deg(np.arctan(uvy/uvx)))
                    #magnitudes.append(motion.magnitude())

            #if not math.isnan(np.mean(magnitudes)):
            if not math.isnan(np.mean(dxs)):
                mean_dx = np.mean(dxs)
                mean_dy = np.mean(dys)
                print("mean_dx" + str(mean_dx))
                print("mean_dy" + str(mean_dy))

                blob_img = blob.blobImage()
                (size_x, size_y) = blob_img.size()

                new_x = int(blob.x + mean_dx) - size_x / 2
                new_y = int(blob.y + mean_dy) - size_y / 2

                alpha_mask = blob_img.binarize().invert()
                self.image = self.image.blit(blob_img,
                                             pos=(new_x, new_y),
                                             alphaMask=alpha_mask)
コード例 #3
0
def pts_in_polygon(xpoints, ypoints, polygon):
    isin = list()
    for i in xrange(0, len(xpoints)):
        isin.append(nxutils.pnpoly(xpoints[i], ypoints[i], polygon))

    ispol = np.array(isin) == 1
    return ispol == 1
コード例 #4
0
def get_cmd_shape(color, mag):
    '''
    gets the outline of a cmd. Guesses at a large polygon, and then add points
    that are outside of the polygon, ignores points within.

    then polar sorts the result.
    returns: N,2 array.
    '''
    # make a guess at the polygon.
    left = (np.min(color), mag[np.argmin(color)])
    right = (np.max(color), mag[np.argmax(color)])
    up = (color[np.argmin(mag)], np.min(mag))
    down = (color[np.argmax(mag)], np.max(mag))
    verts = np.vstack((left, right, up, down))

    points = np.column_stack((color, mag))
    for point in points:
        if nxutils.pnpoly(point[0], point[1], verts) == 0.:
            # add point to verts
            col = verts[:, 0]
            m = verts[:, 1]
            col = np.append(col, point[0])
            m = np.append(m, point[1])
            # order the new points in a circle
            verts = polar_sort(zip(col, m))

    verts = np.append(verts, [verts[0]], axis=0)
    # plt.plot(verts[:, 0], verts[:, 1], lw = 2)
    return verts
コード例 #5
0
ファイル: test.py プロジェクト: ckhroulev/dbg-playground
def correct_mask(pts):
        for j in range(y.size):
            for i in range(x.size):
                if mask[j,i] > 0:
                    if nx.pnpoly(x[i], y[j], pts):
                        mask[j,i] = 2
                    else:
                        mask[j,i] = 1
コード例 #6
0
def inpolygon(x,y,xp,yp):
  '''
  Points inside polygon test.

  Based on matplotlib nxutils for old matplotlib versions
  http://matplotlib.sourceforge.net/faq/howto_faq.html#test-whether-a-point-is-inside-a-polygon

  Can also use Path.contains_point, for recent versions, or
  the pnpoly extension - point in polyon test - by W R Franklin,
  http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  '''

  try:
    from matplotlib.nxutils import pnpoly, points_inside_poly
    _use_mpl = 1
  except ImportError:
    from matplotlib.path import Path
    _use_mpl = 2
  except:
    import pnpoly
    _use_mpl = False

  shape=False
  try:
    if x.ndim>1:
      shape=x.shape
      x=x.flat
      y=y.flat
  except: pass

  if _use_mpl==1:
    verts=np.array(zip(xp,yp))
    if isiterable(x,y):
      points=np.array(zip(x,y))
      res=points_inside_poly(points,verts)
    else:
      res=pnpoly(x,y,verts)==1

  elif _use_mpl==2:
    verts=np.array(zip(xp,yp))
    p=Path(verts)
    if not isiterable(x,y): x,y,itr=[x],[y],0
    else: itr=1
    res=[p.contains_point((x[i],y[i]), radius=0.) for i in range(len(x))]
    res=np.asarray(res,'bool')
    if not itr: res=res[0]

  else:
    if not isiterable(x,y): x,y,itr=[x],[y],0
    else: itr=1
    res=np.zeros(len(x))
    res=[pnpoly.pnpoly(x[i],y[i],xp,yp,len(xp)) for i in range(len(x))]
    res=np.asarray(res)==1
    if not itr: res=res[0]

  if not shape is False: res.shape=shape
  return res
コード例 #7
0
ファイル: pj_healpix.py プロジェクト: rggibb/rhealpixdggs-py
def in_healpix_image(x, y):
    r"""
    Return True if and only if `(x, y)` lies in the image of the HEALPix 
    projection of the unit sphere.
        
    EXAMPLES::
    
        >>> eps = 0     # Test boundary points.
        >>> hp = [
        ... (-pi - eps, pi/4),
        ... (-3*pi/4, pi/2 + eps),
        ... (-pi/2, pi/4 + eps),
        ... (-pi/4, pi/2 + eps),
        ... (0, pi/4 + eps),
        ... (pi/4, pi/2 + eps),
        ... (pi/2, pi/4 + eps),
        ... (3*pi/4, pi/2 + eps),
        ... (pi + eps, pi/4),
        ... (pi + eps,-pi/4),
        ... (3*pi/4,-pi/2 - eps),
        ... (pi/2,-pi/4 - eps),
        ... (pi/4,-pi/2 - eps),
        ... (0,-pi/4 - eps),
        ... (-pi/4,-pi/2 - eps),
        ... (-pi/2,-pi/4 - eps),
        ... (-3*pi/4,-pi/2 - eps),
        ... (-pi - eps,-pi/4)
        ... ]
        >>> for p in hp:
        ...     if not in_healpix_image(*p):
        ...             print 'Fail'
        ... 
        >>> in_healpix_image(0, 0)
        True
        >>> in_healpix_image(0, pi/4 + 0.1)
        False
    """
    # matplotlib is a third-party module.
    from matplotlib.nxutils import pnpoly

    # Fuzz to slightly expand HEALPix image boundary so that pnpoly()
    # counts points on the original boundary as lying in the image.
    eps = 1e-10
    vertices = [(-pi - eps, pi / 4), (-3 * pi / 4, pi / 2 + eps),
                (-pi / 2, pi / 4 + eps), (-pi / 4, pi / 2 + eps),
                (0, pi / 4 + eps), (pi / 4, pi / 2 + eps),
                (pi / 2, pi / 4 + eps), (3 * pi / 4, pi / 2 + eps),
                (pi + eps, pi / 4), (pi + eps, -pi / 4),
                (3 * pi / 4, -pi / 2 - eps), (pi / 2, -pi / 4 - eps),
                (pi / 4, -pi / 2 - eps), (0, -pi / 4 - eps),
                (-pi / 4, -pi / 2 - eps), (-pi / 2, -pi / 4 - eps),
                (-3 * pi / 4, -pi / 2 - eps), (-pi - eps, -pi / 4)]
    return bool(pnpoly(x, y, vertices))
コード例 #8
0
 def __call__(self,indices):
     """Divide the data points up into num_vars bins at the points specified
     in indices. Then perform orthogonal regression on all the points in
     each bin and return the total error. Thus, each bin of points is
     considered to be a candidate for the collection of all the points along
     a given side of the polygon."""
     self.sane = True
     self.generate_polygon(indices)
     self.sane = self.sane and pnpoly(self.centroid[0], self.centroid[1], self.corners)
     if not self.sane:
         return 1e308
     else:
         return self.error
コード例 #9
0
def in_rhealpix_image(x, y, north_square=0, south_square=0):
    r"""
    Return True if and only if the point `(x, y)` lies in the image of 
    the rHEALPix projection of the unit sphere.
            
    EXAMPLES::
    
        >>> eps = 0     # Test boundary points.
        >>> north_square, south_square = 0, 0
        >>> rhp = [
        ... (-pi - eps, pi/4 + eps),
        ... (-pi + north_square*pi/2 - eps, pi/4 + eps),
        ... (-pi + north_square*pi/2 - eps, 3*pi/4 + eps),
        ... (-pi + (north_square + 1)*pi/2 + eps, 3*pi/4 + eps),
        ... (-pi + (north_square + 1)*pi/2 + eps, pi/4 + eps),
        ... (pi + eps, pi/4 + eps),
        ... (pi + eps,-pi/4 - eps),
        ... (-pi + (south_square + 1)*pi/2 + eps,-pi/4 - eps),
        ... (-pi + (south_square + 1)*pi/2 + eps,-3*pi/4 - eps),
        ... (-pi + south_square*pi/2 - eps,-3*pi/4 - eps),
        ... (-pi + south_square*pi/2 -eps,-pi/4 - eps),
        ... (-pi - eps,-pi/4 - eps)
        ... ]
        >>> for p in rhp:
        ...     if not in_rhealpix_image(*p):
        ...             print 'Fail'
        ... 
        >>> print in_rhealpix_image(0, 0)
        True
        >>> print in_rhealpix_image(0, pi/4 + 0.1)
        False
        
    """
    # matplotlib is a third-party module.
    from matplotlib.nxutils import pnpoly

    # Fuzz to slightly expand rHEALPix image boundary so that pnpoly()
    # counts points on the original boundary as lying in the image.
    eps = 1e-15
    vertices = [(-pi - eps, pi / 4 + eps),
                (-pi + north_square * pi / 2 - eps, pi / 4 + eps),
                (-pi + north_square * pi / 2 - eps, 3 * pi / 4 + eps),
                (-pi + (north_square + 1) * pi / 2 + eps, 3 * pi / 4 + eps),
                (-pi + (north_square + 1) * pi / 2 + eps, pi / 4 + eps),
                (pi + eps, pi / 4 + eps), (pi + eps, -pi / 4 - eps),
                (-pi + (south_square + 1) * pi / 2 + eps, -pi / 4 - eps),
                (-pi + (south_square + 1) * pi / 2 + eps, -3 * pi / 4 - eps),
                (-pi + south_square * pi / 2 - eps, -3 * pi / 4 - eps),
                (-pi + south_square * pi / 2 - eps, -pi / 4 - eps),
                (-pi - eps, -pi / 4 - eps)]
    return bool(pnpoly(x, y, vertices))
コード例 #10
0
 def __call__(self, indices):
     """Divide the data points up into num_vars bins at the points specified
     in indices. Then perform orthogonal regression on all the points in
     each bin and return the total error. Thus, each bin of points is
     considered to be a candidate for the collection of all the points along
     a given side of the polygon."""
     self.sane = True
     self.generate_polygon(indices)
     self.sane = self.sane and pnpoly(self.centroid[0], self.centroid[1],
                                      self.corners)
     if not self.sane:
         return 1e308
     else:
         return self.error
コード例 #11
0
ファイル: pathinsquare.py プロジェクト: cfa-nm/bikeability
def pathtally(args):
    '''Tally the number of paths that intersect the given square.'''

    square, paths = args
    
    tally = 0
    
    for path in paths:
        for point in path['coordinates']:
            if nx.pnpoly(point[0],point[1],square[:-1]):
                tally += path['weight']
                break
    
    return tally
コード例 #12
0
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        try:
            # TODO: make this consistent with patch collection algorithm
            x, y = self.get_transform().inverse_xy_tup((mouseevent.x, mouseevent.y))
            xyverts = self.get_verts()
            inside = nxutils.pnpoly(x, y, xyverts)
            #print str(self),"%g,%g is in"%(x,y),xyverts,inside
            return inside,{}
        except ValueError:
            return False,{}
コード例 #13
0
ファイル: patches.py プロジェクト: jtomase/matplotlib
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        try:
            # TODO: make this consistent with patch collection algorithm
            x, y = self.get_transform().inverse_xy_tup((mouseevent.x, mouseevent.y))
            xyverts = self.get_verts()
            inside = nxutils.pnpoly(x, y, xyverts)
            #print str(self),"%g,%g is in"%(x,y),xyverts,inside
            return inside,{}
        except ValueError:
            return False,{}
コード例 #14
0
ファイル: helpers.py プロジェクト: candyash/flask-fastmonkey
def pointInPolygon(x, y, poly):
    """Determine if a point (`x`, `y`) is inside a polygon, using the ray casting method.

    `poly` is a list of 3+ vertices as (x,y) pairs.
    If given a `ShapeStim`-based object, will use the
    rendered vertices and position as the polygon.

    Returns True (inside) or False (outside). Used by :class:`~psychopy.visual.ShapeStim` `.contains()`
    """
    try: #do this using try:...except rather than hasattr() for speed
        poly = poly.verticesPix #we want to access this only once
    except:
        pass
    nVert = len(poly)
    if nVert < 3:
        msg = 'pointInPolygon expects a polygon with 3 or more vertices'
        logging.warning(msg)
        return False

    # faster if have matplotlib tools:
    if haveMatplotlib:
        if matplotlib.__version__ > '1.2':
            return mpl_Path(poly).contains_point([x,y])
        else:
            try:
                return bool(nxutils.pnpoly(x, y, poly))
            except:
                pass

    # fall through to pure python:
    # as adapted from http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
    # via http://www.ariel.com.au/a/python-point-int-poly.html

    inside = False
    # trace (horizontal?) rays, flip inside status if cross an edge:
    p1x, p1y = poly[-1]
    for p2x, p2y in poly:
        if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x):
            if p1y != p2y:
                xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
            if p1x == p2x or x <= xints:
                inside = not inside
        p1x, p1y = p2x, p2y
    return inside
コード例 #15
0
def pointInPolygon(x, y, poly):
    """Determine if a point is inside a polygon; returns True if inside.

    (`x`, `y`) is the point to test. `poly` is a list of 3 or more vertices
    as (x,y) pairs. If given an object, such as a `ShapeStim`, will try to
    use its vertices and position as the polygon.

    Same as the `.contains()` method elsewhere.
    """
    try:  # do this using try:...except rather than hasattr() for speed
        poly = poly.verticesPix  # we want to access this only once
    except Exception:
        pass
    nVert = len(poly)
    if nVert < 3:
        msg = 'pointInPolygon expects a polygon with 3 or more vertices'
        logging.warning(msg)
        return False

    # faster if have matplotlib tools:
    if haveMatplotlib:
        if matplotlib.__version__ > '1.2':
            return mplPath(poly).contains_point([x, y])
        else:
            try:
                return bool(nxutils.pnpoly(x, y, poly))
            except Exception:
                pass

    # fall through to pure python:
    # adapted from http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
    # via http://www.ariel.com.au/a/python-point-int-poly.html

    inside = False
    # trace (horizontal?) rays, flip inside status if cross an edge:
    p1x, p1y = poly[-1]
    for p2x, p2y in poly:
        if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x):
            if p1y != p2y:
                xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
            if p1x == p2x or x <= xints:
                inside = not inside
        p1x, p1y = p2x, p2y
    return inside
コード例 #16
0
ファイル: helpers.py プロジェクト: ChenTzuYin/psychopy
def pointInPolygon(x, y, poly):
    """Determine if a point is inside a polygon; returns True if inside.

    (`x`, `y`) is the point to test. `poly` is a list of 3 or more vertices
    as (x,y) pairs. If given an object, such as a `ShapeStim`, will try to
    use its vertices and position as the polygon.

    Same as the `.contains()` method elsewhere.
    """
    try:  # do this using try:...except rather than hasattr() for speed
        poly = poly.verticesPix  # we want to access this only once
    except Exception:
        pass
    nVert = len(poly)
    if nVert < 3:
        msg = 'pointInPolygon expects a polygon with 3 or more vertices'
        logging.warning(msg)
        return False

    # faster if have matplotlib tools:
    if haveMatplotlib:
        if parse_version(matplotlib.__version__) > parse_version('1.2'):
            return mplPath(poly).contains_point([x, y])
        else:
            try:
                return bool(nxutils.pnpoly(x, y, poly))
            except Exception:
                pass

    # fall through to pure python:
    # adapted from http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
    # via http://www.ariel.com.au/a/python-point-int-poly.html

    inside = False
    # trace (horizontal?) rays, flip inside status if cross an edge:
    p1x, p1y = poly[-1]
    for p2x, p2y in poly:
        if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x):
            if p1y != p2y:
                xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
            if p1x == p2x or x <= xints:
                inside = not inside
        p1x, p1y = p2x, p2y
    return inside
コード例 #17
0
    def contains(self,mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        try:
            l,b,w,h = self.get_window_extent().get_bounds()
        except:
            # TODO: why does this error occur
            #print str(self),"error looking at get_window_extent"
            return False,{}
        r = l+w
        t = b+h
        xyverts = (l,b), (l, t), (r, t), (r, b)
        x, y = mouseevent.x, mouseevent.y
        inside = nxutils.pnpoly(x, y, xyverts)
        return inside,{}
コード例 #18
0
ファイル: text.py プロジェクト: lisarosalina/App
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains): return self._contains(self, mouseevent)

        if not self.get_visible() or self._renderer is None:
            return False, {}

        l, b, w, h = self.get_window_extent().bounds

        r = l + w
        t = b + h
        xyverts = (l, b), (l, t), (r, t), (r, b)
        x, y = mouseevent.x, mouseevent.y
        inside = nxutils.pnpoly(x, y, xyverts)

        return inside, {}
コード例 #19
0
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains): return self._contains(self, mouseevent)

        try:
            l, b, w, h = self.get_window_extent().get_bounds()
        except:
            # TODO: why does this error occur
            #print str(self),"error looking at get_window_extent"
            return False, {}
        r = l + w
        t = b + h
        xyverts = (l, b), (l, t), (r, t), (r, b)
        x, y = mouseevent.x, mouseevent.y
        inside = nxutils.pnpoly(x, y, xyverts)
        return inside, {}
コード例 #20
0
ファイル: text.py プロジェクト: Einstein-NTE/einstein
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        if callable(self._contains):
            return self._contains(self, mouseevent)

        if not self.get_visible() or self._renderer is None:
            return False, {}

        l, b, w, h = self.get_window_extent().bounds

        r = l + w
        t = b + h
        xyverts = (l, b), (l, t), (r, t), (r, b)
        x, y = mouseevent.x, mouseevent.y
        inside = nxutils.pnpoly(x, y, xyverts)

        return inside, {}
コード例 #21
0
    def drop(self):
        if self.state == GRASPING:
            #success = self.manager.put_down_object(self.grasp_arm, max_place_tries=25, use_place_override=1)
            place_pose = PoseStamped()
            ptt = self.transformAtLatestCommonTime('table', self.point)
            place_pose.header = ptt.header
            place_pose.pose.position = ptt.point
            place_pose.pose.orientation = euler_to_quaternion(0, 0, 0)
            place_pose.pose.position.z = 0.03
            # see if it's in one of our predefined boxes

            pw, ph = 0.1, 0.1

            #boxes = [('TRASH', TRASH), ('RECYCLING', RECYCLING)]
            boxes = []
            for name, polygon in boxes:
                pts_arr = np.array([[(p.x, p.y)
                                     for p in polygon.polygon.points]])
                print pts_arr
                if pnpoly(ptt.point.x, ptt.point.y, pts_arr.squeeze()):
                    # we're doing this from the top right corner (don't ask)
                    # place_pose.pose.position = polygon.polygon.points[0]
                    poly_center = pts_arr.squeeze().mean(0)
                    place_pose.pose.position.x = poly_center[0]
                    place_pose.pose.position.y = poly_center[1]
                    pw, ph = w, h
                    rospy.loginfo('Placing in box: %s' % name)

            rospy.loginfo('Placing at %s' % place_pose)
            self.place_viz_pub.publish(place_pose)

            #import pdb; pdb.set_trace()

            self.manager.set_place_area(place_pose, (pw, ph))
            # status = self.manager.place_object(self.grasp_arm, place_pose, padding=0)
            status = self.manager.put_down_object(self.grasp_arm,
                                                  max_place_tries=25,
                                                  use_place_override=1)
            if status == ManipulationResult.SUCCESS:
                self.state = NOTGRASPING
                self.grasp_arm = -1
コード例 #22
0
    def contains(self,mouseevent):
        """Test whether the mouse event occurred in the patch.

        In the case of text, a hit is true anywhere in the
        axis-aligned bounding-box containing the text.

        Returns True or False.
        """
        if callable(self._contains): return self._contains(self,mouseevent)

        if not self.get_visible() or self._renderer is None:
            return False,{}

        l,b,w,h = self.get_window_extent().bounds

        r = l+w
        t = b+h
        xyverts = (l,b), (l, t), (r, t), (r, b)
        x, y = mouseevent.x, mouseevent.y
        inside = nxutils.pnpoly(x, y, xyverts)

        return inside,{}
コード例 #23
0
    def drop(self):
        if self.state == GRASPING:
            #success = self.manager.put_down_object(self.grasp_arm, max_place_tries=25, use_place_override=1)
            place_pose = PoseStamped()
            ptt = self.transformAtLatestCommonTime('table', self.point)
            place_pose.header = ptt.header 
            place_pose.pose.position = ptt.point
            place_pose.pose.orientation = euler_to_quaternion(0,0,0)
            place_pose.pose.position.z = 0.03
            # see if it's in one of our predefined boxes
            
            pw,ph = 0.1,0.1
       
            #boxes = [('TRASH', TRASH), ('RECYCLING', RECYCLING)]
            boxes = []
            for name, polygon in boxes:
                pts_arr = np.array([[(p.x,p.y) for p in polygon.polygon.points]])
                print pts_arr
                if pnpoly(ptt.point.x, ptt.point.y, pts_arr.squeeze()):
                    # we're doing this from the top right corner (don't ask)
                    # place_pose.pose.position = polygon.polygon.points[0]
                    poly_center = pts_arr.squeeze().mean(0)
                    place_pose.pose.position.x = poly_center[0]
                    place_pose.pose.position.y = poly_center[1]
                    pw,ph = w,h
                    rospy.loginfo('Placing in box: %s' % name)
                    
            rospy.loginfo('Placing at %s' % place_pose)
            self.place_viz_pub.publish(place_pose)
            
            #import pdb; pdb.set_trace()

            self.manager.set_place_area(place_pose, (pw,ph))
            # status = self.manager.place_object(self.grasp_arm, place_pose, padding=0) 
            status = self.manager.put_down_object(self.grasp_arm, max_place_tries=25, use_place_override=1)
            if status == ManipulationResult.SUCCESS:
                self.state = NOTGRASPING
                self.grasp_arm = -1
コード例 #24
0
def testGame(file_path):

    TEST_CASES = 100
    
    game = gambit.read_game(file_path)

    vertices,edges = CorrEq.findPolygon(game)
    edges = CorrEq.removeExtraEdges(vertices,edges)

    constraints = deriveConstraints(game)

    points = CorrEq.orderVertices(edges)

    if points == None:
        points = vertices
    
    for i in range(TEST_CASES):
        # Pick a random probability distribution
        probs = [random() for j in range(len(game.contingencies))]       
        # Ensure probabilities sum to 1
        probs = [j/sum(probs) for j in probs]
        
        # Determine whether the distribution is a correlated equilibrium
            # It is if it satisfies the constraints in the LP       
        is_corr_eq = True
        
        for j in constraints:
            if sum(multiply(probs,j)) < 0:
                is_corr_eq = False
                break
        
        u1,u2 = CorrEq.probsToUtilities(probs, game)
        inside = pnpoly(u1,u2,points)
        
        if is_corr_eq == True and inside == False:
            raise Exception('Test failed on: ' + file_path)
            print 'Test failed on: ' + file_path
コード例 #25
0
def testGame(file_path):

    TEST_CASES = 100

    game = gambit.read_game(file_path)

    vertices, edges = CorrEq.findPolygon(game)
    edges = CorrEq.removeExtraEdges(vertices, edges)

    constraints = deriveConstraints(game)

    points = CorrEq.orderVertices(edges)

    if points == None:
        points = vertices

    for i in range(TEST_CASES):
        # Pick a random probability distribution
        probs = [random() for j in range(len(game.contingencies))]
        # Ensure probabilities sum to 1
        probs = [j / sum(probs) for j in probs]

        # Determine whether the distribution is a correlated equilibrium
        # It is if it satisfies the constraints in the LP
        is_corr_eq = True

        for j in constraints:
            if sum(multiply(probs, j)) < 0:
                is_corr_eq = False
                break

        u1, u2 = CorrEq.probsToUtilities(probs, game)
        inside = pnpoly(u1, u2, points)

        if is_corr_eq == True and inside == False:
            raise Exception('Test failed on: ' + file_path)
            print 'Test failed on: ' + file_path
コード例 #26
0
ファイル: main.py プロジェクト: lucemia/box
def calculate_mass_center_in_support_plan(box, overlap_planes):
    """
        判斷目標貨物是否能夠被支點所支撐
        透過 ConvexHull 演算法, 檢查目標貨物的重心 (x,y) 坐標,
        是否在支點形成的凸面之中
    """
    from scipy.spatial import ConvexHull
    import matplotlib.nxutils as nx

    # 取出所有的支點
    points = []
    for left, right, top, bottom in overlap_planes:
        points.extend([
            (left, top),
            (left, bottom),
            (right, top),
            (right, bottom)
        ])

    # 計算支點形成的凸面
    hull = ConvexHull(points)
    # 確認box重心是否在凸面之中
    r = nx.pnpoly(box.center_x, box.center_y, hull)
    return r and True
コード例 #27
0
ファイル: collections.py プロジェクト: gkliska/razvoj
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred in the collection.

        Returns T/F, dict(ind=itemlist), where every item in itemlist contains the event.
        """
        if callable(self._contains): return self._contains(self,mouseevent)
        # TODO: Consider doing the test in data coordinates
        # Patch transforms the mouse into data coordinates and does the
        # test for membership there.  This is more efficient though it
        # may not match the visual appearance of the polygon on the
        # screen.  Regardless, patch and patch collection should use
        # the same algorithm.  Here's the code in patch:
        #
        #    x, y = self.get_transform().inverse_xy_tup((mouseevent.x, mouseevent.y))
        #    xyverts = self.get_verts()
        #    inside = nxutils.pnpoly(x, y, xyverts)
        #
        ind = []
        x, y = mouseevent.x, mouseevent.y
        for i, thispoly in enumerate(self.get_transformed_patches()):
            inside = nxutils.pnpoly(x, y, thispoly)
            if inside: ind.append(i)
        return len(ind)>0,dict(ind=ind)
コード例 #28
0
    def contains(self, mouseevent):
        """
        Test whether the mouse event occurred in the collection.

        Returns T/F, dict(ind=itemlist), where every item in itemlist contains the event.
        """
        if callable(self._contains): return self._contains(self, mouseevent)
        # TODO: Consider doing the test in data coordinates
        # Patch transforms the mouse into data coordinates and does the
        # test for membership there.  This is more efficient though it
        # may not match the visual appearance of the polygon on the
        # screen.  Regardless, patch and patch collection should use
        # the same algorithm.  Here's the code in patch:
        #
        #    x, y = self.get_transform().inverse_xy_tup((mouseevent.x, mouseevent.y))
        #    xyverts = self.get_verts()
        #    inside = nxutils.pnpoly(x, y, xyverts)
        #
        ind = []
        x, y = mouseevent.x, mouseevent.y
        for i, thispoly in enumerate(self.get_transformed_patches()):
            inside = nxutils.pnpoly(x, y, thispoly)
            if inside: ind.append(i)
        return len(ind) > 0, dict(ind=ind)
コード例 #29
0
	for record in data:
	    if 'Graffiti' in record.split(',')[5]:
	        graffitis.append(record)

	# Get id, datetime, point(lat, lng)
	formatted_graffitis = []
	for record in graffitis:
	    array = record.split(',')
	    formatted_graffitis.append([array[0], 
	    	datetime.strptime(array[1], "%m/%d/%Y %I:%M:%S %p"), 
	    	Point((array[49], array[50]))])

	# Graffiti in 2013 w/ coordinates
	formatted_graffitis_2013 = []
	for record in formatted_graffitis:
	    if record[1].year == 2013 and nx.pnpoly(record[2].latitude, record[2].longitude, lower_manhattan) == 1:
	        formatted_graffitis_2013.append(record)

	# sort by time
	formatted_graffitis.sort(key=itemgetter(1), reverse=True)

	# get in months
	formatted_graffitis_2013_month_dict = {}
	for i in range(1, 13):
		l = []
		for record in formatted_graffitis_2013:
			if record[1].month == i:
				l.append(record)
		formatted_graffitis_2013_month_dict[i] = l

	# Get Noise Data
コード例 #30
0
ファイル: utility.py プロジェクト: BobTorgerson/Pyroms
def find_nearestgridpoints(longitude, latitude, grd, Cpos="rho"):

    if type(grd).__name__ == "ROMS_Grid":

        if Cpos is "u":
            lon = grd.hgrid.lon_u[:, :]
            lat = grd.hgrid.lat_u[:, :]
        elif Cpos is "v":
            lon = grd.hgrid.lon_v[:, :]
            lat = grd.hgrid.lat_v[:, :]
        elif Cpos is "rho":
            lon = grd.hgrid.lon_rho[:, :]
            lat = grd.hgrid.lat_rho[:, :]
        elif Cpos is "vert":
            lon = grd.hgrid.lon_vert[:, :]
            lat = grd.hgrid.lat_vert[:, :]
        else:
            raise Warning, "%s bad position. Cpos must be rho, u or v." % Cpos

    if type(grd).__name__ == "CGrid_geo":

        if Cpos is "u":
            lon = grd.lon_u[:, :]
            lat = grd.lat_u[:, :]
        elif Cpos is "v":
            lon = grd.lon_v[:, :]
            lat = grd.lat_v[:, :]
        elif Cpos is "rho":
            lon = grd.lon_rho[:, :]
            lat = grd.lat_rho[:, :]
        elif Cpos is "vert":
            lon = grd.lon_vert[:, :]
            lat = grd.lat_vert[:, :]
        else:
            raise Warning, "%s bad position. Cpos must be rho, u or v." % Cpos

    dlon = lon[:, :] - longitude
    dlat = lat[:, :] - latitude

    diff = (dlon * dlon) + (dlat * dlat)

    jidx, iidx = np.where(diff == diff.min())

    iidx = iidx[0]  # take element 1 in case min dist is not unique
    jidx = jidx[0]

    try:

        iindex = [iidx, iidx + 1, iidx + 1, iidx]
        jindex = [jidx, jidx, jidx + 1, jidx + 1]
        xp = lon[jindex, iindex]
        yp = lat[jindex, iindex]
        verts = []
        for n in range(4):
            verts.append([xp[n], yp[n]])
        inside = pnpoly(longitude, latitude, verts)

        if inside == 0:
            iindex = [iidx, iidx + 1, iidx + 1, iidx]
            jindex = [jidx - 1, jidx - 1, jidx, jidx]
            xp = lon[jindex, iindex]
            yp = lat[jindex, iindex]
            verts = []
            for n in range(4):
                verts.append([xp[n], yp[n]])
            inside = pnpoly(longitude, latitude, verts)

            if inside == 0:
                iindex = [iidx - 1, iidx, iidx, iidx - 1]
                jindex = [jidx - 1, jidx - 1, jidx, jidx]
                xp = lon[jindex, iindex]
                yp = lat[jindex, iindex]
                verts = []
                for n in range(4):
                    verts.append([xp[n], yp[n]])
                inside = pnpoly(longitude, latitude, verts)

                if inside == 0:
                    iindex = [iidx - 1, iidx, iidx, iidx - 1]
                    jindex = [jidx, jidx, jidx + 1, jidx + 1]
                    xp = lon[jindex, iindex]
                    yp = lat[jindex, iindex]
                    verts = []
                    for n in range(4):
                        verts.append([xp[n], yp[n]])
                    inside = pnpoly(longitude, latitude, verts)

                    if inside == 0:
                        raise ValueError, "well where is it then?"

        iindex = iindex[:2]
        jindex = jindex[1:3]

    except:
        # print 'point (%f, %f) is not in the grid' %(longitude, latitude)
        iindex = []
        jindex = []

    return iindex, jindex
コード例 #31
0
#!/usr/bin/env python

import os, sys, time
import matplotlib.nxutils as nxutils
import matplotlib.numerix as nx

def report_memory(i):
    pid = os.getpid()
    a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
    print i, '  ', a2[1],
    return int(a2[1].split()[1])



for i in range(500):
    report_memory(i)
    verts = nx.mlab.rand(100, 2)
    b = nxutils.pnpoly(x, y, verts)
    
    for i in range(500):
        report_memory(i)
        verts = nx.mlab.rand(100, 2)
        points = nx.mlab.rand(10000,2)
        mask = nxutils.points_inside_poly(points, verts)

コード例 #32
0
ファイル: septazips.py プロジェクト: parthdoshi/seniordesign
 def poly_contains(self, poly, pt):
     """Check whether a polynomial contains pt."""
     poly = numpy.array(poly, float)
     nxutils.pnpoly(pt[0], pt[1], poly)
コード例 #33
0
ファイル: projections.py プロジェクト: rggibb/rhealpixdggs-py
def in_image(x, y, proj='healpix_sphere', north=0, south=0):
    r"""
    Return True if `(x, y)` lies in the image of the projection `proj`
    of the unit sphere, where `proj` is either
    'healpix_sphere' or 'rhealpix_sphere' and `north` and `south` indicate 
    the positions of the polar squares in case `proj` = 'rhealpix_sphere'.
    Return False otherwise.
        
    EXAMPLES::
    
        >>> eps = 0     # Test boundary points.
        >>> hp = [
        ... (-pi - eps, pi/4),
        ... (-3*pi/4, pi/2 + eps),
        ... (-pi/2, pi/4 + eps),
        ... (-pi/4, pi/2 + eps),
        ... (0, pi/4 + eps),
        ... (pi/4, pi/2 + eps),
        ... (pi/2, pi/4 + eps),
        ... (3*pi/4, pi/2 + eps),
        ... (pi + eps, pi/4),
        ... (pi + eps,-pi/4),
        ... (3*pi/4,-pi/2 - eps),
        ... (pi/2,-pi/4 - eps),
        ... (pi/4,-pi/2 - eps),
        ... (0,-pi/4 - eps),
        ... (-pi/4,-pi/2 - eps),
        ... (-pi/2,-pi/4 - eps),
        ... (-3*pi/4,-pi/2 - eps),
        ... (-pi - eps,-pi/4)
        ... ]
        >>> for p in hp:
        ...     if not in_image(*p):
        ...             print 'Fail'
        ... 
        >>> in_image(0, 0)
        True
        >>> in_image(0, pi/4 + 0.1)
        False
        >>> eps = 0     # Test boundary points.
        >>> north, south = 0, 0
        >>> rhp = [
        ... (-pi - eps, pi/4 + eps),
        ... (-pi + north*pi/2 - eps, pi/4 + eps),
        ... (-pi + north*pi/2 - eps, 3*pi/4 + eps),
        ... (-pi + (north + 1)*pi/2 + eps, 3*pi/4 + eps),
        ... (-pi + (north + 1)*pi/2 + eps, pi/4 + eps),
        ... (pi + eps, pi/4 + eps),
        ... (pi + eps,-pi/4 - eps),
        ... (-pi + (south + 1)*pi/2 + eps,-pi/4 - eps),
        ... (-pi + (south + 1)*pi/2 + eps,-3*pi/4 - eps),
        ... (-pi + south*pi/2 - eps,-3*pi/4 - eps),
        ... (-pi + south*pi/2 -eps,-pi/4 - eps),
        ... (-pi - eps,-pi/4 - eps)
        ... ]
        >>> for p in rhp:
        ...     if not in_image(*p, proj='rhealpix_sphere'):
        ...             print 'Fail'
        ... 
        >>> in_image(0, 0,proj='rhealpix_sphere')
        True
        >>> in_image(0, pi/4 + 0.1, proj='rhealpix_sphere')
        False
        
    """
    # matplotlib is a third-party module.
    from matplotlib.nxutils import pnpoly

    # Fuzz to slightly expand (r)HEALPix image boundary so that pnpoly()
    # counts points on the original boundary as lying in the image.
    eps = 1e-12
    if proj == 'healpix_sphere':
        vertices = [(-pi - eps, pi / 4), (-3 * pi / 4, pi / 2 + eps),
                    (-pi / 2, pi / 4 + eps), (-pi / 4, pi / 2 + eps),
                    (0, pi / 4 + eps), (pi / 4, pi / 2 + eps),
                    (pi / 2, pi / 4 + eps), (3 * pi / 4, pi / 2 + eps),
                    (pi + eps, pi / 4), (pi + eps, -pi / 4),
                    (3 * pi / 4, -pi / 2 - eps), (pi / 2, -pi / 4 - eps),
                    (pi / 4, -pi / 2 - eps), (0, -pi / 4 - eps),
                    (-pi / 4, -pi / 2 - eps), (-pi / 2, -pi / 4 - eps),
                    (-3 * pi / 4, -pi / 2 - eps), (-pi - eps, -pi / 4)]
    else:
        # Assume proj == 'rhealpix_sphere'
        vertices = [(-pi - eps, pi / 4 + eps),
                    (-pi + north * pi / 2 - eps, pi / 4 + eps),
                    (-pi + north * pi / 2 - eps, 3 * pi / 4 + eps),
                    (-pi + (north + 1) * pi / 2 + eps, 3 * pi / 4 + eps),
                    (-pi + (north + 1) * pi / 2 + eps, pi / 4 + eps),
                    (pi + eps, pi / 4 + eps), (pi + eps, -pi / 4 - eps),
                    (-pi + (south + 1) * pi / 2 + eps, -pi / 4 - eps),
                    (-pi + (south + 1) * pi / 2 + eps, -3 * pi / 4 - eps),
                    (-pi + south * pi / 2 - eps, -3 * pi / 4 - eps),
                    (-pi + south * pi / 2 - eps, -pi / 4 - eps),
                    (-pi - eps, -pi / 4 - eps)]
    return bool(pnpoly(x, y, vertices))
コード例 #34
0
ファイル: dvhcalc.py プロジェクト: carlosqueiroz/dicompyler-1
def calculate_dvh(structure, dose, limit=None, callback=None):
    """Calculate the differential DVH for the given structure and dose grid."""

    sPlanes = structure['planes']
    logger.debug("Calculating DVH of %s %s", structure['id'], structure['name'])

    # Get the dose to pixel LUT
    doselut = dose.GetPatientToPixelLUT()

    # Generate a 2d mesh grid to create a polygon mask in dose coordinates
    # Code taken from Stack Overflow Answer from Joe Kington:
    # http://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask/3655582
    # Create vertex coordinates for each grid cell
    x, y = np.meshgrid(np.array(doselut[0]), np.array(doselut[1]))
    x, y = x.flatten(), y.flatten()
    dosegridpoints = np.vstack((x,y)).T

    # Create an empty array of bins to store the histogram in cGy
    # only if the structure has contour data or the dose grid exists
    if ((len(sPlanes)) and ("PixelData" in dose.ds)):

        # Get the dose and image data information
        dd = dose.GetDoseData()
        id = dose.GetImageData()

        maxdose = int(dd['dosemax'] * dd['dosegridscaling'] * 100)
        # Remove values above the limit (cGy) if specified
        if not (limit == None):
            if (limit < maxdose):
                maxdose = limit
        hist = np.zeros(maxdose)
    else:
        hist = np.array([0])
    volume = 0

    plane = 0
    # Iterate over each plane in the structure
    for z, sPlane in sPlanes.iteritems():

        # Get the contours with calculated areas and the largest contour index
        contours, largestIndex = calculate_contour_areas(sPlane)

        # Get the dose plane for the current structure plane
        doseplane = dose.GetDoseGrid(z)

        # If there is no dose for the current plane, go to the next plane
        if not len(doseplane):
            break

        # Calculate the histogram for each contour
        for i, contour in enumerate(contours):
            m = get_contour_mask(doselut, dosegridpoints, contour['data'])
            h, vol = calculate_contour_dvh(m, doseplane, maxdose,
                                           dd, id, structure)
            # If this is the largest contour, just add to the total histogram
            if (i == largestIndex):
                hist += h
                volume += vol
            # Otherwise, determine whether to add or subtract histogram
            # depending if the contour is within the largest contour or not
            else:
                contour['inside'] = False
                for point in contour['data']:
                    if nx.pnpoly(point[0], point[1],
                                 np.array(contours[largestIndex]['data'])):
                        contour['inside'] = True
                        # Assume if one point is inside, all will be inside
                        break
                # If the contour is inside, subtract it from the total histogram
                if contour['inside']:
                    hist -= h
                    volume -= vol
                # Otherwise it is outside, so add it to the total histogram
                else:
                    hist += h
                    volume += vol
        plane += 1
        if not (callback == None):
            callback(plane, len(sPlanes))
    # Volume units are given in cm^3
    volume = volume/1000
    # Rescale the histogram to reflect the total volume
    hist = hist*volume/sum(hist)
    # Remove the bins above the max dose for the structure
    hist = np.trim_zeros(hist, trim='b')

    return hist
コード例 #35
0
    def paintEvent(self, e):
        if rospy.is_shutdown(): QtGui.QApplication.quit()
        # circle the objects
        r = 150

        self.SCREEN_HEIGHT = self.height()
        self.SCREEN_WIDTH = self.width()

        cursor_coords = None

        with self.object_lock:

            # Draw the circles
            if self.objects is not None and self.projected_objects is not None and self.circle_objects:
                # is dist(cursor,pt) <= dist(cursor,obj) for all obj?
                cursor = np.median(self.projected_cursor, 0)
                distances = [
                    self.dist(pp, cursor) for pp in self.projected_objects[0]
                ]
                closest_pt = self.projected_objects[0, np.argmin(distances)]

                for pt, xformed in zip(self.objects[0],
                                       self.projected_objects[0]):
                    qp = QtGui.QPainter()
                    qp.begin(self)
                    qp.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
                    color = Colors.WHITE
                    if self.isHilighted(pt):
                        # color = self.getHilightColor(pt)
                        inner_pen = qp.pen()
                        inner_pen.setWidth(6)
                        inner_pen.setColor(self.getHilightColor(pt))
                        qp.setPen(inner_pen)
                        coords = self.maybe_flip((xformed[1], xformed[0]))
                        inner_rect = QtCore.QRectF(
                            self.SCREEN_WIDTH - coords[0] - r / 2 + X_OFFSET +
                            5, self.SCREEN_HEIGHT - coords[1] - r / 2 +
                            Y_OFFSET + 5, r - 10, r - 10)
                        qp.drawArc(inner_rect, 0, 360 * 16)

                    if (self.use_selected_thresh and self.isSelected(xformed)) or\
                       (not self.use_selected_thresh and all(xformed==closest_pt)):
                        self.selected_pt = pt
                        color = Colors.GREEN
                    else:
                        self.selected_pt = CLICK_RESET

                    # is it the clicked point?
                    if self.sameObject(pt, self.click_loc):
                        color = Colors.BLUE

                    qp.setPen(color)
                    pen = qp.pen()
                    pen.setWidth(5)
                    qp.setPen(pen)
                    coords = self.maybe_flip((xformed[1], xformed[0]))
                    rect = QtCore.QRectF(coords[0] - r / 2 + X_OFFSET,
                                         coords[1] - r / 2 + Y_OFFSET, r, r)
                    qp.drawArc(rect, 0, 360 * 16)
                    qp.end()

            # draw the cursor
            r = 10
            with self.object_lock:
                if self.cursor_pts is not None and len(
                        self.projected_cursor) > 0:
                    xformed = np.median(self.projected_cursor, 0)
                    coords = self.maybe_flip((xformed[1], xformed[0]))
                    cursor_x = coords[0]
                    cursor_y = coords[1]

                    qp = QtGui.QPainter()
                    qp.begin(self)
                    qp.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
                    color = Colors.BLUE
                    qp.setPen(color)
                    pen = qp.pen()
                    pen.setWidth(5)
                    qp.setPen(pen)

                    # if the cursor is on-screen, draw it
                    if cursor_x > 0 and cursor_y > 0 and cursor_x < self.SCREEN_WIDTH and cursor_y < self.SCREEN_HEIGHT:
                        rect = QtCore.QRectF(
                            cursor_x - r / 2,  # + X_OFFSET,
                            cursor_y - r / 2,  # + Y_OFFSET,
                            r,
                            r)
                        qp.drawArc(rect, 0, 360 * 16)
                    # if the cursor is off screen, draw a hint as to where it is
                    else:
                        hint_x = cursor_x
                        if cursor_x < 0:
                            hint_x = 0
                        if cursor_x > self.SCREEN_WIDTH:
                            hint_x = self.SCREEN_WIDTH

                        hint_y = cursor_y
                        if cursor_y < 0:
                            hint_y = 0
                        if cursor_y > self.SCREEN_HEIGHT:
                            hint_y = self.SCREEN_HEIGHT

                        head = np.array([hint_x,
                                         hint_y])  # + [X_OFFSET, Y_OFFSET]
                        tail_x, tail_y = 0, 0
                        if hint_x == 0:
                            tail_x = 50
                        if hint_x == self.SCREEN_WIDTH:
                            tail_x = -50
                        if hint_y == 0:
                            tail_y = 50
                        if hint_y == self.SCREEN_HEIGHT:
                            tail_y = -50
                        tail = head + [tail_x, tail_y]

                        pen.setWidth(r)
                        qp.setPen(pen)

                        qp.drawLine(head[0], head[1], tail[0], tail[1])
                    qp.end()

            # draw any polygons
            qp = QtGui.QPainter()
            qp.begin(self)
            qp.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)

            for uid, (polygon, color, label,
                      text_rect) in self.polygons.iteritems():
                poly = PySide.QtGui.QPolygon()
                pts_arr = np.array([[(p.x, p.y, p.z)
                                     for p in polygon.polygon.points]])
                points = self.projectPoints(pts_arr, polygon.header)
                points = cv2.perspectiveTransform(points, self.H)

                if self.flip:
                    points[0] = ([self.SCREEN_HEIGHT, self.SCREEN_WIDTH] -
                                 points[0])

                if self.cursor_pts is not None and len(
                        self.projected_cursor) > 0:
                    if pnpoly(cursor_y, cursor_x, points[0]):
                        color = Colors.GREEN
                        self.selected_pt = np.array(pts_arr.squeeze().mean(0))

                selected_pt_xformed = self.projectPoints(
                    np.array([[self.click_loc.squeeze()]]), polygon.header)
                selected_pt_xformed = cv2.perspectiveTransform(
                    selected_pt_xformed, self.H).squeeze()

                if pnpoly(selected_pt_xformed[0], selected_pt_xformed[1],
                          points[0]):
                    color = Colors.BLUE
                    if not self.click_stale:
                        self.clicked_object_pub.publish(uid)
                        self.click_stale = True

                qp.setPen(color)
                pen = qp.pen()
                pen.setWidth(5)
                qp.setPen(pen)

                for point in points[0]:
                    poly.push_back(PySide.QtCore.QPoint(point[1], point[0]))

                qp.drawPolygon(poly)
                origin = points[0].min(0)
                size = points[0].max(0) - origin

                textRect = poly.boundingRect()
                if len(text_rect.points) > 0:
                    text_rect_points = self.projectPoints(
                        np.array([[(p.x, p.y, p.z)
                                   for p in text_rect.points]]),
                        polygon.header)
                    text_rect_points = cv2.perspectiveTransform(
                        text_rect_points, self.H)
                    if self.flip:
                        text_rect_points[0] = (
                            [self.SCREEN_HEIGHT, self.SCREEN_WIDTH] -
                            text_rect_points[0])
                    text_poly = PySide.QtGui.QPolygon()
                    for point in text_rect_points[0]:
                        text_poly.push_back(
                            PySide.QtCore.QPoint(point[1], point[0]))
                    textRect = text_poly.boundingRect()

                qp.setFont(QtGui.QFont('Decorative', 30))
                qp.drawText(textRect,
                            QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap,
                            label)

        # reset once the click has expired
        if (rospy.Time.now() - self.click) >= self.click_duration:
            self.click_loc = CLICK_RESET
            self.click_stale = False
            self.click_duration = rospy.Duration(2.0)

        self.rate_pub.publish()
コード例 #36
0
ファイル: utility.py プロジェクト: gorsol/Pyroms-1
def find_nearestgridpoints(longitude, latitude, grd, Cpos='rho'):


    if type(grd).__name__ == 'ROMS_Grid':

        if Cpos is 'u':
            lon = grd.hgrid.lon_u[:,:]
            lat = grd.hgrid.lat_u[:,:]
        elif Cpos is 'v':
            lon = grd.hgrid.lon_v[:,:]
            lat = grd.hgrid.lat_v[:,:]
        elif Cpos is 'rho':
            lon = grd.hgrid.lon_rho[:,:]
            lat = grd.hgrid.lat_rho[:,:]
        elif Cpos is 'vert':
            lon = grd.hgrid.lon_vert[:,:]
            lat = grd.hgrid.lat_vert[:,:]
        else:
            raise Warning, '%s bad position. Cpos must be rho, u or v.' % Cpos


    if type(grd).__name__ == 'CGrid_geo':

        if Cpos is 'u':
            lon = grd.lon_u[:,:]
            lat = grd.lat_u[:,:]
        elif Cpos is 'v':
            lon = grd.lon_v[:,:]
            lat = grd.lat_v[:,:]
        elif Cpos is 'rho':
            lon = grd.lon_rho[:,:]
            lat = grd.lat_rho[:,:]
        elif Cpos is 'vert':
            lon = grd.lon_vert[:,:]
            lat = grd.lat_vert[:,:]
        else:
            raise Warning, '%s bad position. Cpos must be rho, u or v.' % Cpos


    dlon = lon[:,:] - longitude
    dlat = lat[:,:] - latitude

    diff = (dlon * dlon) + (dlat * dlat)

    jidx, iidx = np.where(diff==diff.min())

    iidx = iidx[0] # take element 1 in case min dist is not unique
    jidx = jidx[0]

    try:

        iindex = [iidx, iidx+1, iidx+1, iidx]
        jindex = [jidx, jidx, jidx+1, jidx+1]
        xp = lon[jindex, iindex]
        yp = lat[jindex, iindex]
        verts = []
        for n in range(4):
            verts.append([xp[n], yp[n]])
        inside = pnpoly(longitude, latitude, verts)

        if inside == 0:
            iindex = [iidx, iidx+1, iidx+1, iidx]
            jindex = [jidx-1, jidx-1, jidx, jidx]
            xp = lon[jindex, iindex]
            yp = lat[jindex, iindex]
            verts = []
            for n in range(4):
                verts.append([xp[n], yp[n]])
            inside = pnpoly(longitude, latitude, verts)

            if inside == 0:
                iindex = [iidx-1, iidx, iidx, iidx-1]
                jindex = [jidx-1, jidx-1, jidx, jidx]
                xp = lon[jindex, iindex]
                yp = lat[jindex, iindex]
                verts = []
                for n in range(4):
                    verts.append([xp[n], yp[n]])
                inside = pnpoly(longitude, latitude, verts)

                if inside == 0:
                    iindex = [iidx-1, iidx, iidx, iidx-1]
                    jindex = [jidx, jidx, jidx+1, jidx+1]
                    xp = lon[jindex, iindex]
                    yp = lat[jindex, iindex]
                    verts = []
                    for n in range(4):
                        verts.append([xp[n], yp[n]])
                    inside = pnpoly(longitude, latitude, verts)

                    if inside == 0:
                        raise ValueError, 'well where is it then?'

        iindex = iindex[:2]
        jindex = jindex[1:3]

    except:
        #print 'point (%f, %f) is not in the grid' %(longitude, latitude)
        iindex = []
        jindex = []
        
    return iindex, jindex
コード例 #37
0
def calculate_dvh(structure, dose, limit=None, callback=None):
    """Calculate the differential DVH for the given structure and dose grid."""

    sPlanes = structure['planes']
    logger.debug("Calculating DVH of %s %s", structure['id'],
                 structure['name'])

    # Get the dose to pixel LUT
    doselut = dose.GetPatientToPixelLUT()

    # Generate a 2d mesh grid to create a polygon mask in dose coordinates
    # Code taken from Stack Overflow Answer from Joe Kington:
    # http://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask/3655582
    # Create vertex coordinates for each grid cell
    x, y = np.meshgrid(np.array(doselut[0]), np.array(doselut[1]))
    x, y = x.flatten(), y.flatten()
    dosegridpoints = np.vstack((x, y)).T

    # Create an empty array of bins to store the histogram in cGy
    # only if the structure has contour data or the dose grid exists
    if ((len(sPlanes)) and ("PixelData" in dose.ds)):

        # Get the dose and image data information
        dd = dose.GetDoseData()
        id = dose.GetImageData()

        maxdose = int(dd['dosemax'] * dd['dosegridscaling'] * 100)
        # Remove values above the limit (cGy) if specified
        if not (limit == None):
            if (limit < maxdose):
                maxdose = limit
        hist = np.zeros(maxdose)
    else:
        hist = np.array([0])
    volume = 0

    plane = 0
    # Iterate over each plane in the structure
    for z, sPlane in sPlanes.iteritems():

        # Get the contours with calculated areas and the largest contour index
        contours, largestIndex = calculate_contour_areas(sPlane)

        # Get the dose plane for the current structure plane
        doseplane = dose.GetDoseGrid(z)

        # If there is no dose for the current plane, go to the next plane
        if not len(doseplane):
            break

        # Calculate the histogram for each contour
        for i, contour in enumerate(contours):
            m = get_contour_mask(doselut, dosegridpoints, contour['data'])
            h, vol = calculate_contour_dvh(m, doseplane, maxdose, dd, id,
                                           structure)
            # If this is the largest contour, just add to the total histogram
            if (i == largestIndex):
                hist += h
                volume += vol
            # Otherwise, determine whether to add or subtract histogram
            # depending if the contour is within the largest contour or not
            else:
                contour['inside'] = False
                for point in contour['data']:
                    if nx.pnpoly(point[0], point[1],
                                 np.array(contours[largestIndex]['data'])):
                        contour['inside'] = True
                        # Assume if one point is inside, all will be inside
                        break
                # If the contour is inside, subtract it from the total histogram
                if contour['inside']:
                    hist -= h
                    volume -= vol
                # Otherwise it is outside, so add it to the total histogram
                else:
                    hist += h
                    volume += vol
        plane += 1
        if not (callback == None):
            callback(plane, len(sPlanes))
    # Volume units are given in cm^3
    volume = volume / 1000
    # Rescale the histogram to reflect the total volume
    hist = hist * volume / sum(hist)
    # Remove the bins above the max dose for the structure
    hist = np.trim_zeros(hist, trim='b')

    return hist
コード例 #38
0
"""
Another broken test...
"""
import os, sys, time
import matplotlib.nxutils as nxutils
from numpy.random import rand
def report_memory(i):
    pid = os.getpid()
    a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
    print i, '  ', a2[1],
    return int(a2[1].split()[1])
for i in range(500):
    report_memory(i)
    verts = rand(100, 2)
    b = nxutils.pnpoly(x, y, verts)   # x, y don't exist
    for i in range(500):
        report_memory(i)
        verts = rand(100, 2)
        points = rand(10000,2)
        mask = nxutils.points_inside_poly(points, verts)
コード例 #39
0
#!/usr/bin/env python
"""
Another broken test...
"""

from __future__ import print_function
import os, sys, time
import matplotlib.nxutils as nxutils
from numpy.random import rand


def report_memory(i):
    pid = os.getpid()
    a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
    print(i, '  ', a2[1], end='')
    return int(a2[1].split()[1])


for i in range(500):
    report_memory(i)
    verts = rand(100, 2)
    b = nxutils.pnpoly(x, y, verts)  # x, y don't exist

    for i in range(500):
        report_memory(i)
        verts = rand(100, 2)
        points = rand(10000, 2)
        mask = nxutils.points_inside_poly(points, verts)