yolov8测试图片并保存预测结果,用于map的计算

前言

当我们使用yolov8进行测试指定文件夹里的图片时,为了计算相应的map,需要先将yolov8的预测结果保存为txt文件;然后将txt文件中的格式(类别、框的中心点和高宽,置信度)转换成符合要求的格式(类别、置信度、框左上角坐标点、框右下角坐标点)。最后运行map计算代码

yolov8测试图片并保存预测结果

按照下面的方法来测试图片并保存预测结果,其中参数model为yolov8的pt模型,参数source为测试的图片或者图片的文件夹路径,参数save_txt设置为True:将预测结果保存为txt文件,参数save_conf设置为True:置信度也保存在txt文件中。

#使用命令
yolo detect predict model=/***/***.pt source=/**/ save_txt=True imgsz=416 save_conf=True
# 或者使用代码
Model = YOLO("/***/***.pt") # load a pretrained model (recommended for training)
Model.predict(source="/**/",save_txt=True, imgsz=416, save_conf=True)

格式转换

由于yolov8预测结果保存的格式为类别、框的中心点和高宽,置信度。我们需要将其转换成类别、置信度、框左上角坐标点、框右下角坐标点。下面的代码实现此需求。

import numpy as np
import cv2
import torch
import os
# 需要该下面这两处地方
label_path = './input/labels0'  # label_path:未转换的txt文件夹路径
image_path = './input/images-optional'  # label_path:原图的文件夹路径

#坐标转换,原始存储的是YOLOv5格式
# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
def xywhn2xyxy(x, w=416, h=416, padw=0, padh=0):

    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
    y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw  # top left x
    y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh  # top left y
    y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw  # bottom right x
    y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh  # bottom right y
    return y

folder = os.path.exists('DR')
if not folder:           
	os.makedirs('DR') 

folderlist = os.listdir(label_path)
for i in folderlist:
    label_path_new = os.path.join(label_path,i)
    with open(label_path_new, 'r') as f:
        lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels
        print(lb)
    read_label = label_path_new.replace(".txt", ".jpg")
    read_label_path = read_label.replace(label_path, image_path)
    print(read_label_path,"ddd")
    img = cv2.imread(str(read_label_path))
    h, w = img.shape[:2]
    lb[:, 1:] = xywhn2xyxy(lb[:, 1:], w, h, 0, 0)  # 反归一化

    # 绘图
    for _, x in enumerate(lb):
        class_label = int(x[0])  # class

        with open('DR/' + i, 'a') as fw:#这里需要把confidence放到第二位
            fw.write(str(int(x[0])) + ' ' + str(x[5])+' '+str(x[1]) + ' ' + str(x[2]) + ' ' + str(x[3]) + ' ' + str(
                x[4]) + '\n')
    '''cv2.imshow('show', img)
    cv2.waitKey(0)  # 按键结束
    cv2.destroyAllWindows()'''

运行结果后,会生成一个文件夹名字为“DR”的文件夹,将里面的txt文件放置在./input/detection-results里面。

最后运行map计算代码

  • 8
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
根据引用[1]和引用的内容,你可以按照以下步骤来计算yolov8测试集mAP指数: 1. 将yolov8预测结果保存为txt文件,确保每行的格式为:类别、框的中心点和高宽、置信度。 2. 将txt文件中的格式转换成符合要求的格式:类别、置信度、框左上角坐标点、框右下角坐标点。 3. 运行map计算代码,对yolov8测试集预测结果进行计算,得到mAP指数。 下面是一个示例代码,演示了如何计算yolov8测试集mAP指数: ```python # 导入所需的库 import numpy as np from sklearn.metrics import average_precision_score # 读取yolov8预测结果txt文件 with open('predictions.txt', 'r') as f: lines = f.readlines() # 将txt文件中的格式转换成符合要求的格式 predictions = [] for line in lines: line = line.strip().split(' ') category = int(line[0]) confidence = float(line[5]) x_center = float(line[1]) y_center = float(line[2]) width = float(line[3]) height = float(line[4]) x_min = x_center - width / 2 y_min = y_center - height / 2 x_max = x_center + width / 2 y_max = y_center + height / 2 predictions.append([category, confidence, x_min, y_min, x_max, y_max]) # 构建真实标签和预测标签 true_labels = np.array([[0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1]]) # 真实标签的格式为:类别、框左上角坐标点、框右下角坐标点 pred_labels = np.array(predictions) # 预测标签的格式为:类别、置信度、框左上角坐标点、框右下角坐标点 # 计算mAP指数 mAP = average_precision_score(true_labels, pred_labels) print("mAP指数为:", mAP) ```
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值