update param tuning and first results

This commit is contained in:
Johannes Waltmann
2025-08-28 14:05:04 +02:00
parent 72dee5bdfc
commit eadcde76e7
13 changed files with 401 additions and 47 deletions
+4 -3
View File
@@ -1,4 +1,5 @@
/data
/.idea
*pt
findings_test.json
/data
/extracted_features
/splits
*pt
+20 -2
View File
@@ -1,5 +1,23 @@
# trials.py
# Parameter Tuning for Object Re-Identification
Reads all frames per camera position and merges them into panoramic image.\
Contains different preprocessing and training scripts to optimize different parameters needed for object re-identification.
Data generated is used to employ object re-identification to a scene graph as part of the implementation work during a masters thesis.
Training and analysis is performed on multiple scenes out of the Matterport 3D dataset.
## panorama_viewer
Reads all frames per camera position and merges them into panoramic image.
Code converted from matlab as seen in https://github.com/yindaz/PanoBasic/blob/master/demo_matterport.m
## object_features_detector
Reads all image frames from a Matterport scene and performs an object and feature detection on each image.
Uses the exact code from the scene graph pipeline adapted to standard python from the ros environment.
## build_training_data
Generates a train/test split for each scene.
Contains 80% training and 20% testing data.
Each data split is organized pair-wise.
Splits include pairings for both positive and negative re-identification.
## reID_param_tuning
Optimizes the parameters alpha, beta and the similarity_threshold based on a grid search.
Binary file not shown.
+170
View File
@@ -0,0 +1,170 @@
import json, random, csv
from collections import defaultdict
from pathlib import Path
from typing import List, Dict, Any
import numpy as np
from sklearn.cluster import KMeans
from tqdm import tqdm
RNG_SEED = 42
random.seed(RNG_SEED)
np.random.seed(RNG_SEED)
def load_findings(json_path):
""" Data Loader """
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
return data
def build_cluster_identities(annotations, min_instances: int = 2, n_clusters_per_class: int = 30):
""" Remove all singular occurrences """
occurrences_by_class = defaultdict(list)
for entry in annotations:
frame_id = entry["frame_id"]
for idx, o in enumerate(entry.get("objects", [])):
occ = {
"frame_id": frame_id,
"object_idx": idx,
"class_name": o["class_name"],
"bounding_box": o["bounding_box"],
"segments": o["segments"],
"clip_embedding": np.asarray(o["clip_embedding"]) if o["clip_embedding"] else None,
"color_histogram": np.asarray(o["color_histogram"]) if o["color_histogram"] else None,
}
occurrences_by_class[o["class_name"]].append(occ)
identities = defaultdict(list)
for cls, occs in occurrences_by_class.items():
embs = [o["clip_embedding"] for o in occs if o["clip_embedding"] is not None]
if not embs:
for i, o in enumerate(occs):
iid = f"{cls}_pseudo_{i}"
identities[iid].append(o)
continue
X = np.vstack(embs)
k = min(n_clusters_per_class, max(1, len(occs)//2))
kmeans = KMeans(n_clusters=k, random_state=RNG_SEED)
labels = kmeans.fit_predict(X)
emb_idx = 0
for o in occs:
if o["clip_embedding"] is None:
iid = f"{cls}_noclip_{random.randrange(1000000)}"
else:
iid = f"{cls}_cluster_{labels[emb_idx]}"
emb_idx += 1
identities[iid].append(o)
# filter
identities = {iid: occs for iid, occs in identities.items() if len(occs) >= min_instances}
return identities
def split_identities(identities, train_frac=0.8, test_frac=0.2):
""" Split Data in train and test """
ids = list(identities.keys())
random.shuffle(ids)
n = len(ids)
n_train = int(n*train_frac)
return (
{i: identities[i] for i in ids[:n_train]},
{i: identities[i] for i in ids[n_train:]},
)
def make_pairs(split_ids, other_pool=None, n_pos=20, n_neg=20, hard_neg=True):
""" Build pairings with positive or negative Re-ID results """
pairs = []
neg_source = other_pool if other_pool else split_ids
for iid, occs in split_ids.items():
if len(occs) < 2:
continue
# Positives
for _ in range(n_pos):
a, b = random.sample(occs, 2)
pairs.append({
"img1": a["frame_id"], "clip1": a["clip_embedding"], "hist1": a["color_histogram"],
"img2": b["frame_id"], "clip2": b["clip_embedding"], "hist2": b["color_histogram"],
"label": 1, "identity": iid
})
# Negatives
for _ in range(n_neg):
neg_candidates = [nid for nid in neg_source if nid != iid]
if not neg_candidates:
continue
if hard_neg:
same_class = [nid for nid, ocs in neg_source.items()
if ocs and ocs[0]["class_name"] == occs[0]["class_name"] and nid != iid]
if same_class:
neg_id = random.choice(same_class)
else:
neg_id = random.choice(neg_candidates)
else:
neg_id = random.choice(neg_candidates)
neg_occ = random.choice(neg_source[neg_id])
pos_occ = random.choice(occs)
pairs.append({
"img1": pos_occ["frame_id"], "clip1": pos_occ["clip_embedding"], "hist1": pos_occ["color_histogram"],
"img2": neg_occ["frame_id"], "clip2": neg_occ["clip_embedding"], "hist2": neg_occ["color_histogram"],
"label": 0, "pos_identity": iid, "neg_identity": neg_id
})
random.shuffle(pairs)
return pairs
def save_pairs(pairs, path):
""" Save data """
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
"img1", "clip1", "hist1",
"img2", "clip2", "hist2",
"label"
])
for pair in pairs:
writer.writerow([
pair["img1"],
pair["clip1"].tolist(),
pair["hist1"].tolist(),
pair["img2"],
pair["clip2"].tolist(),
pair["hist2"].tolist(),
pair["label"]
])
if __name__ == "__main__":
scene_ids = [
"2t7WUuJeko7",
"PX4nDJXEHrG",
"q9vSo1VnCiC",
"Vvot9Ly1tCj",
"zsNo4HB9uLZ"
]
for scene_id in tqdm(scene_ids):
anns = load_findings(f"extracted_features/{scene_id}_features.json")
identities = build_cluster_identities(anns, min_instances=2, n_clusters_per_class=30)
train_ids, test_ids = split_identities(identities)
train_pairs = make_pairs(train_ids, n_pos=20, n_neg=20)
test_pairs = make_pairs(test_ids, other_pool=train_ids, n_pos=10, n_neg=50)
_dir = Path("splits")
_dir.mkdir(parents=True, exist_ok=True)
path_train = _dir / f"{scene_id}" / "train_pairs.csv"
path_test = _dir / f"{scene_id}" / "test_pairs.csv"
save_pairs(train_pairs, path_train)
save_pairs(test_pairs, path_test)
+21 -42
View File
@@ -2,14 +2,13 @@ import json
import os
from dataclasses import dataclass
from ultralytics import YOLO
import clip # Import OpenAI Model pip install git+https://github.com/openai/CLIP.git
import clip # Import OpenAI Model pip install git+https://github.com/openai/CLIP.git
import cv2
import torch
import numpy as np
import torch
from tqdm import tqdm
from PIL import Image as PIL_Image
import time
from ultralytics import YOLO
device = "cuda" if torch.cuda.is_available() else "cpu"
yolo_model = YOLO('yolov9e-seg.pt')
@@ -18,35 +17,22 @@ clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)
@dataclass
class DetectedObject:
class_name: str
top_corner: tuple
bottom_corner: tuple
bounding_box: list[tuple]
segments: list[tuple]
clip_embedding: np.ndarray
color_histogram: np.ndarray
def detected_Object_to_dict(obj: DetectedObject):
def detected_object_to_dict(obj: DetectedObject):
return {
"class_name": obj.class_name,
"top_corner": list(obj.top_corner),
"bottom_corner": list(obj.bottom_corner),
"bounding_box": [list(coords) for coords in obj.bounding_box],
"segments": [list(seg) for seg in obj.segments],
"clip_embedding": obj.clip_embedding.tolist(),
"color_histogram": obj.color_histogram.tolist(),
}
def dict_to_detected_object(d: dict):
return DetectedObject(
class_name=d["class_name"],
top_corner=tuple(d["top_corner"]),
bottom_corner=tuple(d["bottom_corner"]),
segments=[tuple(seg) for seg in d["segments"]],
clip_embedding=np.array(d["clip_embedding"]),
color_histogram=np.array(d["color_histogram"]),
)
def get_color_histogram(image_mask):
hsv_conversion = cv2.cvtColor(image_mask, cv2.COLOR_BGR2HSV)
@@ -93,8 +79,7 @@ def object_and_feature_detection(image_path: str):
detected_objects.append(
DetectedObject(
class_name=class_name,
top_corner=(x1, y1),
bottom_corner=(x2, y2),
bounding_box=[(x1, y1, 0.0), (x2, y2, 0.0)],
segments=[],
clip_embedding=clip_embedding,
color_histogram=np.ndarray(0)
@@ -103,7 +88,6 @@ def object_and_feature_detection(image_path: str):
indices.append(i)
h2, w2, _ = results[0].orig_img.shape
masks = None
lower_black = np.array([0, 0, 0])
upper_black = np.array([0, 0, 1])
@@ -134,20 +118,6 @@ def object_and_feature_detection(image_path: str):
return detected_objects
def read_json(json_path: str):
with open(json_path, "r") as f:
raw = json.load(f)
data = [
{
"frame_id": entry["frame_id"],
"objects": [dict_to_detected_object(o) for o in entry["objects"]],
}
for entry in raw
]
return data
def run_detection(directory: str):
detected_objects = []
@@ -156,7 +126,7 @@ def run_detection(directory: str):
detections = object_and_feature_detection(os.path.join(directory, filename))
detected_objects.append({
"frame_id": filename,
"objects": [detected_Object_to_dict(d) for d in detections]
"objects": [detected_object_to_dict(d) for d in detections]
})
@@ -169,7 +139,16 @@ def write_json(content, file_name):
if __name__ == "__main__":
PATH = "17DRP5sb8fy/matterport_color_images/17DRP5sb8fy/_/matterport_color_images/"
findings = run_detection(PATH)
scene_ids = [
"2t7WUuJeko7",
"PX4nDJXEHrG",
"q9vSo1VnCiC",
"Vvot9Ly1tCj",
"zsNo4HB9uLZ"
]
write_json(findings, "findings_test.json")
for scene_id in tqdm(scene_ids):
PATH = f"data/{scene_id}/matterport_color_images/{scene_id}/matterport_color_images/"
findings = run_detection(PATH)
write_json(findings, f"extracted_features/{scene_id}_features.json")
+116
View File
@@ -0,0 +1,116 @@
import json
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score, accuracy_score
from tqdm import tqdm
import utils
def load_pairs(path):
""" Data Loader """
df = pd.read_csv(path)
pairs = []
for _, row in df.iterrows():
pairs.append({
"clip1": np.array(eval(row["clip1"])),
"hist1": np.array(eval(row["hist1"])),
"clip2": np.array(eval(row["clip2"])),
"hist2": np.array(eval(row["hist2"])),
"label": int(row["label"])
})
return pairs
def _range(steps=0.05):
""" Value Range in [0:1] with stepsize 0.05 """
values = np.arange(0.0, 1.0 + 1e-9, steps)
return np.round(values, 8)
def grid_search(train_pairs, alphas=None, thresholds=None):
""" Find best feature weights and threshold on training pairings """
if alphas is None:
alphas = _range()
if thresholds is None:
thresholds = _range()
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(train_pairs)
best = {"alpha": None, "beta": None, "threshold": None, "f1": -1.0}
for alpha in alphas:
beta = 1 - alpha
scores = alpha * cosine_similarities + beta * bhattarcharyya_coefficients
for thresh in thresholds:
predictions = (scores >= thresh).astype(int)
f1 = f1_score(labels, predictions, zero_division=0)
if f1 > best["f1"]:
best = {"alpha": float(alpha), "beta": float(beta), "threshold": float(thresh), "f1": float(f1)}
return best
def evaluate(test_pairs, alpha, beta, threshold):
""" Calculate Accuracy + f1 Score on test pairings """
cosine_similarities, bhattarcharyya_coefficients, labels = calc_features(test_pairs)
scores = alpha * cosine_similarities + beta * bhattarcharyya_coefficients
predictions = (scores >= threshold).astype(int)
accuracy = accuracy_score(labels, predictions)
f1 = f1_score(labels, predictions, zero_division=0)
return accuracy, f1
def calc_features(pairs):
""" Re-Identification Features per object Pairing """
# TODO: COS_SIM immer 0=<1
cos_sims = np.array([np.maximum(0.0, utils.cosine_similarity(p["clip1"], p["clip2"])) for p in pairs], dtype=float)
bhatts = np.array([utils.bhattarcharyya_coefficient(p["hist1"], p["hist2"]) for p in pairs], dtype=float)
labels = np.array([p["label"] for p in pairs], dtype=int)
return cos_sims, bhatts, labels
if __name__ == "__main__":
scene_ids = [
"17DRP5sb8fy",
"2t7WUuJeko7",
"PX4nDJXEHrG",
"q9vSo1VnCiC",
"Vvot9Ly1tCj",
"zsNo4HB9uLZ"
]
for scene_id in tqdm(scene_ids):
train_pairs = load_pairs(f"splits/{scene_id}/train_pairs.csv")
best = grid_search(train_pairs)
print(f"Best training combination: {best}")
test_pairs = load_pairs(f"splits/{scene_id}/test_pairs.csv")
accuracy, f1 = evaluate(test_pairs, best["alpha"], best["beta"], best["threshold"])
print(f'Test accuracy: {accuracy:.2f}, F1 score: {f1:.2f}')
out_dir = Path("results")
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"training_{scene_id}.json"
with open(out_path, "w", encoding="utf-8") as f:
json.dump(
{
"alpha": round(best["alpha"], 2),
"beta": round(best["beta"], 2),
"threshold": round(best["threshold"], 2),
"train_f1": round(best["f1"], 2),
"test_accuracy": round(accuracy, 2),
"test_f1": round(f1, 2),
}, f, indent=4)
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 0.95,
"beta": 0.05,
"threshold": 0.85,
"train_f1": 0.86,
"test_accuracy": 0.74,
"test_f1": 0.55
}
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 0.95,
"beta": 0.05,
"threshold": 0.85,
"train_f1": 0.84,
"test_accuracy": 0.78,
"test_f1": 0.58
}
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 0.9,
"beta": 0.1,
"threshold": 0.8,
"train_f1": 0.82,
"test_accuracy": 0.72,
"test_f1": 0.52
}
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 0.95,
"beta": 0.05,
"threshold": 0.85,
"train_f1": 0.85,
"test_accuracy": 0.81,
"test_f1": 0.61
}
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 1.0,
"beta": 0.0,
"threshold": 0.85,
"train_f1": 0.85,
"test_accuracy": 0.78,
"test_f1": 0.57
}
+8
View File
@@ -0,0 +1,8 @@
{
"alpha": 1.0,
"beta": 0.0,
"threshold": 0.85,
"train_f1": 0.86,
"test_accuracy": 0.76,
"test_f1": 0.58
}
+22
View File
@@ -0,0 +1,22 @@
import numpy as np
def bhattarcharyya_coefficient(distribution_1, distribution_2):
"""
Computes the difference between two normalized statistical distributions.
E.g. of two color histograms.
Smaller values indicate higher similarity.
"""
value1 = distribution_1 / np.sum(distribution_1)
value2 = distribution_2 / np.sum(distribution_2)
return np.sum(np.sqrt(value1 * value2))
def cosine_similarity(vector_1, vector_2):
"""
Calculates the cosine similarity of two vectors.
Higher values indicate more alike vectors.
"""
return np.dot(vector_1, vector_2) / (np.linalg.norm(vector_1) * np.linalg.norm(vector_2))