예제 #1
0
    def get_diameter(self, point1, point2, mask, image):
        h, w = mask.shape
        line = Line()
        line.init_by_point(point1, point2)
        line.judge_axis(point1, point2)

        start_point = (point1 + point2) / 2.0
        end_point_plus = start_point.copy()
        end_point_minus = start_point.copy()

        for i in range(1, self.max_iter):
            tmp_point = start_point.copy()
            cur_steps = i * self.step
            next_point_puls = line.get_next_point(cur_steps, tmp_point)
            if self.show_point:
                cv2.circle(image,
                           (int(next_point_puls[0]), int(next_point_puls[1])),
                           5, (0, 0, 255), 4)
                cv2.imshow("COCO detections", image)
                cv2.waitKey(0)
            if next_point_puls[0]<w and next_point_puls[1]<h \
                and next_point_puls[0]>=0 and next_point_puls[1]>=0:
                value = mask[int(next_point_puls[1])][int(next_point_puls[0])]
                if value == 0:
                    end_point_plus = line.get_next_point((i - 1) * self.step,
                                                         tmp_point)
                    break
            else:
                end_point_plus[0] = min(
                    next_point_puls[0],
                    w) if next_point_puls[0] >= 0 else end_point_plus[0]
                end_point_plus[1] = min(
                    next_point_puls[1],
                    h) if next_point_puls[1] >= 0 else end_point_plus[1]
                break

        for i in range(1, self.max_iter):
            tmp_point = start_point.copy()
            cur_steps = -i * self.step
            next_point_minus = line.get_next_point(cur_steps, tmp_point)
            if self.show_point:
                cv2.circle(
                    image,
                    (int(next_point_minus[0]), int(next_point_minus[1])), 5,
                    (0, 255, 0), 4)
                cv2.imshow("COCO detections", image)
                cv2.waitKey(0)
            if next_point_minus[0]<w and next_point_minus[1]<h \
                and next_point_minus[0]>=0 and next_point_minus[1]>=0:
                value = mask[int(next_point_minus[1])][int(
                    next_point_minus[0])]
                if value == 0:
                    end_point_minus = line.get_next_point(
                        -(i - 1) * self.step, tmp_point)
                    break
            else:
                end_point_minus[0] = max(
                    next_point_minus[0],
                    0) if next_point_minus[0] < w else end_point_minus[0]
                end_point_minus[1] = max(
                    next_point_minus[1],
                    0) if next_point_minus[1] < h else end_point_minus[1]
                break

        dist_plus = self.get_distance(start_point, end_point_plus)
        dist_minus = self.get_distance(start_point, end_point_minus)
        mid = (int(start_point[0]), int(start_point[1]))
        if dist_plus <= dist_minus:
            res = (int(end_point_minus[0]), int(end_point_minus[1]))
            dist = dist_minus
        else:
            res = (int(end_point_plus[0]), int(end_point_plus[1]))
            dist = dist_plus

        return dist, mid, res
