|
发表于 2023-8-28 20:29:10
|
显示全部楼层
本楼为最佳答案
YOLOv1的目标检测可视化程序
以下是一个使用预训练权重进行目标检测并可视化结果的示例程序。请确保已经安装了必要的依赖项,例如Keras和OpenCV。
- import numpy as np
- import cv2
- from keras.models import Model
- from keras.layers import Input
- from 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 image
- def 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.5
- filtered_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()
复制代码
请将代码中的以下部分进行相应的修改:
- 将 path_to_pretrained_weights 替换为预训练权重文件的路径。
- 将 dog.jpg 替换为你要测试的图像文件的路径。
运行程序后,应该会显示含有检测框和类别的图像窗口。
希望这能帮到你!如果还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!  
|
|