コード例 #1
0
ファイル: margin.py プロジェクト: w20ss11/docstrum
    def fit(self, lines):

        # Collate all the contours from all the 'border' words (those on the first and last lines, and
        # the first and last words from all other lines).
        borderPoints = g.PointArray()
        for word in self.selectBorderWords(lines):
            for wrappedPoint in word.contour:
                borderPoints.append(wrappedPoint[0])

        self.angle = lines.avgAngle

        # interestingly, it's faster to sort the whole list, which is theoretical O(n log n), than it is
        # to do a min operation followed by a max operation, both of which are O(n).
        sortedHorizontally = sorted(
            borderPoints, key=lambda point: point.rotate(self.angle).x)
        leftPoint = sortedHorizontally[0]
        rightPoint = sortedHorizontally[-1]

        sortedVertically = sorted(borderPoints,
                                  key=lambda point: point.rotate(self.angle).y)
        topPoint = sortedVertically[0]
        bottomPoint = sortedVertically[-1]

        self.left = g.Line([leftPoint], self.angle)
        self.right = g.Line([rightPoint], self.angle)
        self.top = g.Line([topPoint], self.angle + 90)
        self.bottom = g.Line([bottomPoint], self.angle + 90)

        self.height = abs(
            topPoint.rotate(self.angle).y - bottomPoint.rotate(self.angle).y)
        self.width = abs(
            leftPoint.rotate(self.angle).x - rightPoint.rotate(self.angle).x)
コード例 #2
0
def test_pseudo_tangent_contact():
    circle = gm.Circle(radius=20, center=gm.Point(0, 0))
    # Parallel to x-axis
    pt1 = gm.Point(-1, 25)
    pt2 = gm.Point(1, 25)
    l1 = gm.Line(pt1, pt2)
    l2 = gm.Line(pt2, pt1)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    iPt2 = circle.get_contact_point_pseudo_tangent(l2)
    print "GT: (0,20), Predict: ", iPt1
    print "GT: (0,20), Predict: ", iPt2
    # Parallel to y-axis
    pt1 = gm.Point(-25, 5)
    pt2 = gm.Point(-25, 50)
    pt3 = gm.Point(30, 5)
    pt4 = gm.Point(30, 50)
    l1 = gm.Line(pt1, pt2)
    l2 = gm.Line(pt3, pt4)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    iPt2 = circle.get_contact_point_pseudo_tangent(l2)
    print "GT: (-20,0), Predict: ", iPt1
    print "GT: (20,0), Predict: ", iPt2
    # A diagonal
    pt1 = gm.Point(50, 0)
    pt2 = gm.Point(0, 50)
    l1 = gm.Line(pt1, pt2)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    print iPt1
コード例 #3
0
 def make_coordinates(self):
     self.lTop_ = self.pos_
     self.lBot_ = self.pos_ + gm.Point(0, self.sz_.y())
     self.rTop_ = self.pos_ + gm.Point(self.sz_.x(), 0)
     self.rBot_ = self.pos_ + gm.Point(self.sz_.x(), self.sz_.y())
     self.l1_ = gm.Line(self.lTop_, self.lBot_)  # Left line
     self.l2_ = gm.Line(self.lBot_, self.rBot_)
     self.l3_ = gm.Line(self.rBot_, self.rTop_)
     self.l4_ = gm.Line(self.rTop_, self.lTop_)
     self.bbox_ = gm.Bbox(self.lTop_, self.lBot_, self.rBot_, self.rTop_)
コード例 #4
0
def is_corner_sharp( end_point1, center_point, end_point2 ):
    """Returns True if angle between lines end_point1-cetner_point
    and center_point-end_point2 is less then 90 degrees."""

    cathetus1 = geometry.Line( center_point, end_point1 )
    cathetus2 = cathetus1.perpendicular( end_point1 )
    hypotenuse = geometry.Line( center_point, end_point2 )

    cathetus2_intersection = geometry.intersect_lines( cathetus2, hypotenuse )

    if cathetus2_intersection is None:
        return False

    return cathetus1.are_on_the_same_side( end_point2, cathetus2_intersection )
