TensorFlow
Object Detection
API
Terminal Output
Machine Learning

Tensorflow Object detection API Print detected class as output to terminal

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Printing detected classes to terminal output is a practical way to validate TensorFlow object detection pipelines during development. It confirms that preprocessing, model inference, and label mapping are wired correctly before adding visualization layers. A reliable terminal output path is also useful for server side inference jobs without GUI support.

End To End Detection Output Flow

A typical flow is:

  1. Load SavedModel.
  2. Load label map from id to class name.
  3. Run inference on an input tensor.
  4. Filter detections by score threshold.
  5. Print class names and confidence values.
python
1import tensorflow as tf
2import numpy as np
3
4# Example label map for demonstration
5LABELS = {1: "person", 2: "bicycle", 3: "car"}
6
7def print_detections(detection_output, threshold=0.5):
8    classes = detection_output["detection_classes"][0].numpy().astype(np.int32)
9    scores = detection_output["detection_scores"][0].numpy()
10
11    for cls_id, score in zip(classes, scores):
12        if score < threshold:
13            continue
14        name = LABELS.get(int(cls_id), f"unknown_{cls_id}")
15        print(f"detected={name} score={score:.3f}")

This helper prints readable class names instead of raw numeric ids.

Running Inference Correctly

The model expects input with batch dimension. Normalize and shape your image tensor before prediction.

python
1import tensorflow as tf
2import numpy as np
3
4# Dummy image for runnable example
5image = np.zeros((480, 640, 3), dtype=np.uint8)
6input_tensor = tf.convert_to_tensor(image)[tf.newaxis, ...]
7
8# Example model placeholder function
9@tf.function
10def fake_model(x):
11    return {
12        "detection_classes": tf.constant([[1.0, 3.0, 2.0]]),
13        "detection_scores": tf.constant([[0.95, 0.77, 0.32]])
14    }
15
16outputs = fake_model(input_tensor)
17print_detections(outputs, threshold=0.5)

In production, replace fake_model with the loaded object detection SavedModel callable.

Thresholding And Label Hygiene

Score threshold selection depends on application tolerance for false positives versus false negatives. Start with a moderate threshold and evaluate on representative data. Also keep label maps versioned with the model so class id alignment does not drift.

If class names print as unknown values, inspect the model label map and ensure ids match training configuration. Mismatched mappings are common when swapping checkpoints.

Logging For Batch And Service Workloads

For streaming inference, prefer structured logs instead of plain print statements. Include frame id, model version, class name, and score. Structured fields improve observability and simplify downstream analytics.

Rate limit logs for high frame rate pipelines. Printing every detection at full rate can overwhelm I O and distort latency measurements.

Real Model Loading And Label Parsing

In production scripts, load the exported SavedModel once at process start and reuse it for all frames. Re loading per frame adds heavy latency and can hide true inference performance.

For label maps, keep parsing logic deterministic. Whether labels come from protobuf text, JSON, or CSV, validate that class ids are unique and contiguous as expected by your training setup. Emit a startup warning if detected ids in output exceed known label range.

If your pipeline processes batches, print aggregated class counts per window instead of one line per detection. Aggregated output is easier to monitor and much cheaper for high throughput workloads. Pair this with sampling so detailed per detection logs can be enabled temporarily during debugging without overwhelming storage.

Common Pitfalls

  • Printing raw class ids without label map translation.
  • Forgetting batch dimension on model input.
  • Using thresholds that are too low and flooding output with noise.
  • Mixing label maps from different model checkpoints.
  • Logging at unbounded volume in production inference loops.

Summary

  • Terminal class output is a valuable debugging and monitoring signal.
  • Translate class ids to names using a synchronized label map.
  • Shape input tensors correctly and apply score filtering.
  • Prefer structured logs for production scale workloads.
  • Keep model and label artifacts version aligned.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.