lamp-triangulation / scripts /lamp_id_tracking.py
ngocleltt's picture
Upload 7 files
035b725 verified
import csv
import re
from pathlib import Path
try:
from PIL import Image
except ImportError:
raise ImportError("Not found pillow. Try pip install pillow")
root_dir = Path('.')
labels_dir = root_dir / 'frames/labels'
images_dir = root_dir / 'frames/images'
output_csv = root_dir / 'lamp_tracks_15.csv'
summary_csv = root_dir / 'lamp_tracks_15_summary.csv'
if not labels_dir.exists():
raise FileNotFoundError(f"Not found folder labels: {labels_dir.resolve()}")
if not images_dir.exists():
raise FileNotFoundError(f"Not found folder images: {images_dir.resolve()}")
lamp_ranges = [
(1, 8, 12),
(2, 8, 18),
(3, 16, 25),
(4, 24, 33),
(5, 33, 40),
(6, 40, 48),
(7, 53, 56),
(8, 54, 63),
(9, 60, 71),
(10, 66, 76),
(11, 70, 81),
(12, 85, 94),
(13, 85, 101),
(14, 97, 111),
(15, 105, 117),
]
image_exts = ['.jpg', '.jpeg', '.png', '.bmp', '.webp']
class_map = {0: 'lamp_on', 1: 'lamp_off', 2: 'lamp_occluded'}
def extract_frame_number(filename):
stem = Path(filename).stem
m = re.search(r'_(\d+)$', stem)
if not m:
return None
return int(m.group(1))
def find_image(stem):
for ext in image_exts:
p = images_dir / f'{stem}{ext}'
if p.exists():
return p
return None
def yolo_to_xyxy(xc, yc, w, h, img_w, img_h):
x1 = (xc - w / 2) * img_w
y1 = (yc - h / 2) * img_h
x2 = (xc + w / 2) * img_w
y2 = (yc + h / 2) * img_h
return x1, y1, x2, y2
def center_of(box):
x1, y1, x2, y2 = box
return ((x1 + x2) / 2, (y1 + y2) / 2)
def active_lamps(frame_num):
return [lid for lid, start, end in lamp_ranges if start <= frame_num <= end]
label_files = sorted(
labels_dir.glob('*.txt'),
key=lambda p: (extract_frame_number(p.name) is None, extract_frame_number(p.name) or 10**9, p.name)
)
rows = []
summary = []
for label_file in label_files:
stem = label_file.stem
frame_num = extract_frame_number(label_file.name)
image_path = find_image(stem)
if frame_num is None:
print(f'Reading frame error in file: {label_file.name}')
continue
if image_path is None:
print(f'Not found frame in file {label_file.name}')
continue
with Image.open(image_path) as img:
img_w, img_h = img.size
detections = []
with open(label_file, 'r', encoding='utf-8') as f:
for line_idx, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
parts = line.split()
if len(parts) < 5:
print(f'Format error {label_file.name}: {line}')
continue
cls = int(float(parts[0]))
xc, yc, w, h = map(float, parts[1:5])
box = yolo_to_xyxy(xc, yc, w, h, img_w, img_h)
cx, cy = center_of(box)
detections.append({
'class_id': cls,
'box': box,
'center': (cx, cy),
'line_idx': line_idx,
})
active = active_lamps(frame_num)
dets_sorted = sorted(detections, key=lambda d: d['center'][0])
lamps_sorted = sorted(active)
if len(lamps_sorted) == 0:
summary.append({
'frame_number': frame_num,
'file_name': image_path.name,
'active_lamps': '',
'assigned_track_ids': '',
'num_detections': len(detections),
'num_assigned': 0,
'note': 'no_active_lamp_in_manual_range',
})
continue
assigned = []
if len(dets_sorted) <= len(lamps_sorted):
for det, lid in zip(dets_sorted, lamps_sorted):
assigned.append((lid, det))
else:
for i, det in enumerate(dets_sorted):
lid = lamps_sorted[i % len(lamps_sorted)]
assigned.append((lid, det))
visible_ids = []
for lid, det in assigned:
x1, y1, x2, y2 = det['box']
visible_ids.append(str(lid))
rows.append({
'frame_number': frame_num,
'file_name': image_path.name,
'label_file': label_file.name,
'track_id': lid,
'class_id': det['class_id'],
'class_name': class_map.get(det['class_id'], f'class_{det["class_id"]}'),
'x1': round(x1, 2),
'y1': round(y1, 2),
'x2': round(x2, 2),
'y2': round(y2, 2),
'cx': round(det['center'][0], 2),
'cy': round(det['center'][1], 2),
'bbox_w': round(x2 - x1, 2),
'bbox_h': round(y2 - y1, 2),
})
summary.append({
'frame_number': frame_num,
'file_name': image_path.name,
'active_lamps': ' '.join(map(str, lamps_sorted)),
'assigned_track_ids': ' '.join(visible_ids),
'num_detections': len(detections),
'num_assigned': len(assigned),
'note': '',
})
fieldnames = [
'frame_number', 'file_name', 'label_file', 'track_id', 'class_id', 'class_name',
'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'bbox_w', 'bbox_h'
]
with open(output_csv, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
summary_fields = [
'frame_number', 'file_name', 'active_lamps', 'assigned_track_ids',
'num_detections', 'num_assigned', 'note'
]
with open(summary_csv, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=summary_fields)
writer.writeheader()
writer.writerows(summary)
print(f'Created: {output_csv}')
print(f'Created: {summary_csv}')
print(f'Sum of detections: {len(rows)}')
print(f'Lamps count: {len(lamp_ranges)}')