Exemple #1
0
 def _init_lanes(self):
     lanes = []
     out = "{:4}{:4}{:4}|\n".format("|", "|", "|")
     print(out * 2, end="")
     out = "{:4}{:4}{:4}\n".format("| 1 |", " 2 |", " 3 |")
     print(out)
     for i in range(1, self.num_lanes + 1):
         is_turnlight = input("Is lane number: " + str(i) +
                              " a turning lane? y/n: ")
         if is_turnlight == "y":
             lanes.append(Lane("turn"))
         lanes.append(Lane("straight"))
     return lanes
Exemple #2
0
    def run(self):
        global speed
        global angle
        while True:
            try:
                img = cv2.imread(path, 1)
                # print('speed now is : {0}', rspeed)
                if img is not None:
                    lane = Lane(img)
                    lane.get_Lines()
                    lane.get_center_line_unwarped()
                    # lane.draw_lane()
                    lane.draw_center_line()
                    # print(lane.center_line)
                    angle = int(errorAngle(lane.center_line))
                    speed = int(calcul_speed(angle))
                    # speed, angle = processing(img)
                    # angle,speed = 0 ,0
                    cv2.waitKey(1)
                    if rspeed < 2:
                        speed = 70
                    if speed > Max_speed:
                        speed = Max_speed
                    print(speed, angle, rspeed)

            except Exception as e:
                print(e)
        cv2.destroyAllWindows()
def full_pipeline(input_image):
    new_image = cv2.undistort(input_image, mtx, dist, None, mtx)
    img_obj = Image.Image(new_image.copy())
    img_obj.threshold_mask('mag', mag_min, mag_max, sobel_kernel)
    img_obj.threshold_mask('dir', dir_min, dir_max, sobel_kernel)
    img_obj.threshold_mask('s', col_min_s, col_max_s)
    img_obj.threshold_mask('l', col_min_l, col_max_l)
    warped, inv_M = img_obj.perspective_transform(
        img_obj.get_final_filter().copy())
    warped_img, inv_M2 = img_obj.perspective_transform(new_image.copy())
    lane_obj = Lane.Lane(warped)
    if lines.detected == True:
        is_detect_left, is_detect_right, leftfit, rightfit = lane_obj.get_lane_fitting(
            True, lines.best_left_fit, lines.best_right_fit)
    else:
        is_detect_left, is_detect_right, leftfit, rightfit = lane_obj.get_lane_fitting(
            False)
    lane_obj.compute_curvature()
    lane_obj.compute_horizontal_distance()
    lane_obj.compute_center_offset()
    lines.verify_last_fit(lane_obj.detect_lane_left,
                          lane_obj.detect_lane_right, lane_obj.leftfit_pixel,
                          lane_obj.rightfit_pixel, lane_obj.h_dist)
    result_img = lane_obj.draw_fitting_lane(input_image, inv_M,
                                            lines.best_left_fit,
                                            lines.best_right_fit)
    return result_img
 def __init__(self, arrivalRates, travelMatrix, capacity, flow,
              signalTimings, timeLimit, synchronous, seed):
     random.seed(seed)
     rng = RandomNumberGenerator.RandomNumberGenerator(seed)
     self.output = []
     self.carsInSystem = 0
     self.id = 0
     self.finished = False
     self.timeLimit = timeLimit
     self.arrivalRates = arrivalRates
     self.signalTimings = signalTimings
     self.flow = flow
     self.capacity = capacity
     self.time = 0
     self.eventList = PQ.PriorQ()
     self.travelMatrix = travelMatrix
     self.lights = [Light.Light(self.signalTimings[i]) for i in range(19)]
     self.randomNumbers = []
     self.arrivalIndex = {
         0: 0,
         1: 1,
         2: 2,
         5: 3,
         6: 4,
         9: 5,
         10: 6,
         13: 7,
         16: 8,
         17: 9,
         18: 10
     }
     self.rngCounter = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
     for i in range(20000):
         self.randomNumbers.append(rng.GetRandList())
     if synchronous:
         for i in [0, 3, 4, 7, 8, 11, 12, 13, 14, 18]:
             self.lights[i].setState(1)
     else:
         for i in [1, 2, 4, 7, 9, 10, 12, 13, 14, 18]:
             self.lights[i].setState(1)
     self.lanes = [
         Lane.Lane(self.capacity[i], self.lights[i]) for i in range(19)
     ]
     for lane in self.arrivalRates:
         self.scheduler(
             self.time - math.log(self.randomNumbers[self.rngCounter[
                 self.arrivalIndex[lane]]][self.arrivalIndex[lane]]) /
             self.arrivalRates[lane], "System Arrival", lane)
     self.rngCounter[self.arrivalIndex[lane]] += 1
     for i in range(19):
         self.scheduler(self.lights[i].getNextChange(), "Light Change", i)
     self.intersections = {
         0: (0, 1, 2, 3),
         1: (4, 5, 6, 7),
         2: (8, 9, 10, 11),
         3: (12, 99, 13, 14),
         4: (15, 16, 17, 18)
     }
