diff --git a/codebook/codebook_centers.npy b/codebook/codebook_centers.npy new file mode 100644 index 0000000..9c34469 Binary files /dev/null and b/codebook/codebook_centers.npy differ diff --git a/codebook/codebook_idf.npy b/codebook/codebook_idf.npy new file mode 100644 index 0000000..2d5faf8 Binary files /dev/null and b/codebook/codebook_idf.npy differ diff --git a/codebook/codebook_meta.json b/codebook/codebook_meta.json new file mode 100644 index 0000000..31f41d6 --- /dev/null +++ b/codebook/codebook_meta.json @@ -0,0 +1,9 @@ +{ + "k": 4096, + "desc_dim": 128, + "resize_max": 640, + "max_total": 2000000, + "batch_size": 8192, + "max_feats_per_img": 800, + "seed": 0 +} \ No newline at end of file diff --git a/codebook/create_codebook_arm.py b/codebook/create_codebook_arm.py new file mode 100644 index 0000000..9d6b358 --- /dev/null +++ b/codebook/create_codebook_arm.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Create BoVW codebook (MiniBatchKMeans) + IDF cho landmarks (Jetson-friendly). +- Cấu hình ngay bên dưới (không cần tham số dòng lệnh). +- Giảm RAM bằng MiniBatchKMeans + resize ảnh + sample descriptor. +- Mặc định dùng SIFT (128-D). Không fallback sang ORB để tránh sai chiều. +- Xuất: + - _centers.npy (K x 128, trung lập, nạp ở mọi máy) + - _idf.npy (K,) + - _meta.json (metadata K, dim, …) + - (tuỳ chọn) _codebook.joblib (nếu muốn dùng sklearn cùng phiên bản) + +Chạy: + python3 create_codebook_arm.py +""" + +import os, glob, json +import numpy as np +import cv2 +from tqdm import tqdm + +# =========================== +# CẤU HÌNH +# =========================== +# Thư mục ảnh (glob). VD: "../dataset/train/images/*.jpg" +IMG_GLOB = "/home/quangtrung/landmarks_ws/src/landmarks_detection_ROS/dataset/train/images/*.jpg" + +# Số cụm (visual words). 512–4096 tuỳ dữ liệu/khả năng. +K = 4096 + +# Tổng descriptor tối đa để train KMeans (giảm => nhẹ RAM, nhanh hơn). +MAX_TOTAL = 2_000_000 + +# Số descriptor tối đa lấy từ mỗi ảnh. +MAX_FEATS_PER_IMG = 800 + +# Resize ảnh về sao cho max(h, w) = RESIZE_MAX (0 để tắt). +RESIZE_MAX = 640 + +# Batch size cho MiniBatchKMeans. Nano thường 4k–16k. +BATCH_SIZE = 8192 + +# Số lần khởi tạo KMeans (KHÔNG dùng "auto" trên sklearn cũ). +N_INIT = 3 + +# Seed cho reproducibility +SEED = 0 + +# Prefix tên file output +OUT_PREFIX = "codebook" + +# Xuất thêm file .joblib (chỉ nên bật nếu train + infer cùng phiên bản sklearn) +SAVE_JOBLIB = False + +# Tính IDF (nên bật nếu pipeline dùng TF-IDF) +ESTIMATE_IDF = True +# =========================== + + +# sklearn chỉ dùng trong file build (không bắt buộc ở runtime nạp .npy) +from sklearn.cluster import MiniBatchKMeans +import joblib + + +def require_sift(): + """Tạo SIFT 128-D; báo lỗi rõ nếu OpenCV thiếu SIFT (không fallback ORB).""" + try: + sift = cv2.SIFT_create(nfeatures=1200) + except Exception: + sift = None + if sift is None: + raise RuntimeError( + "OpenCV của bạn không có SIFT (opencv-contrib). " + "Hãy cài opencv-contrib hoặc build OpenCV kèm SIFT." + ) + return sift + + +def imread_gray_resized(path, resize_max): + img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + if img is None: + return None + if resize_max and resize_max > 0: + h, w = img.shape[:2] + s = float(resize_max) / max(h, w) + if s < 1.0: + img = cv2.resize(img, (int(w * s), int(h * s))) + return img + + +def sample_descriptors(paths, det, max_total, max_feats_per_img, resize_max): + """Lấy mẫu SIFT descriptor tối đa max_total; giới hạn mỗi ảnh max_feats_per_img.""" + all_desc = [] + total = 0 + for p in tqdm(paths, desc="Extracting descriptors"): + img = imread_gray_resized(p, resize_max) + if img is None: + continue + 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] + desc = desc.astype(np.float32, copy=False) + all_desc.append(desc) + total += len(desc) + if total >= max_total: + break + if not all_desc: + return np.empty((0, 128), np.float32) + return np.vstack(all_desc) + + +def fit_codebook(desc, k, batch_size, seed, n_init): + """Fit MiniBatchKMeans (không dùng n_init='auto' để tương thích sklearn cũ).""" + km = MiniBatchKMeans( + n_clusters=k, + batch_size=batch_size, + reassignment_ratio=0.01, + n_init=n_init, + verbose=1, + random_state=seed, + ) + km.fit(desc) + centers = km.cluster_centers_.astype(np.float32, copy=False) + return km, centers + + +def assign_words(desc, centers): + """Gán mỗi descriptor về trung tâm gần nhất bằng numpy (không phụ thuộc sklearn).""" + if desc is None or len(desc) == 0: + return None + desc = desc.astype(np.float32, copy=False) # (n,128) + a2 = np.sum(desc * desc, axis=1, keepdims=True) # (n,1) + b2 = np.sum(centers * centers, axis=1, keepdims=True).T # (1,K) + ab = desc @ centers.T # (n,K) + dist2 = a2 + b2 - 2.0 * ab # (n,K) + return np.argmin(dist2, axis=1) # (n,) + + +def estimate_idf(paths, det, centers, resize_max): + """ + IDF dựa theo df ảnh: + df[j] = số ảnh có ít nhất 1 từ vựng j + idf[j] = log((N+1)/(df[j]+1)) + """ + K = centers.shape[0] + df = np.zeros(K, dtype=np.float32) + for p in tqdm(paths, desc="Estimating IDF"): + img = imread_gray_resized(p, resize_max) + if img is None: + continue + kps, d = det.detectAndCompute(img, None) + if d is None or len(d) == 0: + continue + words = assign_words(d, centers) + if words is None: + continue + df[np.unique(words)] += 1 + N = float(len(paths)) + idf = np.log((N + 1.0) / (df + 1.0)).astype(np.float32) + return idf + + +def main(): + np.random.seed(SEED) + + paths = sorted(glob.glob(IMG_GLOB, recursive=True)) + assert len(paths) > 0, f"Không tìm thấy ảnh với glob: {IMG_GLOB}" + + sift = require_sift() + + # 1) Lấy mẫu descriptor + desc = sample_descriptors(paths, sift, MAX_TOTAL, MAX_FEATS_PER_IMG, RESIZE_MAX) + print("Descriptors:", desc.shape) + assert desc.shape[0] > 0 and desc.shape[1] == 128, "Descriptor rỗng hoặc không phải 128-D (SIFT)!" + + # 2) Fit codebook + kmeans, centers = fit_codebook(desc, K, BATCH_SIZE, SEED, N_INIT) + + # 3) IDF (tuỳ chọn) + if ESTIMATE_IDF: + idf = estimate_idf(paths, sift, centers, RESIZE_MAX) + else: + idf = np.ones(K, dtype=np.float32) + + # 4) Lưu định dạng trung lập + out_centers = f"{OUT_PREFIX}_centers.npy" + out_idf = f"{OUT_PREFIX}_idf.npy" + out_meta = f"{OUT_PREFIX}_meta.json" + np.save(out_centers, centers) + np.save(out_idf, idf) + meta = dict( + k=int(K), + desc_dim=128, + resize_max=int(RESIZE_MAX), + max_total=int(MAX_TOTAL), + batch_size=int(BATCH_SIZE), + max_feats_per_img=int(MAX_FEATS_PER_IMG), + seed=int(SEED), + ) + with open(out_meta, "w") as f: + json.dump(meta, f, indent=2) + print(f"Saved: {out_centers}, {out_idf}, {out_meta}") + + # 5) (tuỳ chọn) Lưu thêm bản sklearn nếu muốn dùng ngay cùng môi trường này + if SAVE_JOBLIB: + out_joblib = f"{OUT_PREFIX}_codebook.joblib" + joblib.dump(kmeans, out_joblib) + print(f"Also saved: {out_joblib}") + + +if __name__ == "__main__": + main() diff --git a/launch/landmark_arm_update.launch b/launch/landmark_arm_update.launch index 342927d..3d1ed74 100644 --- a/launch/landmark_arm_update.launch +++ b/launch/landmark_arm_update.launch @@ -10,8 +10,8 @@ - - + + diff --git a/src/landmark_arm_update.py b/src/landmark_arm_update.py index 84124ec..9ff9095 100644 --- a/src/landmark_arm_update.py +++ b/src/landmark_arm_update.py @@ -21,26 +21,32 @@ except Exception: torch = None from ultralytics import YOLO -from sklearn.metrics.pairwise import cosine_similarity +# from sklearn.metrics.pairwise import cosine_similarity # ===== messages from landmarks_detection_ROS.msg import landmark, landmark_array # ==== Config & paths (ARM-safe defaults) + import rospkg - rospack = rospkg.RosPack() -# Prefer local package assets to avoid cross-package path confusion on devices -try: - package_path = rospack.get_path(rospy.get_param("~ros_package_name", "landmarks_detection_ROS")) +package_path = rospack.get_path("landmarks_detection") + +# === Cosine similarity thuần numpy (thay cho sklearn.metrics.pairwise.cosine_similarity) === +def cos_sim(a: np.ndarray, b: np.ndarray) -> float: + """ + Trả về cosine similarity giữa 2 vector a và b. + Không phụ thuộc sklearn (phù hợp Jetson Nano). + """ + na = np.linalg.norm(a) + 1e-9 + nb = np.linalg.norm(b) + 1e-9 + return float(np.dot(a, b) / (na * nb)) -except rospkg.ResourceNotFound: - package_path = rospack.get_path("landmarks_detection") # Model/codebook defaults (override via ROS params in launch) 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") +CODEBOOK_PATH = rospy.get_param("~codebook", f"{package_path}/codebook/codebook_centers.npy") +IDF_PATH = rospy.get_param("~idf", f"{package_path}/codebook/codebook_idf.npy") # Jetson-specific knobs CUDA_OK = TORCH_AVAILABLE and torch.cuda.is_available() @@ -92,41 +98,79 @@ bridge = CvBridge() # BoVW encoder # ========================= class BoVW: - def __init__(self, codebook_path, idf_path): - self.kmeans = joblib.load(codebook_path) - self.idf = np.load(idf_path).astype(np.float32) - self.K = int(self.kmeans.n_clusters) - assert self.idf.shape[0] == self.K, "IDF size != n_clusters" - # detector: SIFT mặc định, SURF nếu bật (ARM: keep lightweight) - if USE_SURF and hasattr(cv2, "xfeatures2d"): - self.det = cv2.xfeatures2d.SURF_create(hessianThreshold=400) - self.desc_dim = 64 - else: - # SIFT may not be compiled in some OpenCV builds; try/except - try: - self.det = cv2.SIFT_create(nfeatures=int(SIFT_NFEAT)) - self.desc_dim = 128 - except Exception as e: - rospy.logwarn_throttle(10.0, f"SIFT unavailable on this build: {e}. BoVW may not work with current codebook.") - # Fallback to ORB to avoid crash; descriptor dims won't match trained codebook - self.det = cv2.ORB_create(nfeatures=int(max(500, SIFT_NFEAT))) - self.desc_dim = 32 + def __init__(self, centers_path, idf_path): + self.centers = None + self.idf = None + self.K = 0 + self.desc_dim = 128 + + # Load centers (.npy) & idf (.npy) + try: + if os.path.isfile(centers_path) and centers_path.endswith(".npy"): + self.centers = np.load(centers_path).astype(np.float32) # (K,128) + else: + rospy.logwarn("codebook path không phải .npy: '%s'. Hãy dùng *_centers.npy do create_codebook_arm.py sinh ra.", centers_path) + except Exception as e: + rospy.logwarn("Không load được centers '%s': %s", centers_path, str(e)) + + try: + if os.path.isfile(idf_path) and idf_path.endswith(".npy"): + self.idf = np.load(idf_path).astype(np.float32) # (K,) + else: + rospy.logwarn("idf path không phải .npy: '%s'. Hãy dùng *_idf.npy", idf_path) + except Exception as e: + rospy.logwarn("Không load được idf '%s': %s", idf_path, str(e)) + + if self.centers is not None: + self.K = int(self.centers.shape[0]) + self.desc_dim = int(self.centers.shape[1]) + if self.idf is not None and self.K > 0 and self.idf.shape[0] != self.K: + rospy.logwarn("IDF size (%d) != K (%d). Sẽ bỏ qua IDF.", self.idf.shape[0], self.K) + self.idf = None + + # detector: SIFT -> 128-D; nếu thiếu SIFT sẽ fallback ORB (32-D) nhưng khi đó BoVW sẽ bỏ qua (mismatch dim) + try: + self.det = cv2.SIFT_create(nfeatures=int(SIFT_NFEAT)) + self.desc_dim_expected = 128 + except Exception as e: + rospy.logwarn_throttle(10.0, "SIFT unavailable: %s. Sẽ dùng ORB (32-D).", str(e)) + self.det = cv2.ORB_create(nfeatures=int(max(500, SIFT_NFEAT))) + self.desc_dim_expected = 32 + + if self.centers is None: + rospy.logwarn("BoVW tạm TẮT vì không có centers.npy. YOLO vẫn chạy bình thường.") def roi_desc(self, gray): kps, desc = self.det.detectAndCompute(gray, None) return desc - def tfidf(self, desc): - if desc is None or len(desc) == 0: + def _assign_words(self, desc: np.ndarray): + # Gán mỗi descriptor về trung tâm gần nhất bằng numpy + if desc is None or len(desc) == 0 or self.centers is None: 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 -> IDF -> Hellinger -> L2 - s = h.sum() + if desc.shape[1] != self.desc_dim_expected or self.centers.shape[1] != self.desc_dim_expected: + # Mismatch chiều descriptor → bỏ qua để không crash + return None + desc = desc.astype(np.float32, copy=False) # (n,D) + a2 = np.sum(desc * desc, axis=1, keepdims=True) # (n,1) + b2 = np.sum(self.centers * self.centers, axis=1, keepdims=True).T # (1,K) + ab = desc @ self.centers.T # (n,K) + dist2 = a2 + b2 - 2.0 * ab # (n,K) + return np.argmin(dist2, axis=1) # (n,) + + def tfidf(self, desc): + if self.centers is None: + return None + words = self._assign_words(desc) + if words is None: + return None + h = np.bincount(words, minlength=self.K).astype(np.float32) # (K,) + s = float(h.sum()) if s > 0: - h /= s - h *= self.idf + h /= s # TF + if self.idf is not None and self.idf.shape[0] == self.K: + h *= self.idf # TF-IDF + # Hellinger + L2 h = np.sqrt(np.maximum(h, 0)) n = np.linalg.norm(h) + 1e-9 return h / n @@ -163,7 +207,7 @@ class Memory: return self.vecs[lid] def _cosine(self, a, b): - return float(cosine_similarity(a.reshape(1,-1), b.reshape(1,-1))[0,0]) + return cos_sim(a, b) def _spatial_score(self, sim, xyz, lid): s_app = max(0.0, min(1.0, sim))