commit ad2740d5079e3c0d8622da73883807dec89d2e18 Author: trung09122002 Date: Thu Sep 18 15:08:32 2025 +0700 first diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..122af2c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +dataset \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..95d7b9c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,208 @@ +cmake_minimum_required(VERSION 3.0.2) +project(landmarks_detection) + +## Compile as C++11, supported in ROS Kinetic and newer +# add_compile_options(-std=c++11) + +## Find catkin macros and libraries +## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) +## is used, also find other catkin packages +find_package(catkin REQUIRED COMPONENTS + cv_bridge + message_generation + rospy + sensor_msgs + std_msgs +) + +## System dependencies are found with CMake's conventions +# find_package(Boost REQUIRED COMPONENTS system) + + +## Uncomment this if the package has a setup.py. This macro ensures +## modules and global scripts declared therein get installed +## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html +# catkin_python_setup() + +################################################ +## Declare ROS messages, services and actions ## +################################################ + +## To declare and build messages, services or actions from within this +## package, follow these steps: +## * Let MSG_DEP_SET be the set of packages whose message types you use in +## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...). +## * In the file package.xml: +## * add a build_depend tag for "message_generation" +## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET +## * If MSG_DEP_SET isn't empty the following dependency has been pulled in +## but can be declared for certainty nonetheless: +## * add a exec_depend tag for "message_runtime" +## * In this file (CMakeLists.txt): +## * add "message_generation" and every package in MSG_DEP_SET to +## find_package(catkin REQUIRED COMPONENTS ...) +## * add "message_runtime" and every package in MSG_DEP_SET to +## catkin_package(CATKIN_DEPENDS ...) +## * uncomment the add_*_files sections below as needed +## and list every .msg/.srv/.action file to be processed +## * uncomment the generate_messages entry below +## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...) + +## Generate messages in the 'msg' folder +add_message_files( + FILES + landmark.msg + landmark_array.msg +) + +## Generate services in the 'srv' folder +# add_service_files( +# FILES +# Service1.srv +# Service2.srv +# ) + +## Generate actions in the 'action' folder +# add_action_files( +# FILES +# Action1.action +# Action2.action +# ) + +## Generate added messages and services with any dependencies listed here +generate_messages( + DEPENDENCIES + std_msgs +) + +################################################ +## Declare ROS dynamic reconfigure parameters ## +################################################ + +## To declare and build dynamic reconfigure parameters within this +## package, follow these steps: +## * In the file package.xml: +## * add a build_depend and a exec_depend tag for "dynamic_reconfigure" +## * In this file (CMakeLists.txt): +## * add "dynamic_reconfigure" to +## find_package(catkin REQUIRED COMPONENTS ...) +## * uncomment the "generate_dynamic_reconfigure_options" section below +## and list every .cfg file to be processed + +## Generate dynamic reconfigure parameters in the 'cfg' folder +# generate_dynamic_reconfigure_options( +# cfg/DynReconf1.cfg +# cfg/DynReconf2.cfg +# ) + +################################### +## catkin specific configuration ## +################################### +## The catkin_package macro generates cmake config files for your package +## Declare things to be passed to dependent projects +## INCLUDE_DIRS: uncomment this if your package contains header files +## LIBRARIES: libraries you create in this project that dependent projects also need +## CATKIN_DEPENDS: catkin_packages dependent projects also need +## DEPENDS: system dependencies of this project that dependent projects also need +catkin_package( +# INCLUDE_DIRS include +# LIBRARIES landmarks_detection + CATKIN_DEPENDS cv_bridge message_generation message_runtime rospy sensor_msgs std_msgs +# DEPENDS system_lib +) + +########### +## Build ## +########### + +## Specify additional locations of header files +## Your package locations should be listed before other locations +include_directories( +# include + ${catkin_INCLUDE_DIRS} +) + +## Declare a C++ library +# add_library(${PROJECT_NAME} +# src/${PROJECT_NAME}/landmarks_detection.cpp +# ) + +## Add cmake target dependencies of the library +## as an example, code may need to be generated before libraries +## either from message generation or dynamic reconfigure +# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +## Declare a C++ executable +## With catkin_make all packages are built within a single CMake context +## The recommended prefix ensures that target names across packages don't collide +# add_executable(${PROJECT_NAME}_node src/landmarks_detection_node.cpp) + +## Rename C++ executable without prefix +## The above recommended prefix causes long target names, the following renames the +## target back to the shorter version for ease of user use +## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node" +# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "") + +## Add cmake target dependencies of the executable +## same as for the library above +# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) + +## Specify libraries to link a library or executable target against +# target_link_libraries(${PROJECT_NAME}_node +# ${catkin_LIBRARIES} +# ) + +############# +## Install ## +############# + +# all install targets should use catkin DESTINATION variables +# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html + +## Mark executable scripts (Python etc.) for installation +## in contrast to setup.py, you can choose the destination +# catkin_install_python(PROGRAMS +# scripts/my_python_script +# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +# ) + +## Mark executables for installation +## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html +# install(TARGETS ${PROJECT_NAME}_node +# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} +# ) + +## Mark libraries for installation +## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html +# install(TARGETS ${PROJECT_NAME} +# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} +# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} +# RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} +# ) + +## Mark cpp header files for installation +# install(DIRECTORY include/${PROJECT_NAME}/ +# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} +# FILES_MATCHING PATTERN "*.h" +# PATTERN ".svn" EXCLUDE +# ) + +## Mark other files for installation (e.g. launch and bag files, etc.) +# install(FILES +# # myfile1 +# # myfile2 +# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} +# ) + +############# +## Testing ## +############# + +## Add gtest based cpp test target and link libraries +# catkin_add_gtest(${PROJECT_NAME}-test test/test_landmarks_detection.cpp) +# if(TARGET ${PROJECT_NAME}-test) +# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}) +# endif() + +## Add folders to be run by python nosetests +# catkin_add_nosetests(test) diff --git a/codebook/codebook_kNN.joblib b/codebook/codebook_kNN.joblib new file mode 100644 index 0000000..3b0f21e Binary files /dev/null and b/codebook/codebook_kNN.joblib differ diff --git a/codebook/create_codebook.py b/codebook/create_codebook.py new file mode 100755 index 0000000..d2026b5 --- /dev/null +++ b/codebook/create_codebook.py @@ -0,0 +1,68 @@ +# build_codebook.py +# thay doi K va batch_size neu thay doi max_total +import glob, cv2, numpy as np, joblib +from sklearn.cluster import MiniBatchKMeans +from sklearn.preprocessing import normalize +from tqdm import tqdm + +K = 4096 # số visual words (512–4096 tùy dữ liệu) +MAX_FEATS_PER_IMG = 800 +IMG_GLOB = "../dataset/train/images/*.jpg" # thư mục ảnh landmark +USE_SURF = False # True nếu bạn có opencv-contrib và chấp nhận license SURF + +def create_detector(): + if USE_SURF and hasattr(cv2, "xfeatures2d"): + return cv2.xfeatures2d.SURF_create(hessianThreshold=400) + return cv2.SIFT_create(nfeatures=1200) + +def sample_desc(paths, max_total=2_000_000): + det = create_detector() + all_desc = [] + total = 0 + for p in tqdm(paths, desc="Extracting descriptors"): + img = cv2.imread(p, cv2.IMREAD_GRAYSCALE) + if img is None: continue + h, w = img.shape[:2] + s = 640.0 / max(h, w) + if s < 1.0: img = cv2.resize(img, (int(w*s), int(h*s))) + kps, desc = det.detectAndCompute(img, None) + if desc is None or len(desc)==0: continue + if len(desc) > MAX_FEATS_PER_IMG: + idx = np.random.choice(len(desc), MAX_FEATS_PER_IMG, replace=False) + desc = desc[idx] + all_desc.append(desc.astype(np.float32)) + total += len(desc) + if total >= max_total: break + return np.vstack(all_desc) if all_desc else np.empty((0,128), np.float32) + +def estimate_idf(paths, kmeans): + det = create_detector() + K = kmeans.n_clusters + df = np.zeros(K, dtype=np.float32) + for p in tqdm(paths, desc="Estimating DF/IDF"): + img = cv2.imread(p, cv2.IMREAD_GRAYSCALE) + if img is None: continue + kps, d = det.detectAndCompute(img, None) + if d is None or len(d)==0: continue + words = kmeans.predict(d.astype(np.float32)) + df[np.unique(words)] += 1 + idf = np.log((len(paths)+1)/(df+1)).astype(np.float32) + return idf + +def main(): + paths = glob.glob(IMG_GLOB, recursive=True) + assert len(paths)>0, "Không tìm thấy ảnh trong landmarks_train/" + desc = sample_desc(paths) + print("Descriptors:", desc.shape) + assert desc.shape[0]>0, "Không thu được descriptor nào!" + + kmeans = MiniBatchKMeans(n_clusters=K, batch_size=30_000, reassignment_ratio=0.01, verbose=1) + kmeans.fit(desc) + + idf = estimate_idf(paths, kmeans) + joblib.dump(kmeans, "codebook_kNN.joblib") + np.save("idf.npy", idf) + print("Saved: codebook_kNN.joblib, idf.npy") + +if __name__ == "__main__": + main() diff --git a/codebook/idf.npy b/codebook/idf.npy new file mode 100644 index 0000000..fd8905c Binary files /dev/null and b/codebook/idf.npy differ diff --git a/launch/landmark.launch b/launch/landmark.launch new file mode 100755 index 0000000..8244a31 --- /dev/null +++ b/launch/landmark.launch @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/msg/landmark.msg b/msg/landmark.msg new file mode 100755 index 0000000..49f1a08 --- /dev/null +++ b/msg/landmark.msg @@ -0,0 +1,8 @@ +int32 id +string cls +float32 sim +int32[4] bbox # [x1,y1,x2,y2] +float32 x +float32 y +float32 z + diff --git a/msg/landmark_array.msg b/msg/landmark_array.msg new file mode 100755 index 0000000..293f9f7 --- /dev/null +++ b/msg/landmark_array.msg @@ -0,0 +1,3 @@ +Header header +landmark[] landmarks + diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..e3ba5f8 --- /dev/null +++ b/package.xml @@ -0,0 +1,74 @@ + + + landmarks_detection + 0.0.0 + The landmarks_detection_ROS package + + + + + quangtrung + + + + + + TODO + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + catkin + cv_bridge + message_generation + rospy + sensor_msgs + std_msgs + cv_bridge + message_generation + rospy + sensor_msgs + std_msgs + cv_bridge + message_runtime + rospy + sensor_msgs + std_msgs + + + + + + + + diff --git a/rviz/landmarks.rviz b/rviz/landmarks.rviz new file mode 100644 index 0000000..7e32433 --- /dev/null +++ b/rviz/landmarks.rviz @@ -0,0 +1,107 @@ +Panels: + - Class: rviz/Displays + Name: Displays + - Class: rviz/Selection + Name: Selection + - Class: rviz/Views + Name: Views + - Class: rviz/Time + Name: Time +Visualization Manager: + Class: "" + Displays: + - Alpha: 0.5 + Cell Size: 1 + Class: rviz/Grid + Color: 160; 160; 160 + Enabled: true + Line Style: + Line Width: 0.03 + Value: Lines + Name: Grid + Normal Cell Count: 0 + Plane: XY + Plane Cell Count: 10 + Reference Frame: + Value: true + - Class: rviz/TF + Enabled: true + Frame Timeout: 15 + Marker Scale: 1 + Name: TF + Show Arrows: true + Show Axes: true + Show Names: true + Tree: {} + Value: true + - Class: rviz/Image + Enabled: true + Image Topic: /camera/color/image_raw + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: Color Image + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Value: true + - Class: rviz/MarkerArray + Enabled: true + Marker Topic: /landmark_markers + Name: Landmarks + Namespaces: {} + Queue Size: 100 + Value: true + Enabled: true + Global Options: + Background Color: 30; 30; 30 + Default Light: true + Fixed Frame: camera_color_optical_frame + Frame Rate: 30 + Name: root + Tools: + - Class: rviz/Interact + - Class: rviz/MoveCamera + - Class: rviz/Select + - Class: rviz/Measure + - Class: rviz/SetInitialPose + - Class: rviz/SetGoal + Views: + Current: + Class: rviz/Orbit + Distance: 3 + Enable Stereo Rendering: + Stereo Eye Separation: 0.06 + Stereo Focal Distance: 1 + Swap Stereo Eyes: false + Value: false + Focal Point: + X: 0 + Y: 0 + Z: 0 + Focal Shape Fixed Size: true + Focal Shape Size: 0.05 + Invert Z Axis: false + Name: 3D View + Near Clip Distance: 0.01 + Pitch: 0.6 + Target Frame: camera_color_optical_frame + Yaw: 0.6 +Window Geometry: + Displays: + collapsed: false + Height: 900 + Hide Left Dock: false + Hide Right Dock: false + QMainWindow State: 0000000000000000 + Selection: + collapsed: false + Time: + collapsed: false + Tool Properties: + collapsed: false + Views: + collapsed: false + Width: 1400 + X: 100 + Y: 50 diff --git a/src/landmark.py b/src/landmark.py new file mode 100755 index 0000000..e9a63df --- /dev/null +++ b/src/landmark.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os, time, pickle, math +import numpy as np +import rospy +from sensor_msgs.msg import Image, CameraInfo +from std_msgs.msg import Header +from visualization_msgs.msg import Marker, MarkerArray +from cv_bridge import CvBridge +import cv2 + +from ultralytics import YOLO +from sklearn.metrics.pairwise import cosine_similarity +from sklearn.cluster import MiniBatchKMeans + +from landmarks_detection_ROS.msg import landmark, landmark_array + +# ==== Config ==== +import rospkg +rospack = rospkg.RosPack() +package_path = rospack.get_path('landmarks_detection') + +YOLO_MODEL_PATH = rospy.get_param("~yolo_model", f"{package_path}/weights/last.pt") +CODEBOOK_PATH = rospy.get_param("~codebook", f"{package_path}/codebook/codebook_kNN.joblib") +IDF_PATH = rospy.get_param("~idf", f"{package_path}/codebook/idf.npy") +CONF_THRES = rospy.get_param("~conf_thres", 0.5) +SIM_THRESH = rospy.get_param("~sim_thresh", 0.12) +SNAP_MAX = rospy.get_param("~snapshots", 7) +USE_DEPTH = rospy.get_param("~use_depth", True) +USE_SURF = rospy.get_param("~use_surf", False) +DEPTH_TOPIC = rospy.get_param("~depth_topic","/camera/aligned_depth_to_color/image_raw") +COLOR_TOPIC = rospy.get_param("~color_topic","/camera/color/image_raw") +INFO_TOPIC = rospy.get_param("~info_topic", "/camera/color/camera_info") +MAX_DEPTH_M = rospy.get_param("~max_depth_m", 6.0) +DEPTH_KERNEL = rospy.get_param("~depth_kernel", 7) +PUBLISH_MARKERS = rospy.get_param("~publish_markers", True) + +# ==== Helpers ==== +bridge = CvBridge() + +class BoVW: + def __init__(self, codebook_path, idf_path): + # load KMeans & IDF + import joblib + self.kmeans = joblib.load(codebook_path) + self.idf = np.load(idf_path).astype(np.float32) # shape (K,) + self.K = self.kmeans.n_clusters + assert self.idf.shape[0] == self.K, "IDF size != n_clusters" + # SIFT (mặc định) hoặc SURF nếu có contrib và ~use_surf=True + if USE_SURF and hasattr(cv2, "xfeatures2d"): + self.det = cv2.xfeatures2d.SURF_create(hessianThreshold=400) + else: + self.det = cv2.SIFT_create(nfeatures=1200) + + def roi_desc(self, gray): + kps, desc = self.det.detectAndCompute(gray, None) + return desc + + def tfidf(self, desc): + # Fallback TEST-style: nếu không có descriptor => trả về None để cấp ID mới + if desc is None or len(desc) == 0: + return None + labels = self.kmeans.predict(desc.astype(np.float32)) + h, _ = np.histogram(labels, bins=np.arange(self.K+1)) + h = h.astype(np.float32) + # TF normalize + s = h.sum() + if s > 0: + h = h / s + # TF-IDF + h *= self.idf + # Hellinger + L2 + h = np.sqrt(np.maximum(h, 0)) + n = np.linalg.norm(h) + 1e-9 + return h / n + +class Memory: + def __init__(self, sim_thresh=0.42, snap_max=7): + self.vecs = [] # list of snapshots (np.array) + self.cls = [] # class id/name + self.ids = [] # landmark ids + self.meta = [] # dict per id (store xyz, etc) + self.next_id = 0 + self.sim_thresh = sim_thresh + self.snap_max = snap_max + + def match(self, cls_name, vec, xyz=None): + # Fallback TEST-style: nếu vec is None => cấp ID mới ngay + if vec is None: + lid = self.next_id; self.next_id += 1 + self.ids.append(lid) + self.cls.append(cls_name) + # Lưu placeholder để giữ vị trí; sẽ được cập nhật khi có vec thực + self.vecs.append(np.zeros(1, dtype=np.float32)) + self.meta.append({"last_xyz": xyz}) + return lid, 0.0 + + best_i, best_sim = -1, -1.0 + for i, v in enumerate(self.vecs): + if self.cls[i] != cls_name: + continue + # Bỏ qua placeholder không khớp kích thước + if v.ndim==1 and v.size!=vec.size: + continue + sim = float(cosine_similarity(vec.reshape(1,-1), v.reshape(1,-1))[0,0]) + if sim > best_sim: + best_sim, best_i = sim, i + if best_sim >= self.sim_thresh and best_i >= 0: + lid = self.ids[best_i] + # EMA update snapshot (0.9 cũ + 0.1 mới) + self.vecs[best_i] = 0.9*self.vecs[best_i] + 0.1*vec + self.vecs[best_i] = self.vecs[best_i] / (np.linalg.norm(self.vecs[best_i]) + 1e-9) + if xyz is not None: + self.meta[best_i]["last_xyz"] = xyz + return lid, best_sim + # new id + lid = self.next_id; self.next_id += 1 + self.ids.append(lid) + self.cls.append(cls_name) + self.vecs.append(vec) + self.meta.append({"last_xyz": xyz}) + return lid, best_sim + +class Node: + def __init__(self): + self.model = YOLO(YOLO_MODEL_PATH) + self.bovw = BoVW(CODEBOOK_PATH, IDF_PATH) + self.mem = Memory(SIM_THRESH, SNAP_MAX) + self.sub_color = rospy.Subscriber(COLOR_TOPIC, Image, self.cb_color, queue_size=1, buff_size=2**22) + self.sub_depth = rospy.Subscriber(DEPTH_TOPIC, Image, self.cb_depth, queue_size=1, buff_size=2**22) if USE_DEPTH else None + self.sub_info = rospy.Subscriber(INFO_TOPIC, CameraInfo, self.cb_info, queue_size=1) + self.pub_lm = rospy.Publisher("landmarks", landmark_array, queue_size=1) + self.pub_mk = rospy.Publisher("landmark_markers", MarkerArray, queue_size=1) if PUBLISH_MARKERS else None + self.depth = None + self.K = None # intrinsics + self.frame_id = "camera_color_optical_frame" + + def cb_info(self, msg): + self.frame_id = msg.header.frame_id or self.frame_id + self.K = (msg.K[0], msg.K[4], msg.K[2], msg.K[5]) # fx, fy, cx, cy + + def cb_depth(self, msg): + d = bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough") + if d.dtype != np.float32: + d = d.astype(np.float32) / (1000.0 if d.dtype==np.uint16 else 1.0) + self.depth = d + + def depth_at_bbox(self, bbox): + if self.depth is None: return None + x1,y1,x2,y2 = bbox + cx, cy = (x1+x2)//2, (y1+y2)//2 + h,w = self.depth.shape + rx1, ry1 = max(0, cx-DEPTH_KERNEL//2), max(0, cy-DEPTH_KERNEL//2) + rx2, ry2 = min(w, cx+DEPTH_KERNEL//2+1), min(h, cy+DEPTH_KERNEL//2+1) + patch = self.depth[ry1:ry2, rx1:rx2] + if patch.size == 0: return None + z = np.nanmedian(np.where((patch>0)&np.isfinite(patch), patch, np.nan)) + if not np.isfinite(z) or z<=0 or z>MAX_DEPTH_M: return None + return float(z), int(cx), int(cy) + + def deproject(self, u,v,z): + if self.K is None: return (0.0,0.0,float(z)) + fx, fy, cx, cy = self.K + X = (u - cx)/fx * z + Y = (v - cy)/fy * z + return float(X), float(Y), float(z) + + def cb_color(self, msg): + im = bridge.imgmsg_to_cv2(msg, "bgr8") + H,W = im.shape[:2] + gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) + + # YOLO + res = self.model.predict(source=im, conf=CONF_THRES, verbose=False) + if not res: return + r = res[0] + if r.boxes is None: return + + lms = [] + markers = [] + now = rospy.Time.now() + + for b in r.boxes: + x1,y1,x2,y2 = map(int, b.xyxy[0].cpu().numpy()) + x1 = max(0,min(W-1,x1)); x2 = max(0,min(W-1,x2)) + y1 = max(0,min(H-1,y1)); y2 = max(0,min(H-1,y2)) + if x2<=x1 or y2<=y1: continue + + cls_id = int(b.cls[0].item()) + cls_name = r.names.get(cls_id, str(cls_id)) + roi = gray[y1:y2, x1:x2] + + desc = self.bovw.roi_desc(roi) + vec = self.bovw.tfidf(desc) + + xyz = None + if USE_DEPTH: + dz = self.depth_at_bbox((x1,y1,x2,y2)) + if dz is not None: + z, cx, cy = dz + xyz = self.deproject(cx,cy,z) + + lm_id, sim = self.mem.match(cls_name, vec, xyz) + + # message + lm = landmark() + lm.id = lm_id + lm.cls = cls_name + lm.sim = float(sim) + lm.bbox = [x1,y1,x2,y2] + if xyz is not None: + lm.x, lm.y, lm.z = xyz + else: + lm.x = lm.y = lm.z = float('nan') + lms.append(lm) + + # marker (optional) + if self.pub_mk: + m = Marker() + m.header = Header(frame_id=self.frame_id, stamp=now) + m.ns = "landmarks" + m.id = lm_id + m.type = Marker.TEXT_VIEW_FACING + m.action = Marker.ADD + # đặt vị trí gần camera nếu không có depth + if xyz is not None: + m.pose.position.x, m.pose.position.y, m.pose.position.z = xyz + else: + m.pose.position.z = 1.0 + m.scale.z = 0.08 + m.color.r, m.color.g, m.color.b, m.color.a = (1.0,1.0,0.0,1.0) + m.text = f"LM#{lm_id} {cls_name} s={sim:.2f}" + markers.append(m) + + # vẽ nhanh cho debug (rqt_image_view sẽ thấy) + cv2.rectangle(im,(x1,y1),(x2,y2),(0,255,0),2) + cv2.putText(im,f"LM#{lm_id} {cls_name} s={sim:.2f}",(x1,max(15,y1-5)), + cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2) + + # Publish landmarks + arr = landmark_array() + arr.header = Header(frame_id=self.frame_id, stamp=now) + arr.landmarks = lms + self.pub_lm.publish(arr) + + if self.pub_mk: + mk = MarkerArray(markers=markers) + self.pub_mk.publish(mk) + + # (tuỳ chọn) hiển thị debug + if rospy.get_param("~show_debug", False): + cv2.imshow("landmarks_detection", im) + cv2.waitKey(1) + +def main(): + rospy.init_node("landmarks_detection_node") + n = Node() + rospy.loginfo("landmarks_detection_node started.") + rospy.spin() + +if __name__ == "__main__": + main() + diff --git a/weights/last.pt b/weights/last.pt new file mode 100644 index 0000000..fc3a0e0 Binary files /dev/null and b/weights/last.pt differ