Exemple #5
0
def laneDeparture(frame):
    steer = Lane.laneTracking(frame)
    if steer < 45:
        steer = 45
    elif steer > 120:
        steer = 120

    print('steer :', steer)
    kit.servo[0].angle = steerTranslate(steer)
Exemple #6
0
def test_lane_lines(show_plot=True, save_plot=True):
    mtx, dist, M, Minv = load_calibration()

    filenames = glob.glob('test_images/*.jpg')
    #filenames = ['test_images/test1.jpg']

    lane = Lane.Lane(M,
                     Minv,
                     mtx,
                     dist,
                     show_plot=show_plot,
                     save_plot=save_plot)

    for i in range(len(filenames)):
        img = read_img(filenames[i])
        img = img2RGB(img)
        lane.process_img(img, filenames[i])

    return lane
Exemple #7
0
def run_lane_lines(show_plot=True,
                   save_plot=True,
                   fname='project_video.mp4',
                   MAX_FRAMES=10000,
                   n_mod=1,
                   fps=16):
    mtx, dist, M, Minv = load_calibration()

    lane = Lane.Lane(M,
                     Minv,
                     mtx,
                     dist,
                     show_plot=show_plot,
                     save_plot=save_plot)

    clip = VideoFileClip(fname)
    n_frames = int(clip.fps * clip.duration)
    n_frames = min(MAX_FRAMES, n_frames)
    count = 0
    images_list = []
    for frame in clip.iter_frames():
        count = count + 1
        if count % n_mod == 0:
            print("{} of {}".format(count, n_frames))
            lane.process_img(frame, str(count))
            images_list.append(lane.lane_img)
        if count >= MAX_FRAMES:
            break

    clip = ImageSequenceClip(images_list, fps=fps)

    savename = splitext(basename(fname))[0]
    savename = 'out_imgs/' + savename + '_out.mp4'
    clip.write_videofile(savename)

    return lane, clip
Exemple #8
0
def create_vector(builder, nparray, flag):
    numVals = nparray.shape[0]

    if flag == 'left':
        Lane.LaneStartLeftVector(builder, numVals)
        return vec3VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'right':
        Lane.LaneStartRightVector(builder, numVals)
        return vec3VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'spine':
        Lane.LaneStartSpineVector(builder, numVals)
        return vec3VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'create_left_point_validities':
        Lane.LaneStartLeftPointValidityVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals)
    elif flag == 'create_right_point_validities':
        Lane.LaneStartRightPointValidityVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals)
    elif flag == 'left_point_validities':
        Lane.LaneStartLeftPointValidityVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'right_point_validities':
        Lane.LaneStartRightPointValidityVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'create_left_point_anomalies':
        Lane.LaneStartLeftPointAnomalyVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals)
    elif flag == 'create_right_point_anomalies':
        Lane.LaneStartRightPointAnomalyVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals)
    elif flag == 'left_point_anomalies':
        Lane.LaneStartLeftPointAnomalyVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'right_point_anomalies':
        Lane.LaneStartRightPointAnomalyVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'create_left_point_annotation_statuses':
        Lane.LaneStartLeftPointAnnotationStatusVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals, byte=1)
    elif flag == 'create_right_point_annotation_statuses':
        Lane.LaneStartRightPointAnnotationStatusVector(builder, numVals)
        return enumByte2VectorBuilderHelper(builder, numVals, byte=1)
    elif flag == 'left_point_annotations':
        Lane.LaneStartLeftPointAnnotationStatusVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
    elif flag == 'right_point_annotations':
        Lane.LaneStartRightPointAnnotationStatusVector(builder, numVals)
        return enumVector2VectorBuilderHelper(builder, numVals, nparray)