예제 #2
0
    def process_frame(self, frame):
        """
        Process a video frame
        :param frame:
        :return: The processed frame with lane and info overlay
        """
        frame_copy = np.copy(frame)

        frame = get_thresholded_binary_image(frame)
        frame = perspective_transform(frame)

        left_detected = False
        right_detected = False
        left_x = []
        left_y = []
        right_x = []
        right_y = []

        if self.left_line and self.right_line:
            left_x, left_y = self.get_windows(frame,
                                              self.left_line.best_fit_poly)
            right_x, right_y = self.get_windows(frame,
                                                self.right_line.best_fit_poly)

            left_detected, right_detected = self.compare_lines(
                left_x, left_y, right_x, right_y)

        if not left_detected:
            left_x, left_y = self.histogram_lane_detection(
                frame,
                self.lane_segments, (self.image_offset, frame.shape[1] // 2),
                h_window=7)
        if not right_detected:
            right_x, right_y = self.histogram_lane_detection(
                frame,
                self.lane_segments,
                (frame.shape[1] // 2, frame.shape[1] - self.image_offset),
                h_window=7)

        if not left_detected or not right_detected:
            left_detected, right_detected = self.compare_lines(
                left_x, left_y, right_x, right_y)

        # Updated left lane information.
        if left_detected:
            if self.left_line:
                self.left_line.update(y=left_x, x=left_y)
            else:
                self.left_line = Line(self.frames, left_y, left_x)

        # Updated right lane information.
        if right_detected:
            # switch x and y since lines are almost vertical
            if self.right_line:
                self.right_line.update(y=right_x, x=right_y)
            else:
                self.right_line = Line(self.frames, right_y, right_x)

        if self.left_line and self.right_line:
            self.dists.append(
                self.left_line.get_best_fit_distance(self.right_line))
            self.lane = (self.left_line.best_fit_poly +
                         self.right_line.best_fit_poly) / 2
            self.curvature = Line.calc_curvature(self.lane)
            self.offset = self.get_offset(frame)

            self.draw_lane_overlay(frame_copy)
            self.add_text_overlay(frame_copy)

        cv2.imshow('lanes', frame_copy)
        cv2.waitKey(1)
        return frame_copy
예제 #3
0
def followRow(drone, desiredHeight=1.5, timeout=10.0):
    maxControlGap = 0.0
    maxVideoDelay = 0.0
    desiredSpeed = MAX_ALLOWED_SPEED
    startTime = drone.time
    sx, sy, sz, sa = 0, 0, 0, 0
    lastUpdate = None
    refLine = None
    while drone.time < startTime + timeout:
        altitude = desiredHeight
        if drone.altitudeData != None:
            altVision = drone.altitudeData[0] / 1000.0
            altSonar = drone.altitudeData[3] / 1000.0
            altitude = (altSonar + altVision) / 2.0
            # TODO selection based on history? panic when min/max too far??
            if abs(altSonar - altVision) > 0.5:
                #        print altSonar, altVision
                altitude = max(altSonar,
                               altVision)  # sonar is 0.0 sometimes (no ECHO)
        sz = max(-0.2, min(0.2, desiredHeight - altitude))
        if altitude > 2.5:
            # wind and "out of control"
            sz = max(-0.5, min(0.5, desiredHeight - altitude))

        if drone.lastImageResult:
            lastUpdate = drone.time
            assert len(drone.lastImageResult) == 2 and len(
                drone.lastImageResult[0]) == 2, drone.lastImageResult
            (frameNumber, timestamp), rowTopBottom = drone.lastImageResult
            viewlog.dumpVideoFrame(frameNumber, timestamp)
            # keep history small
            videoTime = correctTimePeriod(timestamp / 1000., ref=drone.time)
            videoDelay = drone.time - videoTime
            if videoDelay > 1.0:
                print "!DANGER! - video delay", videoDelay
            maxVideoDelay = max(videoDelay, maxVideoDelay)
            toDel = 0
            for oldTime, oldPose, oldAngles in drone.poseHistory:
                toDel += 1
                if oldTime >= videoTime:
                    break
            drone.poseHistory = drone.poseHistory[:toDel]
            tiltCompensation = Pose(desiredHeight * oldAngles[0],
                                    desiredHeight * oldAngles[1],
                                    0)  # TODO real height?
            validRow = evalRowData(rowTopBottom)
            print "FRAME", frameNumber / 15, "[%.1f %.1f]" % (math.degrees(
                oldAngles[0]), math.degrees(oldAngles[1])), validRow
            if validRow:
                sp = groundPose(*rowTopBottom,
                                scale=ROW_WIDTH /
                                ((validRow[0] + validRow[1]) / 2.0))
                sPose = Pose(*oldPose).add(tiltCompensation).add(sp)
                refLine = Line((sPose.x, sPose.y),
                               (sPose.x + math.cos(sPose.heading),
                                sPose.y + math.sin(sPose.heading)))

        errY, errA = 0.0, 0.0
        if refLine:
            errY = refLine.signedDistance(drone.coord)
            errA = normalizeAnglePIPI(drone.heading - refLine.angle)

        sx = max(0, min(drone.speed, desiredSpeed - drone.vx))
        sy = max(-0.2, min(0.2, -errY - drone.vy)) / 2.0
        sa = max(-0.1, min(0.1, -errA / 2.0)) * 1.35 * (desiredSpeed / 0.4)
        prevTime = drone.time
        drone.moveXYZA(sx, sy, sz, sa)
        drone.poseHistory.append(
            (drone.time, (drone.coord[0], drone.coord[1], drone.heading),
             (drone.angleFB, drone.angleLR)))
        maxControlGap = max(drone.time - prevTime, maxControlGap)
    return maxControlGap
예제 #4
0
                                    np.average(l_radius,0,weights[-len(l_params):]),
                                    np.average(r_radius,0,weights[-len(l_params):]))
        return annotated_image
    return process_image




if __name__ == '__main__':   
    
    # Load camera data
    mtx, dist = load_mtx_dist()
    M, Minv = load_M_Minv()
    
    # Initialize track objects to help evaluate good or bad frames
    left_line = Line()
    right_line = Line() 
    
        
    # Test on image first
    '''
    import glob
    # Make a list of images
    images = glob.glob('test_images/test*.jpg')
    images.sort()       

    img = cv2.imread(images[4])
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    undistorted = cv2.undistort(img, mtx, dist, None, mtx)
    binary_warped, binary_threshold = thresholding(undistorted, M)
    left_fit, right_fit, left_curverad, right_curverad, _ = sliding_window(binary_warped)
예제 #5
0
from vector import Vector
from line import Line

print('1st Pair....')
n1 = Vector((4.046, 2.836))
k1 = 1.21
n2 = Vector((10.115, 7.09))
k2 = 3.025
ell1 = Line(n1, k1)
ell2 = Line(n2, k2)
print('Calculate Intersection:', ell1.intersection_with(ell2))
print()
print('2nd Pair....')
n1 = Vector((7.204, 3.182))
k1 = 8.68
n2 = Vector((8.172, 4.114))
k2 = 9.883
ell1 = Line(n1, k1)
ell2 = Line(n2, k2)
print('Calculate Intersection:', ell1.intersection_with(ell2))
print()
print('3rd Pair....')
n1 = Vector((1.182, 5.562))
k1 = 6.744
n2 = Vector((1.773, 8.343))
k2 = 9.525
ell1 = Line(n1, k1)
ell2 = Line(n2, k2)
print('Calculate Intersection:', ell1.intersection_with(ell2))
예제 #6
0
        pub.publish(lane_detector.turn_dir)

        rate.sleep()


if __name__ == "__main__":

    draw = False

    src = np.float32([[50, 300], [590, 300], [640, 480], [0, 480]])
    dst = np.float32([[0, 0], [640, 0], [640, 480], [0, 480]])

    M, Minv = perspective_tf(src, dst)

    # init lane lines obj and lane detection obj
    left_line = Line(5)
    right_line = Line(5)
    lane_detector = LaneDetection(M, Minv, left_line, right_line)

    # init node, cam sub and lane pub
    rospack = rospkg.RosPack()
    rospy.init_node('perception_lanes_node', anonymous=False)
    rate = rospy.Rate(10)  # 10hz

    rospy.Subscriber('sensors/camera_topic', Image, callback)
    pub = rospy.Publisher('perception/lanes_topic', String)

    rospy.loginfo("Lane Detection started..")
    talker()

    # closing all open windows
예제 #7
0
    def tangent_lines(self, p):
        """Tangent lines between `p` and the ellipse.

        If `p` is on the ellipse, returns the tangent line through point `p`.
        Otherwise, returns the tangent line(s) from `p` to the ellipse, or
        None if no tangent line is possible (e.g., `p` inside ellipse).

        Parameters
        ==========

        p : Point

        Returns
        =======

        tangent_lines : list with 1 or 2 Lines

        Raises
        ======

        NotImplementedError
            Can only find tangent lines for a point, `p`, on the ellipse.

        See Also
        ========

        sympy.geometry.point.Point, sympy.geometry.line.Line

        Examples
        ========

        >>> from sympy import Point, Ellipse
        >>> e1 = Ellipse(Point(0, 0), 3, 2)
        >>> e1.tangent_lines(Point(3, 0))
        [Line(Point(3, 0), Point(3, -12))]

        >>> # This will plot an ellipse together with a tangent line.
        >>> from sympy import Point, Ellipse, Plot
        >>> e = Ellipse(Point(0,0), 3, 2)
        >>> t = e.tangent_lines(e.random_point()) # doctest: +SKIP
        >>> p = Plot() # doctest: +SKIP
        >>> p[0] = e # doctest: +SKIP
        >>> p[1] = t # doctest: +SKIP

        """
        if self.encloses_point(p):
            return []

        if p in self:
            rise = (self.vradius**2) * (self.center[0] - p[0])
            run = (self.hradius**2) * (p[1] - self.center[1])
            p2 = Point(simplify(p[0] + run), simplify(p[1] + rise))
            return [Line(p, p2)]
        else:
            if len(self.foci) == 2:
                f1, f2 = self.foci
                maj = self.hradius
                test = (2 * maj - Point.distance(f1, p) -
                        Point.distance(f2, p))
            else:
                test = self.radius - Point.distance(self.center, p)
            if test.is_number and test.is_positive:
                return []
            # else p is outside the ellipse or we can't tell. In case of the
            # latter, the solutions returned will only be valid if
            # the point is not inside the ellipse; if it is, nan will result.
            x, y = Dummy('x'), Dummy('y')
            eq = self.equation(x, y)
            dydx = idiff(eq, y, x)
            slope = Line(p, Point(x, y)).slope
            tangent_points = solve([slope - dydx, eq], [x, y])

            # handle horizontal and vertical tangent lines
            if len(tangent_points) == 1:
                assert tangent_points[0][0] == p[0] or tangent_points[0][
                    1] == p[1]
                return [
                    Line(p, Point(p[0] + 1, p[1])),
                    Line(p, Point(p[0], p[1] + 1))
                ]

            # others
            return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
예제 #8
0
 def setUp(self):
     self.l = Line(Point(100, 110),
                   Point(220, 230),
                   lineColor="Pink",
                   lineWidth=1,
                   fillColor='Yellow')
예제 #9
0
win_w = 500
win_h = 500
win = pygame.display.set_mode((win_w, win_h))
pygame.display.set_caption("Wernk-Pong")

controller = Controller()
paddle_1 = Paddle(win_w, win_h, 10, "assets/wernkepaddle3.png", 10,
                  controller.up, controller.down)
paddle_2 = Paddle(win_w, win_h, win_w - 30, "assets/beckpaddle3.png", 10,
                  controller.up, controller.down)
scoreboard = Scoreboard(win_w, win_h)
ball = Ball(paddle_1, paddle_2, scoreboard, win_w, win_h, 30,
            "assets/wernkeball2.png",
            "assets/beckball.png")  # 15 seems to fast for the player
line = Line(win_w, win_h)

sprites = pygame.sprite.Group([paddle_1, paddle_2, scoreboard, ball, line])

run = True

while run:
    pygame.time.delay(5)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    win.fill((0, 0, 0))

    controller.update()
예제 #10
0
import time
from line import Line

axiomatic_line = Line([0, -200], [0, 200])

queue = [axiomatic_line]

while True:
    line = queue.pop(0)
    line.draw()
    queue.extend(line.get_children())
예제 #11
0
from turtle import Screen
from line import Line
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor('black')
screen.title('Pong')
screen.tracer(0)
line = Line()
line.move_turtle()

right_paddle = Paddle()
left_paddle = Paddle()
ball = Ball()
scoreboard = Scoreboard()

ball_speed = 0.1

right_paddle.set_position((350, 0))
left_paddle.set_position((-350, 0))

screen.listen()
screen.onkeypress(right_paddle.up, "Up")
screen.onkeypress(right_paddle.down, "Down")
screen.onkeypress(left_paddle.up, "w")
screen.onkeypress(left_paddle.down, "s")
예제 #12
0
def mapRaw():
    '''These lines are not pre-calculated.  BinaryTree will try to perform the necessary calculations.'''
    color1 = (222, 0, 0)
    color2 = (80, 0, 0)
    walls = [
        Line(600, 0, 0, 0, color=color1),
        Line(600, 400, 600, 0, color=color2),
        Line(0, 400, 600, 400, color=color1),
        Line(0, 0, 0, 400, color=color2),
        Line(0, 160, 40, 160, color=color2),
        Line(200, 120, 120, 120, color=color1),
        Line(200, 0, 200, 120, color=color1),
        Line(320, 0, 320, 120, color=color2),
        Line(320, 120, 400, 120, color=color1),
        Line(400, 120, 400, 80, color=color2),
        Line(400, 80, 520, 80, color=color1)
    ]
    #Line(440,280,440,120, color=color2)]
    #Line(520,160,360,80, color=(0,0,111))]

    return walls
예제 #13
0
def mapPrecooked():
    '''These lines are pre-calculated.  Can only be used with the manual method in the BinaryTree class.'''
    color1 = (222, 0, 0)
    color2 = (80, 0, 0)
    walls = [
        Line(160, 120, 240, 120, color=color1),
        Line(240, 120, 240, 200, color=color2),
        Line(240, 200, 160, 200, color=color1),
        Line(160, 200, 160, 120, color=color2),
        Line(560, 40, 40, 40, color=color1),
        Line(560, 120, 560, 40, color=color2),
        Line(560, 360, 560, 120, color=color2),
        Line(240, 360, 560, 360, color=color1),
        Line(40, 360, 240, 360, color=color1),
        Line(40, 200, 40, 360, color=color2),
        Line(40, 120, 40, 200, color=color2),
        Line(40, 40, 40, 120, color=color2)
    ]
    return walls
예제 #14
0
파일: navpat.py 프로젝트: myrobot2017/osgar
def run_there_and_back_SCHOOL(robot, speed):
    follow_line(robot, Line((0, 2.3), (14.0, 2.3)), speed=speed, timeout=60)
    turn_back(robot, speed)
    follow_line(robot, Line((14.0, 2.3), (0, 2.3)), speed=speed, timeout=60)
    turn_back(robot, speed)
예제 #15
0
파일: rr_drone.py 프로젝트: ASTARCHEN/heidi
def processFrame(frame, debug=False):
    global g_mser
    result = []
    allHulls = []
    selectedHulls = []
    #  for stripOffset in [ -100, 0, +100, +200 ]:
    for stripOffset in [+100]:
        midY = frame.shape[0] / 2 + stripOffset
        stripWidth = 120
        if g_mser == None:
            g_mser = cv2.MSER(_delta=10,
                              _min_area=100,
                              _max_area=stripWidth * 1000)
        imgStrip = frame[midY:midY + stripWidth, 0:frame.shape[1]]
        b, g, r = cv2.split(imgStrip)
        gray = b
        contours = g_mser.detect(gray, None)
        hulls = []
        selected = None
        for cnt in contours:
            (x1, y1), (x2, y2) = np.amin(cnt, axis=0), np.amax(cnt, axis=0)
            if y1 == 0 and y2 == stripWidth - 1:  # i.e. whole strip
                if x1 > 0 and x2 < frame.shape[1] - 1:
                    hull = cv2.convexHull(cnt.reshape(-1, 1, 2))
                    for h in hull:
                        h[0][1] += midY
                    hulls.append(hull)
                    # select the one with the smallest area
                    if len(cnt) >= MIN_ROAD_AREA:
                        rect = rect2BLBRTRTL([(a[0][0], a[0][1])
                                              for a in approx4pts(hull)])
                        if rect != None:
                            bl, br, tr, tl = rect
                            tmpInt = Line(bl, tl).intersect(Line(br, tr))
                            if tmpInt != None:
                                p = tuple([int(x) for x in tmpInt])
                                if br[0] - bl[0] > tr[0] - tl[0] and p[
                                        1] > 0 and p[1] < frame.shape[0]:
                                    # make sure that direction is forward and in the image
                                    result.append(rect)
#                if selected == None or selected[0] > len(cnt):
#                  selected = len(cnt), hull, rect
#    if selected:
#      result.append( selected[2] )
        if debug:
            allHulls.extend(hulls)
            if selected != None:
                selectedHulls.append(selected[1])

    if debug:
        cv2.polylines(frame, allHulls, 2, (0, 255, 0), 2)
        if len(selectedHulls) > 0:
            cv2.polylines(frame, selectedHulls, 2, (0, 0, 0), 2)


#    for trapezoid in result:
#      cv2.drawContours( frame,[np.int0(trapezoid)],0,(255,0,0),2)
#    for trapezoid in result:
#      bl,br,tr,tl = trapezoid
#      p = tuple([int(x) for x in Line(bl,tl).intersect( Line(br,tr) )])
#      cv2.circle( frame, p, 10, (0,255,128), 3 )
#      navLine = trapezoid2line( trapezoid )
#      if navLine:
#        drawArrow(frame, navLine[0], navLine[1], (0,0,255), 4)
        cv2.imshow('image', frame)
        saveIndexedImage(frame)
    return result
예제 #16
0
from ball import Ball
from score import Scoreboard

WIDTH = 1000
HEIGHT = 600
POSITIONS = [(-470, 0), (470, 0)]

screen = Screen()
screen.setup(width=WIDTH, height=HEIGHT)
screen.bgcolor("black")
screen.title("PING PONG")
screen.tracer(0)

h = 0
while h < HEIGHT / 2:
    Line((0, h))
    Line((0, -h))
    h += 30

r_paddle = Paddle((470, 0))
l_paddle = Paddle((-470, 0))

my_ball = Ball()
my_score = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "a")
예제 #17
0
from point import Point

def app_init():
    root = tk.Tk()
    root.geometry("500x500")
    canvas =  tk.Canvas(root, height=500, width=500)
    canvas.place(x=0, y=0)
    return root, canvas

# メイン
r,c = app_init()
s1 = Square(c, Point(c, 100,100), Point(c, 200, 200))
s1.draw()
s2 = Square(c, Point(c, 10,10), Point(c, 50, 50))
s2.draw()
l1 = Line(c, Point(c, 50, 50), Point(c, 300, 300), color='red')
l1.draw()
# クラスメソッドを呼ぶ
Square.print_num()
Line.print_num()
# 親クラスのスタティックメソッドを呼ぶ
Square.all_rights()
# Tkボタンとハンドラー
def gmove():
    # セッターメソッド
    s1.foreground = 'blue'
    # 追加メソッド呼び出し
    s1.move(Point(c,10, 10))
    l1.move(Point(c,10,10))
    print(s1.foreground)
btn = tk.Button(r, text="Move", command=gmove)
예제 #18
0
        sys.exit(1)
    return s


#read from file

f = open(args.file, "r")
assoc = int(args.assoc)
cacheSize = parse_size(args.size)
cacheList = collections.deque([], maxlen=(cacheSize // cache_line_size))

if assoc != 0:
    cache = Cache(cacheSize, cache_line_size, assoc)
elif assoc == 0 or assoc > (cacheSize // cache_line_size):
    for i in range(cacheSize // cache_line_size):
        cacheList.append(Line())

total = 0
i = 0
blockSize = 0
misses = 0
hits = 0
hmFlag = 0
for line in f:
    sepLine = line.split()
    if len(sepLine) != 3: continue
    sepLine[0] = sepLine[0][:-1]
    sepLine[2] = sepLine[2].strip("\n")
    if assoc != 0 and assoc < (cacheSize // cache_line_size):
        cache.setTag(sepLine[2])
    newLine = Line()
예제 #19
0
def topology(objects,
             stitch_poles=True,
             verbose=True,
             e_max=0,
             coordinate_system=None,
             object_name='name',
             id_key='id',
             quantization_factor=1e4,
             property_transform=None):

    id_ = lambda d: d[id_key]

    if property_transform is None:

        def property_transform(outprop, key, inprop):
            outprop[key] = inprop
            return True

    stitch_poles = True
    verbose = False
    e_max = 0
    object_name = 'name'
    if coordinate_system:
        system = systems[coordinate_system]

    if objects.has_key('type') and objects['type'] == 'FeatureCollection':
        objects = {object_name: objects}
    ln = Line(quantization_factor)

    [x0, x1, y0, y1] = bound(objects)

    oversize = x0 < -180 - E or x1 > 180 + E or y0 < -90 - E or y1 > 90 + E
    if coordinate_system is None:
        if oversize:
            system = systems["cartesian"]
        else:
            system = systems["spherical"]
        coordinate_system = system.name

    if coordinate_system == 'spherical':
        if oversize:
            raise Exception(u"spherical coordinates outside of [±180°, ±90°]")
        if stitch_poles:
            stitch(objects)
            [x0, x1, y0, y1] = bound(objects)
        if x0 < -180 + E:
            x0 = -180
        if x1 > 180 - E:
            x1 = 180
        if y0 < -90 + E:
            y0 = -90
        if y1 > 90 - E:
            y1 = 90

    if is_infinit(x0):
        x0 = 0
    if is_infinit(x1):
        x1 = 0

    if is_infinit(y0):
        y0 = 0
    if is_infinit(y1):
        y1 = 0

    logging.debug("{}".format([x0, y0, x1, y1]))

    kx, ky = make_ks(quantization_factor, x0, x1, y0, y1)
    if not quantization_factor:
        quantization_factor = x1 + 1
        x0 = y0 = 0

    class FindEmax(types):
        def __init__(self, obj):
            self.emax = 0
            self.obj = obj

        def point(self, point):
            x1 = point[0]
            y1 = point[1]
            x = ((x1 - x0) * kx)
            y = ((y1 - y0) * ky)
            ee = system['distance'](x1, y1, x / kx + x0, y / ky + y0)
            if ee > self.emax:
                self.emax = ee
            point[0] = int(x)
            point[1] = int(y)

    finde = FindEmax(objects)
    e_max = finde.emax
    clock(objects, system.ring_area)

    class findCoincidences(types):
        def line(self, line):
            for point in line:
                lines = ln.arcs.coincidenceLines(point)
                if not line in lines:
                    lines.append(line)

    fcInst = findCoincidences(objects)
    polygon = lambda poly: map(ln.lineClosed, poly)

    #Convert features to geometries, and stitch together arcs.
    class makeTopo(types):
        def Feature(self, feature):
            geometry = feature["geometry"]
            if feature['geometry'] == None:
                geometry = {}
            if feature.has_key('id'):
                geometry['id'] = feature['id']
            if feature.has_key('properties'):
                geometry['properties'] = feature['properties']
            return self.geometry(geometry)

        def FeatureCollection(self, collection):
            collection['type'] = "GeometryCollection"
            collection['geometries'] = map(self.Feature,
                                           collection['features'])
            del collection['features']
            return collection

        def GeometryCollection(self, collection):
            collection['geometries'] = map(self.geometry,
                                           collection['geometries'])

        def MultiPolygon(self, multiPolygon):
            multiPolygon['arcs'] = map(polygon, multiPolygon['coordinates'])

        def Polygon(self, polygon):
            polygon['arcs'] = map(ln.lineClosed, polygon['coordinates'])

        def MultiLineString(self, multiLineString):
            multiLineString['arcs'] = map(ln.lineOpen,
                                          multiLineString['coordinates'])

        def LineString(self, lineString):
            lineString['arcs'] = ln.lineOpen(lineString['coordinates'])

        def geometry(self, geometry):
            if geometry is None:
                geometry = {}
            else:
                types.geometry(self, geometry)
            geometry['id'] = id_(geometry)
            if geometry['id'] is None:
                del geometry['id']
            properties0 = geometry['properties']
            if properties0:
                properties1 = {}
                del geometry['properties']
                for key0 in properties0:
                    if property_transform(properties1, key0,
                                          properties0[key0]):
                        geometry['properties'] = properties1
            if 'arcs' in geometry:
                del geometry['coordinates']
            return geometry

    makeTopoInst = makeTopo(objects)
    return {
        'type': "Topology",
        'transform': {
            'scale': [1.0 / kx, 1.0 / ky],
            'translate': [x0, y0]
        },
        'objects': makeTopoInst.outObj,
        'arcs': ln.getArcs()
    }
예제 #20
0
    def testRotate1(self):
        L1 = Line((20, 30), (20, 10))
        L2 = L1.rotate(33)

        self.assertAlmostEqual(L1.angle(), 270)
        self.assertAlmostEqual(L2.angle(), 303)
예제 #21
0
def topology(objects, stitchPoles=True, quantization=1e4, id_key='id',
             property_transform=property_transform, system=False,
             simplify=False):
    ln = Line(quantization)
    id_func = lambda x: x[id_key]
    if simplify:
        objects = simplify_object(objects, simplify)
    [x0, x1, y0, y1] = bound(objects)

    oversize = x0 < -180 - E or x1 > 180 + E or y0 < -90 - E or y1 > 90 + E
    if not system:
        if oversize:
            system = systems["cartesian"]
        else:
            system = systems["spherical"]
    if system.name == 'spherical':
        if oversize:
            raise Exception(u"spherical coordinates outside of [±180°, ±90°]")
        if stitchPoles:
            stitch(objects)
            [x0, x1, y0, y1] = bound(objects)
        if x0 < -180 + E:
            x0 = -180
        if x1 > 180 - E:
            x1 = 180
        if y0 < -90 + E:
            y0 = -90
        if y1 > 90 - E:
            y1 = 90
    if is_infinit(x0):
        x0 = 0
    if is_infinit(x1):
        x1 = 0

    if is_infinit(y0):
        y0 = 0
    if is_infinit(y1):
        y1 = 0
    [kx, ky] = make_ks(quantization, x0, x1, y0, y1)
    if not quantization:
        quantization = x1 + 1
        x0 = y0 = 0

    class findEmax(Types):

        def __init__(self, obj):
            self.emax = 0
            self.obj(obj)

        def point(self, point):
            x1 = point[0]
            y1 = point[1]
            x = ((x1 - x0) * kx)
            y = ((y1 - y0) * ky)
            ee = system.distance(x1, y1, x / kx + x0, y / ky + y0)
            if ee > self.emax:
                self.emax = ee
            point[0] = int(x)
            point[1] = int(y)
    finde = findEmax(objects)
    emax = finde.emax
    clock(objects, system.ring_area)

    class find_coincidences(Types):

        def line(self, line):
            for point in line:
                lines = ln.arcs.coincidence_lines(point)
                if not line in lines:
                    lines.append(line)
    fcInst = find_coincidences(objects)
    polygon = lambda poly: map(ln.line_closed, poly)
    #Convert features to geometries, and stitch together arcs.

    class make_topo(Types):

        def Feature(self, feature):
            geometry = feature["geometry"]
            if feature['geometry'] is None:
                geometry = {}
            if 'id' in feature:
                geometry['id'] = feature['id']
            if 'properties' in feature:
                geometry['properties'] = feature['properties']
            return self.geometry(geometry)

        def FeatureCollection(self, collection):
            collection['type'] = "GeometryCollection"
            collection['geometries'] = map(
                self.Feature,
                collection['features']
            )
            del collection['features']
            return collection

        def GeometryCollection(self, collection):
            collection['geometries'] = map(
                self.geometry,
                collection['geometries']
            )

        def MultiPolygon(self, multiPolygon):
            multiPolygon['arcs'] = map(polygon, multiPolygon['coordinates'])

        def Polygon(self, polygon):
            polygon['arcs'] = map(ln.line_closed, polygon['coordinates'])

        def MultiLineString(self, multiLineString):
            multiLineString['arcs'] = map(
                ln.line_open,
                multiLineString['coordinates']
            )

        def LineString(self, lineString):
            lineString['arcs'] = ln.line_open(lineString['coordinates'])

        def geometry(self, geometry):
            if geometry is None:
                geometry = {}
            else:
                Types.geometry(self, geometry)
            geometry['id'] = id_func(geometry)
            if geometry['id'] is None:
                del geometry['id']
            properties0 = geometry['properties']
            if properties0:
                properties1 = {}
                del geometry['properties']
                for key0 in properties0:
                    transformed = property_transform(
                        properties1,
                        key0,
                        properties0[key0]
                    )
                    if transformed:
                        geometry['properties'] = properties1
            if 'arcs' in geometry:
                del geometry['coordinates']
            return geometry
    make_topo_inst = make_topo(objects)
    return {
        'type': "Topology",
        'bbox': [x0, y0, x1, y1],
        'transform': {
            'scale': [1.0 / kx, 1.0 / ky],
            'translate': [x0, y0]
        },
        'objects': make_topo_inst.outObj,
        'arcs': ln.get_arcs()
    }
예제 #22
0
    def testRotate2(self):
        L1 = Line((20, 30), (0, 10))
        L2 = L1.rotate(-226)

        self.assertAlmostEqual(L1.angle(), 225)
        self.assertAlmostEqual(L2.angle(), 359)
예제 #23
0
def transpose(field):
    """Transposes given square matrix"""

    return [Line([line.get_field(i) for line in field]) for i in range(size)]
예제 #24
0
    def testLength(self):
        p1xy = (10, 5)
        p2xy = (13, 9)

        line = Line(p1xy, p2xy)
        self.assertAlmostEqual(line.length(), 5)
예제 #25
0
import tkinter as tk
from square import Square
from line import Line
from point import Point


def app_init():
    root = tk.Tk()
    root.geometry("500x500")
    canvas = tk.Canvas(root, height=500, width=500)
    canvas.place(x=0, y=0)
    return root, canvas


# メイン
r, c = app_init()
s1 = Square(c, "Square1", Point(c, 100, 100), Point(c, 200, 200), 'black')
s1.draw()
l1 = Line(c, "Line1", Point(c, 50, 50), Point(c, 300, 300), 'red')
l1.draw()
r.mainloop()
예제 #26
0
 def update_status_line(self, text):
     """Update status line with given text."""
     text = text.ljust(self.mcols)
     _line = Line(0, text, self.screen, [curses.A_REVERSE, None])
     _line.print()
     self.screen.refresh()
예제 #27
0
    def __init__(self, planet):
        Panel.__init__(self, (5,5), planet)
        self.planet = planet
        
        owner = "Neutral"
        color = PICO_YELLOW
        is_mine = False
        if planet.owning_civ:
            color = planet.owning_civ.color
            if planet.owning_civ.is_enemy:
                owner = "Enemy"
            else:
                owner = "Your"
                is_mine = True

        self.tab = {'text':'%s Planet' % owner, 'color':color, 'icon':'assets/i-planet.png'}
        self.add(Text("Resources", "small", (0,0), PICO_WHITE, False), V2(0,0))
        
        y = 15
        chart_data = {}
        for r in RESOURCES:
            pr = getattr(planet.resources, r)
            if pr:
                self.add(SimpleSprite((0,0), 'assets/i-%s.png' % r), V2(0,y))
                self.add(Text(r.title(), "small", (0,0), PICO_WHITE, False), V2(15,y+2))
                self.add(Text("%s%%" % pr, "small", (0,0), PICO_WHITE, False), V2(40,y+2))
                y += 15
                chart_data[RESOURCE_COLORS[r]] = pr
      
        self.add(PieChart((0,0), chart_data), V2(70, 10))

        y = max(y + 7, 41)
        self.add(Line(V2(0,0), V2(96, 0), PICO_WHITE),V2(0, y))
        y += 5

        self.add(SimpleSprite((0,0), 'assets/i-pop.png'), V2(34,y))
        color = PICO_WHITE
        if planet.population == 0 or planet.population >= planet.get_max_pop():
            color = PICO_YELLOW
        self.add(Text("%d/%d" %(planet.population, planet.get_max_pop()), "small", (0,0), color, False), V2(47,y+1))

        if planet.ships and is_mine:
            y += 14
            self.add(Line(V2(0,0), V2(96, 0), PICO_WHITE),V2(0, y))
            y += 4
            ships_alpha = sorted(planet.ships.keys())
            for ship in ships_alpha:
                if "alien" in ship:
                    continue
                if planet.ships[ship] <= 0:
                    continue
                try:
                    self.add(SimpleSprite((0,0), 'assets/i-%s.png' % ship), V2(0,y))
                except:
                    print("ERROR FINDING ICON FOR %s" % ship)
                    pass
                self.add(Text("%ss" % ship.title(), "small", (0,0), PICO_WHITE, False), V2(15,y + 2))
                color = PICO_WHITE
                if planet.ships[ship] > planet.get_max_fighters():
                    color = PICO_RED
                self.add(Text("%d" % planet.ships[ship], "small", (0,0), color, False), V2(88,y + 2))
                y += 15

        self.redraw()
    # Combine color and gradient thresholds to produce binary image from input
    binary_output = helpers.colorGradientPipeLine(undist)
    # Perspective transform on both binary image and original image (debug)
    warped_binary = helpers.warpPerspective(binary_output)
    # Find lane lines through sliding windows and polyfit
    slideWindow_img, result = helpers.fit_polynomial(warped_binary, undist)
    resultwText = helpers.addTextResult(result)  # Put text on resulting image
    final_result = helpers.addOverlay(resultwText, slideWindow_img)
    return final_result


# Calibrate camera with sample images
mtx, dist = helpers.calibrateCamera()

# Create line objects (leftline and rightLine)
helpers.leftLine = Line()
helpers.rightLine = Line()

# Video processing only
video = '/Users/sumedhinamdar/Documents/GitHub/CarND-Advanced-Lane-Lines/challenge_video.mp4'
clip1 = VideoFileClip(video)
# NOTE: this function expects color images!!
white_clip = clip1.fl_image(process_image)
white_output = video.replace('.mp4', '_lanesFound.mp4')
white_clip.write_videofile(white_output, audio=False)

# # Image processing only
# # Pass in test images to imageList
# imageList = glob.glob(
#     '/Users/sumedhinamdar/Documents/GitHub/CarND-Advanced-Lane-Lines/test_images/*.jpg')
#
예제 #29
0
from moviepy.editor import VideoFileClip
from line import Line
from helper import *
from image_processing import combined_threshold
from pipeline_image import pipeline
import calibrate_camera

if __name__ == "__main__":
    left_lane = Line()
    right_lane = Line()
    white_output = 'project_video_out.mp4'
    clip1 = VideoFileClip("project_video.mp4")
    white_clip = clip1.fl_image(
        pipeline)  #NOTE: this function expects color images!!
    white_clip.write_videofile(white_output, audio=False)
예제 #30
0
from vector import Vector
from line import Line

l1 = Line(normal_vector=Vector(['4.046', '2.836']), constant_term='1.21')
l2 = Line(normal_vector=Vector(['10.115', '7.09']), constant_term='3.025')

print(l1.intersection_with(l2))

l1 = Line(normal_vector=Vector(['7.204', '3.182']), constant_term='8.68')
l2 = Line(normal_vector=Vector(['8.172', '4.114']), constant_term='9.883')

print(l1.intersection_with(l2))

l1 = Line(normal_vector=Vector(['1.182', '5.562']), constant_term='6.744')
l2 = Line(normal_vector=Vector(['1.773', '8.343']), constant_term='9.525')

print(l1.intersection_with(l2))