コード例 #5
0
def test_line_bbox_intersection():
    bbox = gm.Bbox(gm.Point(1, 2), gm.Point(1, 1), gm.Point(2, 1), gm.Point(2, 2))
    l1 = gm.Line(gm.Point(0, 0), gm.Point(1.5, 1.9))
    l2 = gm.Line(gm.Point(0, 0), gm.Point(1, 10))
    l3 = gm.Line(gm.Point(0, 1), gm.Point(5, 1))
    print "GT: True, Predict:", bbox.is_intersect_line(l1)
    print "GT: False, Predict:", bbox.is_intersect_line(l2)
    print "GT: True, Predict:", bbox.is_intersect_line(l3)

    pt1, s1 = bbox.get_intersection_with_line(l1)
    pt2, s2 = bbox.get_intersection_with_line(l2)
    pt3, s3 = bbox.get_intersection_with_line(l3)
    print pt1, s1
    print pt2, s2
    print pt3, s3
コード例 #6
0
    def run_process(self, iterations):

        for k in range(iterations):

            line_hits_cluster = False

            while not line_hits_cluster:
                random_line_params = self.get_random_line()
                random_line = geom.Line(random_line_params[0],
                                        random_line_params[1])

                if self.line_hits_cluster(random_line):
                    line_hits_cluster = True

                    next_particle = self.get_next_particle(random_line)
                    """
					add particle at next_particle to the cluster, remove it from the boundary_set and add its empty neighbours to it,
					actualize cluster_radius, so the next random line can be chosen correct accordingly
					"""
                    self.particles.append(next_particle)
                    self.actualize_boundary_set()

                    self.actualize_cluster_radius()

                    print(k)

                else:
                    self.missed_counter += 1  #counts how often a random line missed the current cluster, as described in the paper
                    print("line missed cluster")

        print("DONE")
        print("number of misses: " + str(self.missed_counter))
    def update_rangefinder_sensors(self):
        """
        The function to update the agent range finder sensors.
        """
        for i, angle in enumerate(self.agent.range_finder_angles):
            rad = geometry.deg_to_rad(angle)
            # project a point from agent location outwards
            projection_point = geometry.Point(
                x=self.agent.location.x +
                math.cos(rad) * self.agent.range_finder_range,
                y=self.agent.location.y +
                math.sin(rad) * self.agent.range_finder_range)
            # rotate the projection point by the agent's heading angle to
            # align it with heading direction
            projection_point.rotate(self.agent.heading, self.agent.location)
            # create the line segment from the agent location to the projected point
            projection_line = geometry.Line(a=self.agent.location,
                                            b=projection_point)
            # set range to maximum detection range
            min_range = self.agent.range_finder_range

            # now test against maze walls to see if projection line hits any wall
            # and find the closest hit
            for wall in self.walls:
                found, intersection = wall.intersection(projection_line)
                if found:
                    found_range = intersection.distance(self.agent.location)
                    # we are interested in the closest hit
                    if found_range < min_range:
                        min_range = found_range

            # Update sensor value
            self.agent.range_finders[i] = min_range
コード例 #8
0
 def create_geometries(self):
     return {
         self.name: [
             geometry.Line(start=d1, end=d2)
             for (d1, d2) in pairwise(self.dc.to_dc_items(self.axis))
         ]
     }
コード例 #9
0
 def vertice_for_one_corner_wall( corner_point, end_point, other_end_point ):
     vertices = vertices_for_line_segment_end( corner_point, end_point, offset )
     wall_line = geometry.Line( corner_point, end_point )
     if not wall_line.are_on_the_same_side( vertices[0], other_end_point ):
         return vertices[0]
     else:
         return vertices[1]
コード例 #10
0
 def parallel_outstanding_line( corner, end, other_end ):
     corner_wall_line = geometry.Line( corner, end )
     perpendicular = corner_wall_line.perpendicular( corner )
     intersections = geometry.intersect_line_and_circle( geometry.Circle( corner, offset ), perpendicular )
     assert( len( intersections ) == 2 )
     if not corner_wall_line.are_on_the_same_side( intersections[0], other_end ):
         return perpendicular.perpendicular( intersections[0] )
     else:
         return perpendicular.perpendicular(intersections[1])