Exemple #9
0
def buildFlatbuffer(laneSegments, leftPointValidity, rightPointValidity,
                    leftPointAnomaly, rightPointAnomaly,
                    leftPointAnnotationStatus, rightPointAnnotationStatus):
    temp_lanes = []

    for i in range(len(laneSegments)):
        laneSegment = laneSegments[i]
        builder = flatbuffers.Builder(1024)

        lefts = create_vector(builder, laneSegment['left'], 'left')
        rights = create_vector(builder, laneSegment['right'], 'right')
        spines = create_vector(builder, laneSegment['spine'], 'spine')

        # left point annotation status
        if len(leftPointAnnotationStatus) == 0:
            left_point_annotation_statuses = create_vector(
                builder, laneSegment['left'],
                'create_left_point_annotation_statuses')
        else:
            left_point_annotation_statuses = create_vector(
                builder, np.array(leftPointAnnotationStatus),
                'left_point_annotations')

        # right point annotation status
        if len(rightPointAnnotationStatus) == 0:
            right_point_annotation_statuses = create_vector(
                builder, laneSegment['right'],
                'create_right_point_annotation_statuses')
        else:
            right_point_annotation_statuses = create_vector(
                builder, np.array(rightPointAnnotationStatus),
                'right_point_annotations')

        # left point validity
        if len(leftPointValidity) == 0:
            left_point_validities = create_vector(
                builder, laneSegment['left'], 'create_left_point_validities')
        else:
            left_point_validities = create_vector(builder,
                                                  np.array(leftPointValidity),
                                                  'left_point_validities')

        # right point validity
        if len(rightPointValidity) == 0:
            right_point_validities = create_vector(
                builder, laneSegment['right'], 'create_right_point_validities')
        else:
            right_point_validities = create_vector(
                builder, np.array(rightPointValidity),
                'right_point_validities')

        # left point anomaly
        if not leftPointAnomaly is None and len(leftPointAnomaly) == 0:
            left_point_anomalies = create_vector(
                builder, laneSegment['left'], 'create_left_point_anomalies')
        elif not leftPointAnomaly is None:
            left_point_anomalies = create_vector(builder,
                                                 np.array(leftPointAnomaly),
                                                 'left_point_anomalies')
        else:
            left_point_anomalies = None

        # right point anomaly
        if not rightPointAnomaly is None and len(rightPointAnomaly) == 0:
            right_point_anomalies = create_vector(
                builder, laneSegment['right'], 'create_right_point_anomalies')
        elif not rightPointAnomaly is None:
            right_point_anomalies = create_vector(builder,
                                                  np.array(rightPointAnomaly),
                                                  'right_point_anomalies')
        else:
            right_point_anomalies = None

        # Start Lane:
        Lane.LaneStart(builder)

        # Set ID:
        Lane.LaneAddId(builder, 0)

        # Add Lefts:
        Lane.LaneAddLeft(builder, lefts)

        # Add Rights:
        Lane.LaneAddRight(builder, rights)

        # Add Spine:
        Lane.LaneAddSpine(builder, spines)

        # Add PointValidity
        Lane.LaneAddLeftPointValidity(builder, left_point_validities)
        Lane.LaneAddRightPointValidity(builder, right_point_validities)

        # Add PointAnomaly
        if not left_point_anomalies is None:
            Lane.LaneAddLeftPointAnomaly(builder, left_point_anomalies)

        if not right_point_anomalies is None:
            Lane.LaneAddRightPointAnomaly(builder, right_point_anomalies)

        # Add PointAnnotationStatus
        Lane.LaneAddLeftPointAnnotationStatus(builder,
                                              left_point_annotation_statuses)
        Lane.LaneAddRightPointAnnotationStatus(
            builder, right_point_annotation_statuses)

        lane = Lane.LaneEnd(builder)
        builder.Finish(lane)
        temp_lanes.append(lane)

        return builder
