170 lines
5.7 KiB
Python
170 lines
5.7 KiB
Python
import json, random, csv
|
|
from collections import defaultdict
|
|
from pathlib import Path
|
|
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 optimization_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)
|