import numpy as npimport cv2from keras.models import Modelfrom keras.layers import Inputfrom yolo_v1 import YOLO# 定义类别标签classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']def load_image(image_path): # 加载图像并进行预处理(根据训练时的预处理方式进行) image = cv2.imread(image_path) image = cv2.resize(image, (448, 448)) image = image / 255.0 image = np.expand_dims(image, axis=0) return imagedef draw_boxes(image, boxes, scores): # 在图像上绘制检测框和类别名称 for box, score in zip(boxes, scores): x, y, w, h = box class_index = np.argmax(score) class_name = classes[class_index] confidence = score[class_index] label = f"{class_name}: {confidence:.2f}" cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) return image# 构建模型input_image = Input(shape=(448, 448, 3))yolo_model = YOLO(input_image, training=False)model = Model(inputs=input_image, outputs=yolo_model.output)# 加载预训练权重model.load_weights('path_to_pretrained_weights')# 进行目标检测和可视化image_path = 'dog.jpg'image = load_image(image_path)output = model.predict(image)# 解析输出boxes = output[..., :4]scores = output[..., 4:]# 设置置信度阈值,过滤掉置信度较低的检测结果confidence_threshold = 0.5filtered_boxes = []filtered_scores = []for box, score in zip(boxes[0], scores[0]): max_score = np.max(score) if max_score > confidence_threshold: filtered_boxes.append(box) filtered_scores.append(score)# 绘制检测结果并显示图像result_image = draw_boxes(cv2.imread(image_path), filtered_boxes, filtered_scores)cv2.imshow("Detection Result", result_image)cv2.waitKey(0)cv2.destroyAllWindows()