Exemple #10
0
def Game(start_time):
    points = 0

    WIDTH = 800
    HEIGHT = 400

    def stop(answer):
        if answer is True:
            answer = False
        else:
            answer = True

    LANE_HEIGHT = 60
    TOP_WINDOW_SPACE = 40

    speeds = [5, -5, 3, -4, 5]

    lanes = [None] * 5
    for i in range(len(lanes)):
        if i == 4:
            lanes[i] = Lane(0, TOP_WINDOW_SPACE + LANE_HEIGHT * i, 2, 2,
                            speeds[i], LANE_HEIGHT)
        else:
            lanes[i] = Lane(0, TOP_WINDOW_SPACE + LANE_HEIGHT * i, 1, 3,
                            speeds[i], LANE_HEIGHT)

    frog = Frog(WIDTH / 2,
                lanes[-1].y + LANE_HEIGHT + LANE_HEIGHT / 4,
                0,
                0,
                WIDTH,
                HEIGHT,
                step=LANE_HEIGHT)

    root = Tk()
    w = Canvas(root, width=WIDTH, height=HEIGHT)

    paused = Button(root, text="PAUSE", command=stop)

    w.pack()

    state = None
    answer = True
    while answer is True:

        points = round(100 - (time.time() - start_time), 1)

        for lane in lanes:
            lane.moveCars()

        # move the frog
        if keyboard.is_pressed("up arrow"):
            frog.moveUp()
        if keyboard.is_pressed("down arrow"):
            frog.moveDown()
        if keyboard.is_pressed("left arrow"):
            frog.moveLeft()
        if keyboard.is_pressed("right arrow"):
            frog.moveRight()

        w.delete("all")
        w.create_rectangle(0, 0, WIDTH, HEIGHT, fill="white")
        w.create_text(400, 15, text=str("POINTS: " + str(points)))
        pausedw = w.create_window(700, 20, window=paused)

        for lane in lanes:
            lane.draw(w)
        frog.draw(w)
        w.update()

        for lane in lanes:
            for vehicle in lane.cars:
                if frog.collision(vehicle) is True:
                    state = False
                    break

        if state == False:
            break

        if points == 0:
            state = False
            break

        if frog.y <= TOP_WINDOW_SPACE:
            state = True
            break

        time.sleep(50 / 1000)

    paused.destroy()

    if state is False:  # if the player has failed
        Failer(w, root)

    elif state is True:  # if the player won
        Winner(w, points, root)
    w.mainloop()
Exemple #11
0
tk = Tk()
WIDTH = 800
HEIGHT = 400
w = Canvas(tk, width=WIDTH, height=HEIGHT)
tk.title("Frogger Game (by Roger Rey)")
w.pack()

LANE_HEIGHT = 40
TOP_WINDOW_SPACE = 40
speeds = [7, -5, 10, -9, 3]
lanes = [None] * 5

for i in range(len(lanes)):
    if i == 4:  #lorrys
        lanes[i] = Lane(0, TOP_WINDOW_SPACE + LANE_HEIGHT * i, 2, 6,
                        len(lanes), speeds[i], LANE_HEIGHT)
    else:  #cars
        lanes[i] = Lane(0, TOP_WINDOW_SPACE + LANE_HEIGHT * i, 1, 4,
                        len(lanes), speeds[i], LANE_HEIGHT)

frog = Frog(WIDTH / 2, lanes[-1].y + LANE_HEIGHT + LANE_HEIGHT / 4, 0, 0,
            WIDTH, HEIGHT, LANE_HEIGHT)

while not frog.finishReached() and frog.alive:

    for lane in lanes:
        lane.moveCars()

    #move the frog
    frog.move()
Exemple #12
0

def steerTranslate(value):
    trans = int(value * 4 / 3 - 10)

    return trans


cam = cv2.VideoCapture(gstreamer_pipeline(flip_method=0), cv2.CAP_GSTREAMER)
kit = ServoKit(channels=16)

if cam.isOpened():
    try:
        while True:
            ret, frame = cam.read()
            steer = Lane.laneTracking(frame)
            if steer < 45:
                steer = 45
            elif steer > 120:
                steer = 120

            print('steer :', steer)
            kit.servo[0].angle = steerTranslate(steer)
            if cv2.waitKey(30) & 0xff == 27:
                break
    finally:
        cv2.destroyAllWindows()
        cam.release()
else:
    print("NoVideo")
Exemple #13
0
myLabel2=Label(w,text="Score: ")
myLabel2.place(x=0,y=0)
myLabel3=Label(w,text="Pulsa p per pausar ")
myLabel3.place(x=0,y=30)

w.pack()

#x,y,type,numOfCars,carsSpeed)

LANE_HEIGHT=60
TOP_WINDOW_SPACE=60
speeds=[5,-14,8,-9,11]
lanes=[None]*5
for i in range(len(lanes)):
    if i==4:
        lanes[i] = Lane(0, TOP_WINDOW_SPACE + LANE_HEIGHT * i, 2, 3, speeds[i], LANE_HEIGHT)
    else:
        lanes[i] = Lane(0,TOP_WINDOW_SPACE + LANE_HEIGHT*i,1,4,speeds[i],LANE_HEIGHT)



frog=Frog(WIDTH/2,lanes[-1].y+LANE_HEIGHT+LANE_HEIGHT/4,0,30,WIDTH,HEIGHT,step=LANE_HEIGHT)
now = datetime.now()
Game=TRUE


name=input("Tell me your name:")
#dictionary={"Key":"Value"}
paused=False

