要保存 TensorFlow 物体检测增强图像,可以使用以下代码示例:
import tensorflow as tf
import numpy as np
import cv2
# 加载模型和标签
model = tf.saved_model.load('path_to_saved_model')
labels = ['label1', 'label2', ...] # 替换为实际的标签列表
# 读取和预处理图像
image = cv2.imread('input_image.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = tf.image.resize(image, (300, 300))
image = tf.expand_dims(image, axis=0)
image = tf.cast(image, tf.float32) / 255.0
# 推断和后处理
output = model(image)
detections = output['detection_boxes'][0].numpy()
scores = output['detection_scores'][0].numpy()
classes = output['detection_classes'][0].numpy().astype(np.int32)
num_detections = int(output['num_detections'][0])
# 绘制边界框和标签
for i in range(num_detections):
if scores[i] >= 0.5: # 设置阈值来过滤低置信度的检测结果
ymin, xmin, ymax, xmax = detections[i]
xmin = int(xmin * image.shape[2])
xmax = int(xmax * image.shape[2])
ymin = int(ymin * image.shape[1])
ymax = int(ymax * image.shape[1])
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)
cv2.putText(image, labels[classes[i]], (xmin, ymin-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
# 保存增强后的图像
output_image = cv2.cvtColor(image.numpy()[0], cv2.COLOR_RGB2BGR)
cv2.imwrite('output_image.jpg', output_image)
需要注意的是,上述代码示例假设你已经训练好了一个物体检测模型,并将其保存为 TensorFlow SavedModel 的格式。你需要将 path_to_saved_model
替换为你实际保存模型的路径。另外,如果你的模型有自定义标签,需要将 labels
列表替换为你实际的标签列表。