コード例 #11
0
ファイル: generateBody.py プロジェクト: zeta1999/PetIBM
def main(args):
  """
  Generates a file containing the coordinates of a body.

  Parameters
  ----------
  args: namespace
    Arguments parsed from the command-line.
  """
  if args.body_type == 'file':
    body = geometry.Geometry(file_path=args.file_path)
  elif args.body_type == 'circle':
    body = geometry.Circle(radius=args.circle[0],
                           center=geometry.Point(args.circle[1],
                                                 args.circle[2]),
                           n=args.n, ds=args.ds)
  elif args.body_type == 'line':
    body = geometry.Line(length=args.line[0],
                         start=geometry.Point(args.line[1], args.line[2]),
                         n=args.n, ds=args.ds)
  elif args.body_type == 'rectangle':
    body = geometry.Rectangle(bottom_left=geometry.Point(args.rectangle[0],
                                                         args.rectangle[1]),
                              top_right=geometry.Point(args.rectangle[2],
                                                       args.rectangle[3]),
                              nx=args.n,
                              ny=args.n,
                              ds=args.ds)
  elif args.body_type == 'sphere':
    body = geometry.Sphere(radius=args.sphere[0],
                           center=geometry.Point(args.sphere[1],
                                                 args.sphere[2],
                                                 args.sphere[3]),
                           n=args.n,
                           ds=args.ds)
  body.scale(ratio=args.scale)
  body.rotation(center=args.rotation,
                roll=args.roll,
                yaw=args.yaw,
                pitch=args.pitch,
                mode=args.mode)
  body.translation(displacement=args.translation)
  if body.dimensions == 2 and args.body_type == 'file':
    body.discretization(n=args.n,
                        ds=args.ds)
  if body.dimensions == 2 and args.extrusion:
    body = body.extrusion(limits=args.extrusion,
                          n=args.n,
                          ds=args.ds,
                          force=args.force)
  if args.save:
    output_path = os.path.join(args.save_directory,
                               args.save_name + '.' + args.extension)
    body.write(file_path=output_path)
  if args.show:
      body.plot()
コード例 #12
0
ファイル: dynamics.py プロジェクト: pulkitag/pyphy-engine
def get_toc_ball_wall(obj1, obj2):
	'''
		obj1: ball
		obj2: wall
	'''
	lines = obj2.get_lines()
	vel   = obj1.get_velocity()
	pos   = obj1.get_position()
	r     = obj1.get_radius()
	tCol    = np.inf
	nrmlCol = None
	ptCol   = None
	for l in lines:
		#This is the nrml from the line towards the point
		nrml    = l.get_normal_towards_point(pos)
		nrml.scale(-1) #Normal from point towards line
		speed   = vel.dot(nrml)	
		if speed <=0:
			continue
		#Velocity in orthogonal direction
		velOrth = vel - (speed * nrml)
		lDir    = l.get_direction()	
		#Find the time of collision
		ray = gm.Line(pos, pos + nrml)
		intPoint = l.get_intersection_ray(ray)
		#print l
		assert intPoint is not None, ("Intersection point cannot be none - pos, nmrl", 
												pos.x(), pos.y(), nrml.x(), nrml.y())
		distCenter = pos.distance(intPoint)
		dist       = distCenter - r	
		if dist < 0:
			#It is possible that a line (but not the line segment) intersects the ball. Then
			#dist < 0, and we need to rule out such cases. 
			assert distCenter >= 0
			onSegment = l.is_on_segment(intPoint)
			if onSegment:
				print "Something is amiss" 
				pdb.set_trace()
			else:
				continue
		t = dist / speed
		#Find the intersection point on line
		#i.e. the point 
		linePoint = intPoint + (t * velOrth)
		onSegment = l.is_on_segment(linePoint)
		if not onSegment:
			continue	
		if t < tCol:
			tCol    = t
			nrml.scale(-1)
			nrmlCol = nrml
			ptCol   = linePoint					
	
	#pdb.set_trace()
	#print tCol, nrmlCol, ptCol
	return tCol, nrmlCol, ptCol	
