TensorFlow
Object Detection
API
Image Processing
Machine Learning

TensorFlow Object Detection API print objects found on image to console

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When using the TensorFlow Object Detection API, printing detected objects to console is often the first debugging milestone before building UI overlays or downstream automation. The basic flow is: load model, run inference on an image tensor, parse detection outputs, apply confidence threshold, and map class IDs to readable labels. Most confusion comes from output tensor shapes and confidence filtering.

This article provides a practical inference-and-print pipeline for single images using TensorFlow 2 style saved models.

Core Sections

1. Load detection model and label map

python
1import tensorflow as tf
2
3model = tf.saved_model.load("exported-model/saved_model")
4detect_fn = model.signatures["serving_default"]
5
6label_map = {
7    1: "person",
8    2: "bicycle",
9    3: "car",
10}

In real projects, parse label_map.pbtxt instead of hardcoding.

2. Prepare image tensor

python
1import cv2
2import numpy as np
3
4image_bgr = cv2.imread("test.jpg")
5image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
6input_tensor = tf.convert_to_tensor(image_rgb)[tf.newaxis, ...]

Model expects shape [1, H, W, 3].

3. Run inference and extract outputs

python
1outputs = detect_fn(input_tensor)
2
3boxes = outputs["detection_boxes"][0].numpy()
4classes = outputs["detection_classes"][0].numpy().astype(int)
5scores = outputs["detection_scores"][0].numpy()
6num = int(outputs["num_detections"][0])

Only the first num entries are valid detections.

4. Print detections above threshold

python
1threshold = 0.5
2for i in range(num):
3    if scores[i] < threshold:
4        continue
5    cls = classes[i]
6    name = label_map.get(cls, f"class_{cls}")
7    print(f"detected={name} score={scores[i]:.3f} box={boxes[i].tolist()}")

Thresholding removes low-confidence noise.

5. Convert normalized boxes to pixel coordinates

Detection boxes are normalized [ymin, xmin, ymax, xmax].

python
1h, w, _ = image_rgb.shape
2ymin, xmin, ymax, xmax = boxes[i]
3left, top = int(xmin * w), int(ymin * h)
4right, bottom = int(xmax * w), int(ymax * h)

This is useful if you later draw boxes with OpenCV.

6. Batch and logging patterns for pipelines

For batch jobs, print structured logs for downstream parsers.

python
1import json
2print(json.dumps({
3    "file": "test.jpg",
4    "objects": [
5        {"class": label_map.get(classes[i], str(classes[i])), "score": float(scores[i])}
6        for i in range(num) if scores[i] >= threshold
7    ]
8}))

Structured console output scales better than ad-hoc print strings.

Common Pitfalls

  • Forgetting batch dimension and passing [H, W, 3] instead of [1, H, W, 3].
  • Interpreting detection arrays without slicing to num_detections.
  • Printing raw class IDs without label map resolution.
  • Using very low threshold and flooding logs with false positives.
  • Confusing normalized box coordinates with pixel-space coordinates.

Summary

To print objects found by TensorFlow Object Detection API, run inference on a batched image tensor, parse class/score/box tensors, filter by confidence, and map class IDs to labels. Add coordinate conversion and structured logging when moving from debugging to production pipelines. With a consistent parsing routine, console output becomes a reliable foundation for object-detection workflows.

For teams maintaining tensorflow object detection api print objects found on image to console in long-lived codebases, reliability improves when implementation guidance is paired with a lightweight verification routine. A practical pattern is to define three test categories up front. First, happy-path tests that validate normal expected inputs. Second, boundary tests that include empty values, minimum and maximum limits, and malformed records from real logs. Third, operational tests that simulate production-like behavior under retries, parallel execution, and partial failure. This combination catches both obvious logic defects and the subtle integration issues that usually appear after deployment.

It is also useful to encode assumptions close to the code rather than leaving them in scattered documentation. Add short comments where invariants matter, keep helper utilities centralized, and avoid repeating slightly different logic in multiple modules. In CI, run a small deterministic suite on every commit and a broader dataset suite on schedule. When incidents occur, convert the failing scenario into a permanent regression test before patching. Over time this creates a strong feedback loop where tensorflow object detection api print objects found on image to console behavior remains stable even as dependencies, framework versions, and team ownership change. The result is less firefighting and faster review cycles.


Course illustration
Course illustration

All Rights Reserved.