From cea25354b15d6ad9c564ebe917d1d518e8e088f3 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Thu, 18 Dec 2025 19:15:12 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E5=99=A8=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/agent.py | 29 ++++++++++------------ 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/agent.py b/src/Active-Lane-Keeping-Assistant/agent.py index 6c51f98c18..18a0706b7a 100644 --- a/src/Active-Lane-Keeping-Assistant/agent.py +++ b/src/Active-Lane-Keeping-Assistant/agent.py @@ -138,24 +138,21 @@ def get_actions(self, detection_surface_area:float, return steer, self.throttle @staticmethod - def _simple_controller(error:float) -> float: - """Hard Coded Controller - - Args: - error (float): Difference to the center of the detected lane. - - Returns: - float: Steering angle to use. + def _simple_controller(error: float) -> float: + """Hard Coded Controller - Optimized to use Class Constants """ - limit = 0.75 - tolerance = 0.1 + # 使用类中定义的常量,方便统一管理 + limit = Agent.SIMPLE_STEER_LIMIT + tolerance = Agent.SIMPLE_ERROR_TOLERANCE + if (abs(error) < tolerance): - steer = 0 - elif error > 0: - steer = -limit - else: - steer = limit - return steer + return 0.0 + + # 简化逻辑分支 + if error > 0: + return -limit + + return limit def _p_controller(self, error:float) -> float: """Proportional Controller From 0c6bc72aae40d9af877d37f9db7c7935b3698977 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Thu, 18 Dec 2025 20:11:31 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=E4=BC=98=E5=8C=96lane=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/lane.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/lane.py b/src/Active-Lane-Keeping-Assistant/lane.py index 9a7cd67f09..ddfc45eab6 100644 --- a/src/Active-Lane-Keeping-Assistant/lane.py +++ b/src/Active-Lane-Keeping-Assistant/lane.py @@ -12,6 +12,10 @@ class Lane: HLS_L_THRESHOLD_MIN = 150 HLS_L_THRESHOLD_MAX = 255 XM_PER_PIX = 3.7 / 781 + ROI_BOTTOM = 350 + ROI_TOP = 260 + ROI_LEFT = 200 + ROI_RIGHT = 440 def __init__(self, height:int, width:int, save:bool=False, save_folder:str=join('img', 'examples')) -> None: """Constructor @@ -66,8 +70,11 @@ def get_lines(self, img:np.ndarray) -> np.ndarray: return binary_blured - def extract_roi(self, img:np.ndarray, bottom:int=350, top:int=260, - left:int=200, right:int=440) -> tuple[np.ndarray, np.ndarray]: + def extract_roi(self, img: np.ndarray, + bottom: int = ROI_BOTTOM, + top: int = ROI_TOP, + left: int = ROI_LEFT, + right: int = ROI_RIGHT) -> tuple[np.ndarray, np.ndarray]: """Extract the Region of Interest Extracts the region of interest and transforms it to fit the original From f2d5bb7bdf574c6654f2daaa95a8b54c6774d281 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Thu, 18 Dec 2025 20:39:51 +0800 Subject: [PATCH 03/10] =?UTF-8?q?=E4=BC=98=E5=8C=96world=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/world.py | 52 ++++++++++++++-------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/world.py b/src/Active-Lane-Keeping-Assistant/world.py index 7f106f10ca..37b7d25488 100644 --- a/src/Active-Lane-Keeping-Assistant/world.py +++ b/src/Active-Lane-Keeping-Assistant/world.py @@ -47,12 +47,23 @@ def __init__(self, server_ip: str = '127.0.0.1', port: int = 2000, # Use Tesla Model 3 as Car self.bp = self.blueprint_library.filter('model3')[0] - # === 修复 2: 随机选择出生点,防止车位被占导致无法生成 === - spawn_points = self.world.get_map().get_spawn_points() - if spawn_points: - self.spawn_point = random.choice(spawn_points) - else: - self.spawn_point = carla.Transform() # 防止没有生成点的情况 + # === 修改: 将出生点设置为当前上帝视角相机的位置 === + # 1. 获取上帝视角的观察者对象 + spectator = self.world.get_spectator() + + # 2. 获取观察者现在的坐标和朝向 + transform = spectator.get_transform() + + # 3.稍微把位置抬高一点(+2米),防止相机贴地导致车卡在地里 + transform.location.z += 2.0 + + # 4. 稍微把位置往前挪一点(+5米),让你能直接看到车出现在眼前 + # (利用朝向向量计算前方的位置) + forward_vector = transform.get_forward_vector() + transform.location.x += forward_vector.x * 5.0 + transform.location.y += forward_vector.y * 5.0 + + self.spawn_point = transform # ==================================================== self.vehicle = None @@ -90,16 +101,7 @@ def reset(self) -> tuple[float, float, np.ndarray, bool]: self.vehicle = self.world.spawn_actor(self.bp, self.spawn_point) # Spawn camera - blueprint = self.blueprint_library.find('sensor.camera.rgb') - blueprint.set_attribute('image_size_x', f'{self.image_width}') - blueprint.set_attribute('image_size_y', f'{self.image_height}') - blueprint.set_attribute('fov', f'{self.fov}') - - # Relative location to car - spawn_point = carla.Transform(carla.Location(x=2.5, z=0.7)) - self.sensor = self.world.spawn_actor(blueprint, spawn_point, - attach_to=self.vehicle) - self.sensor.listen(self.image_queue.put) + self._spawn_camera() # Spawn collision sensor blueprint = self.world.get_blueprint_library() \ @@ -110,8 +112,20 @@ def reset(self) -> tuple[float, float, np.ndarray, bool]: self.collision_sensor.listen(lambda e: {self._set_collision()}) self.initialized = True - return self._change_to_left_lane() + return 0.0, 0.0, np.zeros((self.image_height, self.image_width, 3)), False + + def _spawn_camera(self) -> None: + """Helper method to spawn the camera sensor""" + blueprint = self.blueprint_library.find('sensor.camera.rgb') + blueprint.set_attribute('image_size_x', f'{self.image_width}') + blueprint.set_attribute('image_size_y', f'{self.image_height}') + blueprint.set_attribute('fov', f'{self.fov}') + # Relative location to car + spawn_point = carla.Transform(carla.Location(x=2.5, z=0.7)) + self.sensor = self.world.spawn_actor(blueprint, spawn_point, + attach_to=self.vehicle) + self.sensor.listen(self.image_queue.put) def _set_collision(self) -> None: """Helper to set collision_detected to True. """ @@ -189,8 +203,8 @@ def step(self, show: bool = True, throttle: float = 0, transformed_image, error, detection_surface_area = self.lane \ .pipe(img=image) - if show: - World.show_image(image=transformed_image) + #if show: + #World.show_image(image=transformed_image) return error, detection_surface_area, transformed_image, \ self.collision_detected \ No newline at end of file From 9176e7a8caf33814d78db608628b231b4c551820 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Fri, 19 Dec 2025 17:27:17 +0800 Subject: [PATCH 04/10] =?UTF-8?q?=E4=BC=98=E5=8C=96main=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/main.py | 38 ++++++++++++----------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/main.py b/src/Active-Lane-Keeping-Assistant/main.py index 7ac65d4135..25f94c15fd 100644 --- a/src/Active-Lane-Keeping-Assistant/main.py +++ b/src/Active-Lane-Keeping-Assistant/main.py @@ -265,27 +265,29 @@ def make_path(folder:str, id:str) -> str: return path -if __name__ == '__main__': + +def parse_args() -> argparse.Namespace: + """Parses command line arguments""" parser = argparse.ArgumentParser(prog='Active Lane Keeping System', - description='') - parser.add_argument('-id', '--identifier', type=str, help=('Unique ' - 'identifier used to identify the run.'), dest='id', required=True) + description='') + parser.add_argument('-id', '--identifier', type=str, required=True, + help='Unique identifier used to identify the run.', dest='id') parser.add_argument('-c', '--controller', default='pid', type=str, - choices=['simple', 'p', 'pd', 'pid'], help=('The method used to ' - 'control the car.'), dest='controller') - parser.add_argument('-s', '--steps', default=100, type=int, help=('The ' - 'number of steps that the agent controls the car. This does not ' - 'include the inital setup driving to the fourth lane.'), dest='steps') - parser.add_argument('-a', '--adapt', action='store_true', - help=('Whether to adapt the parameters. This only takes effect if not ' - '\'simple\' is selected as controller.'), dest='adapt') + choices=['simple', 'p', 'pd', 'pid'], dest='controller', + help='The method used to control the car.') + parser.add_argument('-s', '--steps', default=100, type=int, dest='steps', + help='The number of steps that the agent controls the car.') + parser.add_argument('-a', '--adapt', action='store_true', dest='adapt', + help='Whether to adapt the parameters.') parser.add_argument('-t', '--tolerance', default=0.2, type=float, - help=('Tolerance range for the adaption of the parameters. This takes ' - 'effect only if adapt is set to true.'), dest='tolerance') - parser.add_argument('-d', '--debug', action='store_true', - help=('Whether to use debug mode for logging. This takes effect only ' - 'if adapt is set to true.'), dest='debug') - args = parser.parse_args() + help='Tolerance range for the adaption.', dest='tolerance') + parser.add_argument('-d', '--debug', action='store_true', dest='debug', + help='Whether to use debug mode for logging.') + + return parser.parse_args() +if __name__ == '__main__': + + args = parse_args() path = make_path(folder='assets', id=args.id) From fc6e581119f4ec810cb1665e58ebbc6589ca6575 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Fri, 19 Dec 2025 21:03:55 +0800 Subject: [PATCH 05/10] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87=E7=AE=A1=E7=90=86=E5=99=A8=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/recorder.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Active-Lane-Keeping-Assistant/recorder.py b/src/Active-Lane-Keeping-Assistant/recorder.py index 826b34a5e1..e8c1744b62 100644 --- a/src/Active-Lane-Keeping-Assistant/recorder.py +++ b/src/Active-Lane-Keeping-Assistant/recorder.py @@ -60,4 +60,13 @@ def close_recording(self) -> None: """ if self.video is None: raise Exception('No video initialized.') - self.video.release() \ No newline at end of file + self.video.release() + + def __enter__(self): + """Context manager entry point""" + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Context manager exit point - ensures video is closed""" + if self.video is not None: + self.close_recording() \ No newline at end of file From 58453e730742bd389fb837c899b812b08c49a0d6 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Fri, 19 Dec 2025 21:25:42 +0800 Subject: [PATCH 06/10] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E5=88=A4=E7=A9=BA=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/agent.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/agent.py b/src/Active-Lane-Keeping-Assistant/agent.py index 18a0706b7a..a3db79b20d 100644 --- a/src/Active-Lane-Keeping-Assistant/agent.py +++ b/src/Active-Lane-Keeping-Assistant/agent.py @@ -1,8 +1,8 @@ from __future__ import annotations +import os import matplotlib.pyplot as plt import numpy as np -import os class Agent(): """Agent that outputs the desired behaviour given @@ -128,7 +128,7 @@ def get_actions(self, detection_surface_area:float, """ if (self.check_surface_area(detection_surface_area)): steer = 0 - if len(self.errors) > 0: + if self.errors: self.errors.append(self.errors[-1]) else: self.errors.append(0) From 99cd23b4b4aacf1825c087ed300f4fb184ffcc20 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Fri, 19 Dec 2025 21:56:53 +0800 Subject: [PATCH 07/10] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20Lambda=20=E8=A1=A8?= =?UTF-8?q?=E8=BE=BE=E5=BC=8F=E7=9A=84=E5=86=97=E4=BD=99=E8=AF=AD=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/world.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Active-Lane-Keeping-Assistant/world.py b/src/Active-Lane-Keeping-Assistant/world.py index 37b7d25488..1639fd8e67 100644 --- a/src/Active-Lane-Keeping-Assistant/world.py +++ b/src/Active-Lane-Keeping-Assistant/world.py @@ -109,7 +109,8 @@ def reset(self) -> tuple[float, float, np.ndarray, bool]: self.collision_sensor = self.world.spawn_actor(blueprint, carla.Transform(), attach_to=self.vehicle) self.collision_detected = False - self.collision_sensor.listen(lambda e: {self._set_collision()}) + # Remove redundant set brackets + self.collision_sensor.listen(lambda e: self._set_collision()) self.initialized = True return 0.0, 0.0, np.zeros((self.image_height, self.image_width, 3)), False From b4c363723f988086ff576258dbe2d28c9965f9ad Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Fri, 19 Dec 2025 22:50:19 +0800 Subject: [PATCH 08/10] =?UTF-8?q?=E6=8F=90=E5=8F=96=E8=BD=A6=E9=81=93?= =?UTF-8?q?=E8=BE=B9=E8=B7=9D=E6=AF=94=E4=BE=8B=E5=B8=B8=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/lane.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Active-Lane-Keeping-Assistant/lane.py b/src/Active-Lane-Keeping-Assistant/lane.py index ddfc45eab6..d47cb15692 100644 --- a/src/Active-Lane-Keeping-Assistant/lane.py +++ b/src/Active-Lane-Keeping-Assistant/lane.py @@ -16,6 +16,9 @@ class Lane: ROI_TOP = 260 ROI_LEFT = 200 ROI_RIGHT = 440 + # === 新增 === + MARGIN_RATIO = 1.0 / 12.0 + # =========== def __init__(self, height:int, width:int, save:bool=False, save_folder:str=join('img', 'examples')) -> None: """Constructor @@ -32,7 +35,7 @@ def __init__(self, height:int, width:int, save:bool=False, self.save_folder = save_folder self.img_height = height self.img_width = width - self.margin = int((1/12) * self.img_width) + self.margin = int(self.MARGIN_RATIO * self.img_width) self.DEGREE = 2 # Variables to store for lines From b9be10514df597a993e0a76c10b2b090a347173f Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Sat, 20 Dec 2025 19:05:06 +0800 Subject: [PATCH 09/10] =?UTF-8?q?=E6=8F=90=E5=8F=96=20PD=20=E6=8E=A7?= =?UTF-8?q?=E5=88=B6=E5=99=A8=E7=9A=84=E6=97=B6=E9=97=B4=E6=AD=A5=E9=95=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/agent.py | 15 +++------------ src/Active-Lane-Keeping-Assistant/world.py | 4 ++-- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/agent.py b/src/Active-Lane-Keeping-Assistant/agent.py index a3db79b20d..c8f837ab64 100644 --- a/src/Active-Lane-Keeping-Assistant/agent.py +++ b/src/Active-Lane-Keeping-Assistant/agent.py @@ -115,17 +115,7 @@ def save_error_fig(self, path:str, id:str) -> None: def get_actions(self, detection_surface_area:float, error:float) -> tuple[float, float]: - """Retrieve action based on Observation - Args: - error (float): Difference to the center of the detected lane. - detection_surface_area (float): Detected surface area. - - Returns: - tuple[float, float]: - [0]: Steering angle to use. - [1]: Throttle to apply. - """ if (self.check_surface_area(detection_surface_area)): steer = 0 if self.errors: @@ -179,9 +169,10 @@ def _pd_controller(self, error:float) -> float: self.prev_error = self.errors[-2] else: self.prev_error = self.errors[-1] - + deviation = error - self.prev_error - steer = - self.tau_d * deviation/0.1 + self._p_controller(error) + dt = 0.1 # Delta time + steer = - self.tau_d * deviation / dt + self._p_controller(error) return steer def _pid_controller(self, error:float) -> float: diff --git a/src/Active-Lane-Keeping-Assistant/world.py b/src/Active-Lane-Keeping-Assistant/world.py index 1639fd8e67..15846afd94 100644 --- a/src/Active-Lane-Keeping-Assistant/world.py +++ b/src/Active-Lane-Keeping-Assistant/world.py @@ -204,8 +204,8 @@ def step(self, show: bool = True, throttle: float = 0, transformed_image, error, detection_surface_area = self.lane \ .pipe(img=image) - #if show: - #World.show_image(image=transformed_image) + if show: + World.show_image(image=transformed_image) return error, detection_surface_area, transformed_image, \ self.collision_detected \ No newline at end of file From 8e2efa7e0ade6c09c2eacb6099359b29c53249d7 Mon Sep 17 00:00:00 2001 From: wutong88yuyu <2179751939@qq.com> Date: Sun, 21 Dec 2025 15:12:29 +0800 Subject: [PATCH 10/10] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=90=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF=E5=B9=B6=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Active-Lane-Keeping-Assistant/agent.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Active-Lane-Keeping-Assistant/agent.py b/src/Active-Lane-Keeping-Assistant/agent.py index c8f837ab64..3cb11e0734 100644 --- a/src/Active-Lane-Keeping-Assistant/agent.py +++ b/src/Active-Lane-Keeping-Assistant/agent.py @@ -9,9 +9,15 @@ class Agent(): """ SIMPLE_STEER_LIMIT = 0.75 SIMPLE_ERROR_TOLERANCE = 0.1 - def __init__(self, tau_p:float = 0, tau_d:float = 0, tau_i:float = 0, - surface_lower_threshold:float = 20e6, throttle:float = 0.3, - suface_upper_threshold=30e6, controller:str = 'simple') -> None: + + def __init__(self, + tau_p: float = 0, + tau_d: float = 0, + tau_i: float = 0, + surface_lower_threshold: float = 20e6, + throttle: float = 0.3, + surface_upper_threshold: float = 30e6, # Fixed typo: suface -> surface + controller: str = 'simple') -> None: """Constructor Args: @@ -43,7 +49,7 @@ def __init__(self, tau_p:float = 0, tau_d:float = 0, tau_i:float = 0, self.tau_d = tau_d self.tau_i = tau_i self.surface_lower_threshold = surface_lower_threshold - self.surface_upper_threshold = suface_upper_threshold + self.surface_upper_threshold = surface_upper_threshold # Fixed assignment self.prev_error = None self.throttle = throttle self.func = None