コード例 #13
0
    def paint(self, image, color=colors.YELLOW):

        for character in self.characters:
            image = character.paint(image, color)

            for neighbour in character.nearestNeighbours:
                line = g.Line([character, neighbour])
                image = line.paint(image, color)

        return image
コード例 #14
0
def test_get_normal_towards_point():
    pt1 = gm.Point(0, 0)
    pt2 = gm.Point(1, 1)
    l = gm.Line(pt1, pt2)
    pt3 = gm.Point(1, 0)
    nr1 = l.get_normal_towards_point(pt3)
    print "GT: (0.71,-0.71), Predict: ", nr1
    pt3 = gm.Point(0, 1)
    nr1 = l.get_normal_towards_point(pt3)
    print "GT: (-0.71,0.71), Predict: ", nr1
コード例 #15
0
 def calculate(self, face):
     top = Point(face.central_point.x, 0)
     vertical_line = geometry.Line(face.central_point, top)
     self.break_point_nose_point = DisplacementAngle(
         face.break_point, face.point_nose, vertical_line)
     self.central_point_wall = SymmetryAngle(face.wall, face.central_point,
                                             top)
     self.nose_point_wall = SymmetryAngle(face.wall, face.point_nose,
                                          face.break_point)
     self.nose_point_maxilar = SymmetryAngle(face.maxilar, face.point_nose,
                                             face.break_point)
コード例 #16
0
ファイル: margin.py プロジェクト: w20ss11/docstrum
    def __init__(self, candidateLines):

        self.candidateLines = candidateLines

        fullLines = [
            line for line in self.candidateLines
            if 1280 < line.box.width < 1330
        ]
        left = g.Line([line.box.center.left for line in fullLines])
        right = g.Line([line.box.center.right for line in fullLines])

        # Make sure that 'start' means the same end for both geometric lines. This fixes a frustrating problem,
        # where in some pages most lines wouldn't be picked up.
        if left.start[1] < left.end[1]:
            left.start, left.end = left.end, left.start
        if right.start[1] < right.end[1]:
            right.start, right.end = right.end, right.start

        self.points = g.PointArray(
            [left.start, left.end, right.end, right.start])
コード例 #17
0
 def findTuples(self):
     # Get tuple info ... 2/21/2018
     for character in self.characters:
         for neighbour in character.nearestNeighbours:
             line = g.Line([character, neighbour])
             angle = line.calculateAngle(line.start, line.end)
             delta = line.start - line.end
             distance = math.sqrt(delta.x**2 + delta.y**2)
             #print("START: ",line.start, " END: ", line.end, " DIST: ", distance," ANGLE_degree: ", angle.degrees(), "ANGLE_canonical: ", angle.canonical)
             self.angles.append(angle.canonical)
             #self.angles.append(angle.degrees())
             self.distances.append(distance)
コード例 #18
0
ファイル: mapping.py プロジェクト: chyplos/python-pathfinding
 def __visibility_test(self, node_a, node_b):
     """Performs a simple direct visibility test between two points, in an
     unoptimized fashion"""
     # Todo: ensure visibility checks cannot go through polygons (facepalm)
     direct_line = geometry.Line(node_a, node_b)
     for p in self.polygons:
         for l in p.lines:
             if l.does_intersect(direct_line, False):
                 return False
         for l in p.triangle_lines:
             if l.does_intersect(direct_line, False):
                 return False
         if direct_line in p.triangle_lines: return False
     return True  # survived all the tests
コード例 #19
0
    def paint(self, image, color=colors.YELLOW):

        for character in self.characters:
            image = character.paint(image, color)

            for neighbour in character.nearestNeighbours:
                line = g.Line([character, neighbour])
                image = line.paint(image, color, thickness=1)

        box = self.getBoundingBox()
        if box is not None:
            cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]),
                          (0, 255, 0), 1)

        return image
