You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从TFLite检测结果中提取BoundingBox的坐标与尺寸参数?

从TFLite Object Detection结果中提取Bounding Box参数

我通过detection_result = detector.detect(input_tensor)获取检测结果,打印后得到如下结构:

DetectionResult(detections=[Detection(bounding_box=BoundingBox(origin_x=209, origin_y=0, width=137, height=135), categories=[Category(index=71, score=0.39453125, display_name='', category_name='tv')])])

我需要提取其中的origin_x、origin_y、width和height的值,之前尝试直接打印detector.detect没得到目标内容,完整代码如下:

import argparse
import sys
import time
import cv2
from tflite_support.task import core
from tflite_support.task import processor
from tflite_support.task import vision
import utils
import tflite_runtime.interpreter as tflite

def run(model: str, camera_id: int, width: int, height: int, num_threads: int,
        enable_edgetpu: bool) -> None:

  # Variables to calculate FPS
  counter, fps = 0, 0
  start_time = time.time()

  # Start capturing video input from the camera
  cap = cv2.VideoCapture(camera_id)
  cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

  # Visualization parameters
  row_size = 20  # pixels
  left_margin = 24  # pixels
  text_color = (0, 0, 255)  # red
  font_size = 1
  font_thickness = 1
  fps_avg_frame_count = 10

  # Initialize the object detection model
  base_options = core.BaseOptions(
      file_name=model, use_coral=enable_edgetpu, num_threads=num_threads)
  detection_options = processor.DetectionOptions(
      max_results=3, score_threshold=0.3)
  options = vision.ObjectDetectorOptions(
      base_options=base_options, detection_options=detection_options)
  detector = vision.ObjectDetector.create_from_options(options)

  # Continuously capture images from the camera and run inference
  while cap.isOpened():
    success, image = cap.read()
    if not success:
      sys.exit(
          'ERROR: Unable to read from webcam. Please verify your webcam settings.'
      )

    counter += 1
    image = cv2.flip(image, 1)

    # Convert the image from BGR to RGB as required by the TFLite model.
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # Create a TensorImage object from the RGB image.
    input_tensor = vision.TensorImage.create_from_array(rgb_image)

    # Run object detection estimation using the model.
    detection_result = detector.detect(input_tensor)

    # Draw keypoints and edges on input image
    image = utils.visualize(image, detection_result)
    print(detection_result)
    

    # Calculate the FPS
    if counter % fps_avg_frame_count == 0:
      end_time = time.time()
      fps = fps_avg_frame_count / (end_time - start_time)
      start_time = time.time()

    # Show the FPS
    fps_text = 'FPS = {:.1f}'.format(fps)
    text_location = (left_margin, row_size)
    cv2.putText(image, fps_text, text_location, cv2.FONT_HERSHEY_PLAIN,
                font_size, text_color, font_thickness)

    # Stop the program if the ESC key is pressed.
    if cv2.waitKey(1) == 27:
      break
    cv2.imshow('object_detector', image)

  cap.release()
  cv2.destroyAllWindows()


def main():
  parser = argparse.ArgumentParser(
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument(
      '--model',
      help='Path of the object detection model.',
      required=False,
      default='modeltpu.tflite')
  parser.add_argument(
      '--cameraId', help='Id of camera.', required=False, type=int, default=0)
  parser.add_argument(
      '--frameWidth',
      help='Width of frame to capture from camera.',
      required=False,
      type=int,
      default=320)
  parser.add_argument(
      '--frameHeight',
      help='Height of frame to capture from camera.',
      required=False,
      type=int,
      default=240)
  parser.add_argument(
      '--numThreads',
      help='Number of CPU threads to run the model.',
      required=False,
      type=int,
      default=4)
  parser.add_argument(
      '--enableEdgeTPU',
      help='Whether to run the model on EdgeTPU.',
      action='store_true',
      required=False,
      default=True)
  args = parser.parse_args()

  run(args.model, int(args.cameraId), args.frameWidth, args.frameHeight,
      int(args.numThreads), bool(args.enableEdgeTPU))


if __name__ == '__main__':
  main()

解决方案

TFLite Support Library返回的detection_result是结构化的Python对象,直接通过属性访问就能提取Bounding Box的参数,无需解析打印的字符串。

在你的代码中,找到print(detection_result)的位置,添加以下代码即可提取并输出目标参数:

# 提取Bounding Box参数
for detection in detection_result.detections:
    # 获取当前检测结果的Bounding Box对象
    bbox = detection.bounding_box
    # 直接访问属性提取值
    origin_x = bbox.origin_x
    origin_y = bbox.origin_y
    width = bbox.width
    height = bbox.height
    # 打印结果
    print(f"检测框参数: origin_x={origin_x}, origin_y={origin_y}, width={width}, height={height}")

如果你的检测结果最多只有一个(或者只需要第一个),可以简化为:

if detection_result.detections:
    bbox = detection_result.detections[0].bounding_box
    print(f"检测框参数: origin_x={bbox.origin_x}, origin_y={bbox.origin_y}, width={bbox.width}, height={bbox.height}")

修改后的完整run函数相关片段如下:

# Run object detection estimation using the model.
detection_result = detector.detect(input_tensor)

# Draw keypoints and edges on input image
image = utils.visualize(image, detection_result)
# print(detection_result)  # 可选:保留原打印或注释掉

# 提取并打印Bounding Box参数
for detection in detection_result.detections:
    bbox = detection.bounding_box
    origin_x = bbox.origin_x
    origin_y = bbox.origin_y
    width = bbox.width
    height = bbox.height
    print(f"检测框参数: origin_x={origin_x}, origin_y={origin_y}, width={width}, height={height}")

内容的提问来源于stack exchange,提问作者Michael Dixon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:52:51