def orden(e):
 def get_init_network(self,roadname_list,signal_plan, roaddata,demand_data,stime,etime):
     Network= []
     car_len=self.car_len
     self.Demand = demand_data
     for i in range(len(roadname_list)): #for each road of the network
         res = self.get_one_roaddata(roadname_list[i],roaddata)
         widen_S=0  #the number of lanes with Stretching-segment Design
         for j in range(len(res)):
             if res[j][5]!=-1 and res[j][3]=='直':
                 widen_S+=1
                 widen_S_len=res[j][5]
         road_len = int(res[0][4])
         lane_num=2   #The number of lanes in the road,the default is 2
         #Initilize a road
         one_road=Road.Road(roadname_list[i],road_len,lane_num,40,10.8,1,1,car_len,stime,etime,widen_S)  #初始化路段对象
         ssa = []    #The green light interval corresponding to each turn
         ssa_right = ''  #Judge whether there is right turn signal control
         for j in range(len(signal_plan)):
             #print(roadname_list[i],signal_plan[j].roadname)
             if roadname_list[i] == signal_plan[j].roadname:
                 temp = []
                 temp.append(signal_plan[j].CDZ)  # 转向
                 temp.append(signal_plan[j].green)  # 绿灯区间
                 ssa.append(temp)
         for j in range(len(ssa)):
             ssa_right += ssa[j][0]
         o_lane = []
         road_right = ''  #Judge whether there is a right turn lane in the road information
         for j in range(len(res)):
             road_right += res[j][3]
             o_lane.append(res[j][3])
         if '右' in road_right and '右' not in ssa_right:  #Has right turn lane but no right turn signal control
             for j in range(len(o_lane)):
                 if '右' in o_lane[j] and len(o_lane[j]) == 1:
                     o_lane[j] = '右转nosig'   #Supplement the right turn lane without signal control
         elif '右' not in road_right:
             if '右' in ssa_right:
                 o_lane.append('右')   #Supplement the right turn lane
             else:
                 o_lane.append('右转nosig')   #Supplement the right turn lane without signal control
         #print(o_lane)
         lane = ['直' for x in range(len(o_lane))]
         for j in range(len(o_lane)):  #Change to standard turn order( left->straight->right )
             if '左' in o_lane[j]:
                 lane[0] = o_lane[j]
                 o_lane[j]=''
             if '左' in lane and '左' in o_lane[j]:
                 lane[1] = o_lane[j]
             if '右' in o_lane[j]:
                 lane[-1] = o_lane[j]
         Road_widen=[0 for x in range(len(lane))]  #Stretching-segment lane distribution
         #print(lane)
         for j in range(len(lane)): # for each lane of this road
             lane_ID=roadname_list[i]+'-'+str(j)
             direction=lane[j]
             if 'nosig' in lane[j]:
                 signalornot=1   #No signal control lane is always 1
             else:
                 signalornot=0
             ht=2        #Saturation headway,default is 2 second
             wideornot=0
             if 'nosig' in lane[j]:
                 SSA=[[stime, etime]]
             else:
                 SSA =self.get_green(ssa, lane[j])  #Obtain the green traffic time corresponding to each lane
             lane_len = road_len
             widen_len=-1
             for k in range(len(res)):
                 if res[k][5]!=-1:
                     if '左' in res[k][3] and '左' in direction and j==0:
                         widen_len=res[k][5]
                         Road_widen[j]='L'
                     if '右' in res[k][3] and '右' in direction and j==len(lane)-1:
                         widen_len = res[k][5]
                         Road_widen[j] = 'R'
             if widen_S>0:
                 if direction=='直' and len(lane)-1-widen_S<=j:
                     widen_len=widen_S_len
                     Road_widen[j] = 'S'
             # initilize a lane of this road
             one_lane = Lane.Lane(lane_ID, direction, lane_len, signalornot, ht, wideornot, car_len, SSA,widen_len,stime,etime)
             one_road.Lanes.append(one_lane)
         one_road.widen=Road_widen
         for j in range(len(self.Demand)):
             if self.Demand[j].road_path[0]==roadname_list[i] and stime<=self.Demand[j].entrytime<=etime:
                 time_index=(self.Demand[j].entrytime-stime).seconds
                 one_road.demand_time[time_index]+=1
                 one_road.demand[time_index].append(self.Demand[j])
         for j in range(len(one_road.Lanes)):
             if one_road.widen[j]!=0:
                 one_road.capcaity+=int(one_road.Lanes[j].widen_len/car_len)
             else:
                 one_road.capcaity += int(one_road.Lanes[j].lane_length/car_len)
         Network.append(one_road)
     self.Network=Network
     #self.Demand=demand_data
     return 0