コード例 #20
0
ファイル: lha_optimized.py プロジェクト: donnyhai/dla
	def get_random_line(self):
		
		"""
		We choose uniform random parameters (alpha, p) in [0, pi) x [0, 20/19 * self.cluster_radius) 
		which is equivalent to choosing a B-isotropic line where B is a circle with radius 20/19 * self.cluster_radius with center 0
		and by contstruction therefore certainly contains the current cluster. 
		random.random() chooses uniformly in [0, 1.0)
		return is the parameters pair (alpha, p)
		"""
	 
		alpha = pi * random.random()
		radius = self.cluster_radius + 2 #radius of a circle which certainly surrounds the current cluster
		p = 2 * radius * random.random() - radius
		
		return geom.Line(alpha, p)
コード例 #21
0
def test_line_ray_intersection():
    l1 = gm.Line(gm.Point(-5, 5), gm.Point(5, 5))
    l2 = gm.Line(gm.Point(-1, 0), gm.Point(1, 10))
    print "GT:(0,5) Predict:", l1.get_intersection_ray(l2)

    l1 = gm.Line(gm.Point(-5, 5), gm.Point(5, 5))
    l2 = gm.Line(gm.Point(-1, 0), gm.Point(-1, 3))
    print "GT:(-1,5) Predict:", l1.get_intersection_ray(l2)

    l1 = gm.Line(gm.Point(-5, 5), gm.Point(5, 5))
    l2 = gm.Line(gm.Point(-1, 3), gm.Point(-1, 0))
    print "GT:None Predict:", l1.get_intersection_ray(l2)
コード例 #22
0
def test_line_intersection():
    # Intersect x, y axis
    l1 = gm.Line(gm.Point(-1, 0), gm.Point(1, 0))
    l2 = gm.Line(gm.Point(0, -1), gm.Point(0, 1))
    print "GT:(0,0) Predict:", l1.get_intersection(l2)

    # 45 lines
    l1 = gm.Line(gm.Point(0, 0), gm.Point(1, 1))
    l2 = gm.Line(gm.Point(1, 0), gm.Point(0, 1))
    print "GT:(0.5,0.5) Predict:", l1.get_intersection(l2)

    # Parallel lines
    l1 = gm.Line(gm.Point(0, 0), gm.Point(1, 1))
    l2 = gm.Line(gm.Point(1, 3), gm.Point(5, 7))
    print "GT:None Predict:", l1.get_intersection(l2)

    # Parallel lines
    l1 = gm.Line(gm.Point(0, -1), gm.Point(0, 1))
    l2 = gm.Line(gm.Point(2, -1), gm.Point(2, 1))
    print "GT:None Predict:", l1.get_intersection(l2)
コード例 #23
0
def get_box_coords(stPoint, enPoint, wThick=30):
    '''
        stPoint: bottom-left point
        enPoint: The direction along which thickness needs to expanded.
        wThick: thickness of the wall
    '''
    line = gm.Line(stPoint, enPoint)
    pDiff = enPoint - stPoint
    dist = pDiff.mag()
    nrml = line.get_normal()
    lDir = line.get_direction()
    # print "nrml", nrml
    pt1 = stPoint
    pt2 = pt1 + dist * lDir
    pt3 = pt2 - (wThick * nrml)
    pt4 = pt3 - (dist * lDir)
    pts = [pt1, pt2, pt3, pt4]
    # print pt1, pt2, pt3, pt4
    return pts
コード例 #24
0
def test_line_ray_bbox_intersection():
    bbox = gm.Bbox(gm.Point(1, 2), gm.Point(1, 1), gm.Point(2, 1), gm.Point(2, 2))
    l1 = gm.Line(gm.Point(0, 0), gm.Point(1.5, 1.9))
    l2 = gm.Line(gm.Point(0, 0), gm.Point(1, 10))
    l3 = gm.Line(gm.Point(0, 1), gm.Point(5, 1))
    print "GT: True, Predict:", bbox.is_intersect_line(l1)
    print "GT: False, Predict:", bbox.is_intersect_line(l2)
    print "GT: True, Predict:", bbox.is_intersect_line(l3)

    l4 = gm.Line(gm.Point(1.5, 0.5), gm.Point(1.5, -0.5))
    l6 = gm.Line(gm.Point(1.5, -0.5), gm.Point(1.5, 0.5))
    l5 = gm.Line(gm.Point(1.5, 1.9), gm.Point(0, 0))
    print "GT: False, Predict:", bbox.is_intersect_line_ray(l4)
    print "GT: True, Predict:", bbox.is_intersect_line(l4)
    print "GT: True, Predict:", bbox.is_intersect_line_ray(l6)
    print "GT: True,  Predict:", bbox.is_intersect_line_ray(l5)
