深度学习目标检测python代码
时间: 2023-07-31 22:12:55 浏览: 50
以下是使用 TensorFlow Object Detection API 进行目标检测的 Python 代码示例:
```python
import cv2
import numpy as np
import tensorflow as tf
# 加载模型
model = tf.saved_model.load('path/to/saved_model')
# 定义标签列表
labels = ['person', 'car', 'truck', 'bicycle', 'motorbike']
# 加载图片
image = cv2.imread('path/to/image')
# 调整图片大小
image = cv2.resize(image, (300, 300))
# 转换颜色空间
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 转换为浮点型并进行归一化
image = image.astype(np.float32) / 255.0
# 构建输入张量
inputs = tf.expand_dims(image, axis=0)
# 进行推理
outputs = model(inputs)
# 解析输出结果
boxes = outputs['detection_boxes'][0].numpy()
scores = outputs['detection_scores'][0].numpy()
classes = outputs['detection_classes'][0].numpy().astype(np.int32)
# 绘制检测结果
for i in range(len(scores)):
if scores[i] > 0.5:
ymin, xmin, ymax, xmax = boxes[i]
xmin = int(xmin * image.shape[1])
xmax = int(xmax * image.shape[1])
ymin = int(ymin * image.shape[0])
ymax = int(ymax * image.shape[0])
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
cv2.putText(image, labels[classes[i] - 1], (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,上述代码中的 `path/to/saved_model`、`path/to/image` 和标签列表等需要根据实际情况进行替换。