コード例 #25
0
ファイル: dataio.py プロジェクト: filipeabperes/pyphy-engine
 def _create_walls(self, xleft, yleft, thetas, wlens, fColor):
     theta1, theta2, theta3 = thetas
     wlen1, wlen2, wlen3 = wlens
     pt1 = gm.Point(xleft, yleft)
     dir1 = gm.theta2dir(theta1)
     pt2 = pt1 + (wlen1 * dir1)
     dir2 = gm.theta2dir(theta2)
     pt3 = pt2 + (wlen2 * dir2)
     dir3 = gm.theta2dir(theta3)
     pt4 = pt3 + (wlen3 * dir3)
     pts = [pt1, pt2, pt3, pt4]
     if self.verbose_ > 0:
         print 'Wall Points: %s, %s, %s, %s' % (pt1, pt2, pt3, pt4)
     walls = pm.create_cage(pts, wThick=self.wthick_, fColor=fColor)
     # get the lines within which the balls need to be added.
     self.pts = pts
     self.lines_ = []
     for w in walls:
         self.world_.add_object(w)
     for i in range(len(pts)):
         self.lines_.append(gm.Line(pts[i], pts[np.mod(i + 1, len(pts))]))
     return walls
コード例 #26
0
    def propagateDown(self):
        self.newState = []
        currentPlayer = self.state.players[self.player]

        for i in geometry.directions:
            if geometry.dot(currentPlayer.direction, i) != -1:

                tempState = copy.deepcopy(self.state)
                newPlayer = tempState.players[self.player]
                newPlayer.direction = i
                dead = False

                for j in range(1, newPlayer.speed + 1):
                    newPos = newPlayer.pos + newPlayer.direction * j
                    if (newPos.x < 0 or newPos.x > setup.gameWidth
                            or newPos.y < 0 or newPos.y > setup.height):
                        dead = True
                    else:
                        for r in range(setup.players):
                            for line in self.state.players[r].lines:
                                end = line.direction * line.length + line.start
                                if (geometry.colinear(newPos, line.start, end)
                                        and min(line.start.x, end.x) <=
                                        newPos.x <= max(line.start.x, end.x)
                                        and max(line.start.y, end.y) <=
                                        newPos.y <= max(line.start.y, end.y)):
                                    dead = True

                if (len(newPlayer.lines) == 0 or
                        newPlayer.lines[-1].direction != newPlayer.direction):
                    l = geometry.Line(newPlayer.pos, newPlayer.direction,
                                      newPlayer.speed)
                    newPlayer.lines.append(l)
                else:
                    newPlayer.lines[-1].length += newPlayer.speed
                newPlayer.pos += newPlayer.direction * newPlayer.speed
                self.newState.append((Node(self.depth + 1, self.maxDepth,
                                           tempState, self.player), dead))
コード例 #27
0
 def find_textline(self, image):
     image = image.copy()
     ratio = 4.0 / 8.0
     #ratio = 4.0/4.0
     for word in self.words:
         #dir(word)
         #word.angles
         points = []
         multiplier = 1
         for character in word.characters:
             #print "(",character.x,", ",character.y,")"
             #print "nn: ", character.nearestNeighbors
             points.append([character.x, character.y])
         points.sort(key=lambda x: x[0])
         #print("points:",points)
         w = max(points, key=lambda x: x[0])[0] - min(points,
                                                      key=lambda x: x[0])[0]
         #print("w:",w)
         h = max(points, key=lambda x: x[1])[1] - min(points,
                                                      key=lambda x: x[1])[1]
         #print(h)
         dx, dy, x0, y0 = cv2.fitLine(numpy.array(points),
                                      cv2.cv.CV_DIST_L2, 0, 0.01, 0.01)
         #print("dx:",dx,", dy:",dy,", x0:",x0,", y0:",y0)
         #start = (int(x0 - dx*w*ratio), int(y0 - dy*w*ratio))
         start = (int(min(points, key=lambda x: x[0])[0]),
                  int((dy / dx) *
                      (min(points, key=lambda x: x[0])[0] - x0) + y0))
         #end = (int(x0 + dx*w*ratio), int(y0 + dy*w*ratio))
         end = (int(max(points, key=lambda x: x[0])[0]),
                int((dy / dx) * (max(points, key=lambda x: x[0])[0] - x0) +
                    y0))
         #print(start,end)
         self.lines.append(g.Line([start, end]))
         cv2.line(image, start, end, (0, 255, 255), 2)
     return image
コード例 #28
0
def test_point_along_line():
    pt1 = gm.Point(0, 0)
    pt2 = gm.Point(1, 1)
    l = gm.Line(pt1, pt2)
    pt = l.get_point_along_line(pt2, 3)
    print pt
コード例 #29
0
 def create_line_instance(self):
     C1 = (1, 8)
     C2 = (8, 10)
     LINE = geometry.Line(C1, C2)
     return LINE
コード例 #30
0
    def getWords(self):

        words = []
        k = 5
        mode = 'horizontal'  # mode = ['default','horizontal','vertical']
        #EPS = 1e-2

        # find the average distance between nearest neighbours
        NNDistances = []
        NNHorizontalDistances = []
        NNVerticalDistances = []
        remove_counter = 0
        for character in self.characters:
            remove_counter = remove_counter + 1
            result = self.NNTree.query(
                character.toArray(), k=k
            )  # we only want nearest neighbour, but the first result will be the point matching itself.
            nearestNeighbourDistance = result[0]
            for i in xrange(1, k):
                #print("[%s] nearestNeighbourDistance: %s"%(remove_counter,result[0]))
                NNDistances.append(nearestNeighbourDistance[i])
        avgNNDistance = sum(NNDistances) / len(NNDistances)

        maxDistance = avgNNDistance * 3
        #maxDistance = avgNNDistance*20000
        for character in self.characters:
            #print ("Finding a a nn of ",character.x,character.y)
            queryResult = self.NNTree.query(character.coordinate, k=k)
            distances = queryResult[0]
            neighbours = queryResult[1]
            for i in range(1, k):
                if mode == 'horizontal':
                    ###################################
                    # Transitive Closure - Horizontal #
                    ###################################
                    #if(abs(self.characters[neighbours[i]].y-character.y) < avgNNDistance/2):
                    neighbour = self.characters[neighbours[i]]
                    line = g.Line([character.coordinate, neighbour.coordinate])
                    angle = line.calculateAngle(line.start, line.end)
                    if (
                            abs(angle.canonical) <= 0.261799
                            and distances[i] < maxDistance
                    ):  # 15(degree) = 0.261799(rad), 30(degree) = 0.523599(rad)
                        character.nearestNeighbours.append(neighbour)
                        NNHorizontalDistances.append(distances[i])
                        #print (i,"th nn!", "dist:", distances[i], " neighbor:(",neighbour.x,",",neighbour.y,")")
                    # Below is just for calculating the most common vertical distance purpose...
                    if (
                            1.309 <= abs(angle.canonical) <= 1.8326
                            and distances[i] < maxDistance
                    ):  # 75(degree)=1.309(rad), 105(degree)=1.8326(rad) 60(degree)=1.0472(rad), 90(degree)=1.5708(rad), 120(degree)=2.0944(rad)
                        NNVerticalDistances.append(distances[i])
                elif mode == 'vertical':  # This code might be deleted in future..?
                    ###################################
                    # Transitive Closure - Vertical   #
                    ###################################
                    #if(abs(self.characters[neighbours[i]].x-character.x) < avgNNDistance/2):
                    neighbour = self.characters[neighbours[i]]
                    line = g.Line([character.coordinate, neighbour.coordinate])
                    angle = line.calculateAngle(line.start, line.end)
                    if (
                            1.309 <= abs(angle.canonical) <= 1.8326
                    ):  # 75(degree)=1.309(rad), 105(degree)=1.8326(rad) 60(degree)=1.0472(rad), 90(degree)=1.5708(rad), 120(degree)=2.0944(rad)
                        character.nearestNeighbours.append(neighbour)
                        NNVerticalDistances.append(distances[i])


#                        print (i,"th nn!", "dist:", distances[i], " neighbor:(",neighbour.x,",",neighbour.y,") angle:",angle.canonical)
                else:
                    ###################################
                    # Transitive Closure - Default    #
                    ###################################
                    # Find nn in every direction within maxDistance
                    if distances[i] < maxDistance:
                        neighbour = self.characters[neighbours[i]]
                        character.nearestNeighbours.append(neighbour)

        num_bins = int(
            (numpy.max(NNDistances) - numpy.min(NNDistances) + 1) / 10)
        n, bins, patches = plt.hist(NNDistances,
                                    num_bins,
                                    facecolor='orange',
                                    alpha=0.5)
        plt.show()
        print("Total %d all NNs" % len(NNDistances))
        print("average NN distance: ", avgNNDistance)

        num_bins = int((numpy.max(NNHorizontalDistances) -
                        numpy.min(NNHorizontalDistances) + 1) / 10)
        n, bins, patches = plt.hist(NNHorizontalDistances,
                                    num_bins,
                                    facecolor='orange',
                                    alpha=0.5)
        plt.show()
        print("Total %d hor NNs" % len(NNHorizontalDistances))
        dist_peaks = []
        n_copy = n.copy()
        n_copy[::-1].sort()  # sort in reverse way
        for i in xrange(num_bins):
            _max_idx = numpy.where(n == n_copy[i])  # Find peak
            for j in xrange(len(_max_idx[0])):
                dist_peaks.append(int(bins[_max_idx[0][j]]))
        print("Distance peaks: %s" % dist_peaks)
        avgHorizontalNNDistance = sum(NNHorizontalDistances) / (
            len(NNHorizontalDistances))
        print("average NN horizontal distance: %.2f\n" %
              avgHorizontalNNDistance)

        num_bins = int((numpy.max(NNVerticalDistances) -
                        numpy.min(NNVerticalDistances) + 1) / 10)
        n, bins, patches = plt.hist(NNVerticalDistances,
                                    num_bins,
                                    facecolor='orange',
                                    alpha=0.5)
        plt.show()
        print("Total %d ver NNs" % len(NNVerticalDistances))
        dist_peaks = []
        n_copy = n.copy()
        n_copy[::-1].sort()  # sort in reverse way
        for i in xrange(num_bins):
            _max_idx = numpy.where(n == n_copy[i])  # Find peak
            for j in xrange(len(_max_idx[0])):
                dist_peaks.append(int(bins[_max_idx[0][j]]))
        print("Distance peaks: %s" % dist_peaks)
        avgVerticalNNDistance = sum(NNVerticalDistances) / (
            len(NNVerticalDistances))
        print("average NN vertical distance: %.2f\n" % avgVerticalNNDistance)

        self.characters = sorted(self.characters,
                                 key=lambda character: (character.x))
        for character in self.characters:
            #print ("Deciding wordness of (",character.x,character.y,")")
            if character.parentWord == None:
                #print ("(",character.x,character.y,") is a parent!")
                if len(character.nearestNeighbours) >= 0:
                    #print ("(",character.x,character.y,") is a word!!!!")
                    word = Word([character])
                    word.findTuples()
                    words.append(word)
        '''
        print "Total ", len(words), " words are found."
        for idx, word in enumerate(words):
            print "[",idx,"] word:"
            for idx_char, character in enumerate(word.characters):
                print "**[", idx_char, "] char info.. ", "(",character.x,",",character.y,")"
        '''
        return words