DETR代码怎么实现detect预测?

 参考博客:【深度学习】实现DETR模型预测+保存每个图片中的检测框的txt文件+代码-优快云博客

但我自己跑会报一些错误,大家可以把错误放进gpt里面让gpt帮忙修改一下代码。

上述博客的预测代码只能够实现带有预测框结果的图片保存以及预测框信息的保存,如下:

所以我在上述基础上又添加了inference time 和 FPS 的计算,最后会打印结果:

参考代码

import math
import os.path

from PIL import Image
import requests
import matplotlib.pyplot as plt

import torch
from torch import nn
from torchvision.models import resnet50
import torchvision.transforms as T
from hubconf import *
from util.misc import nested_tensor_from_tensor_list

import time

torch.set_grad_enabled(False)

# 输入自己的数据集的类别
CLASSES = [
    'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
    'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A',
    'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
    'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack',
    'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',
    'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',
    'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass',
    'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',
    'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake',
    'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A',
    'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
    'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A',
    'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier',
    'toothbrush'
]

# colors for visualization
COLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125],
          [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]]

# # 输入自己的数据集的类别
# CLASSES = [
#     'N/A','ball','fakeperson','frustum','ironball','octaheron','polyhedron','uuv' # 只有一个类别
# ]
#
# # colors for visualization
# # COLORS = [[0.000, 0.447, 0.741]]  # 为 'person' 类别分配一种颜色
# COLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125],
#           [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]]

# standard PyTorch mean-std input image normalization
transform = T.Compose([
    T.Resize(800),
    T.ToTensor(),
    T.Normalize([0.485, 0.456, 0.406],
                [0.229, 0.224, 0.225])
])


# for output bounding box post-processing
def box_cxcywh_to_xyxy(x):
    x_c, y_c, w, h = x.unbind(1)
    b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
         (x_c + 0.5 * w), (y_c + 0.5 * h)]
    return torch.stack(b, dim=1)


def rescale_bboxes(out_bbox, width, height):
    # img_w, img_h = size
    # b = box_cxcywh_to_xyxy(out_bbox)
    box_coords = box_cxcywh_to_xyxy(out_bbox)
    scale_tensor = torch.Tensor(
        [width, height, width, height]).to(
        torch.cuda.current_device()
    )
    return box_coords * scale_tensor


def plot_results(pil_img, prob, boxes, image_item):
    # 保存图片和labels文件夹的目录
    save_dir = './save/exp5'
    # 保存画框后的图片目录
    save_img_path = os.path.join(save_dir, image_item)
    # labels文件夹目录
    save_txt_dir = './save/exp5/labels'

    # 创建目录(如果不存在)
    os.makedirs(save_dir, exist_ok=True)
    os.makedirs(save_txt_dir, exist_ok=True)


    plt.figure(figsize=(16, 10))
    plt.imshow(pil_img)
    ax = plt.gca()
    colors = COLORS * 100
    for p, (xmin, ymin, xmax, ymax), c in zip(prob, boxes.tolist(), colors):
        ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
                                   fill=False, color=c, linewidth=3))
        cl = p.argmax()
        text = f'{CLASSES[cl]}: {p[cl]:0.2f}'

        # 获取每个图片相应的txt文件的名字
        # 如xxx.jpg,此处txt_id为xxx
        txt_id = image_item[:-4]
        # 获取每个txt的绝对路径 /home/exp1/xxx.txt
        filename = os.path.join(save_txt_dir, f"{txt_id}.txt")
        with open(filename, "a", encoding="utf-8") as f:
            # 此处我只需要保存预测类别的序号和概率即可,
            # 所以保存在txt文件里为cl-1即可,
            # -1是因为我这里不需要N/A这个类别的序号
            results = f"{cl - 1} {p[cl]} \n"
            f.writelines(results)

        ax.text(xmin, ymin, text, fontsize=15,
                bbox=dict(facecolor='yellow', alpha=0.5))
    plt.axis('off')
    # 保存画好的图片
    plt.savefig(save_img_path, format='jpeg')
    plt.close("all")


def detect(im, model, transform):
    device = torch.cuda.current_device()
    width = im.size[0]
    height = im.size[1]


    # mean-std normalize the input image (batch-size: 1)
    img = transform(im).unsqueeze(0)

    # 检查图片的通道数,如果是单通道,则扩展为 3 通道
    if img.shape[1] == 1:  # 检查通道数 (C == 1)
        img = img.repeat(1, 3, 1, 1)  # 复制 3 份通道数据,变成 RGB 格式

    img = img.to(device)

    # propagate through the model
    outputs = model(img)

    # keep only predictions with 0.7+ confidence
    probas = outputs['pred_logits'].softmax(-1)[0, :, :-1]
    keep = probas.max(-1).values > 0.7

    # convert boxes from [0; 1] to image scales
    bboxes_scaled = rescale_bboxes(outputs['pred_boxes'][0, keep], width, height)
    return probas[keep], bboxes_scaled


if __name__ == "__main__":
    device = torch.device('cuda:0')
    model = detr_resnet50(pretrained=False, num_classes=91)
    state_dict = torch.load(r"detr-r50-e632da11.pth", map_location='cuda')
    model.load_state_dict(state_dict["model"])

    model.to(device)
    model.eval()

    image_file_path = os.listdir("E:/CODE/python/datasets/coco128/images/train2017")
    total_images = len(image_file_path)

    total_time = 0  # 总推理时间统计
    for image_item in image_file_path:
        print("Processing:", image_item)
        image_path = os.path.join("E:/CODE/python/datasets/coco128/images/train2017", image_item)

        # 加载图片并转换为 RGB
        im = Image.open(image_path).convert("RGB")

        # 记录推理开始时间
        start_time = time.time()
        scores, boxes = detect(im, model, transform)
        # 记录推理结束时间
        end_time = time.time()

        # 累积推理时间
        total_time += (end_time - start_time)

        # 保存检测结果
        plot_results(im, scores, boxes, image_item)

    # 计算 FPS 和平均推理时间
    avg_inference_time = total_time / total_images
    fps = 1 / avg_inference_time

    print(f"Total Images Processed: {total_images}")
    print(f"Average Inference Time: {avg_inference_time:.4f} seconds")
    print(f"FPS: {fps:.2f} frames per second")

 代码修改注意事项

1. 使用自己的数据集修改数据集类别

2. 修改结果的保存路径

3.  可能会存在单通道的图片,需要添加部分代码以防报错

·

4. 置信度的调整

5. 类别数的修改(类别个数+1)

6. 权重文件的修改,如果是自己的数据集,训练结束后从生成的outputs文件夹中选择checkpoints.pth的路径添加在此处;或者使用官方给的预训练权重。

### 关于 DETR 模型的实际应用案例 #### 使用 PyTorch 实现 DETR 的目标检测实战教程 为了实现 DETR 模型的目标检测功能,可以采用如下 Python 代码来完成预测测试图像的任务: ```python import random from PIL import Image import glob import torch from torchvision import transforms as T def detect(image, model, transform): # 将输入图片转换为张量并标准化处理 img = transform(image).unsqueeze(0) # 利用模型进行推理得到输出结果 with torch.no_grad(): output = model(img)[0] # 获取置信度分数以及边界框坐标 scores = list(output['scores'].detach().cpu().numpy()) boxes = [[round(i, 2) for i in box.tolist()] for box in output['boxes'].detach().cpu()] return scores, boxes transform = T.Compose([ T.Resize(800), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) for _ in range(20): image_path = random.choice(glob.glob('../open-images-bus-trucks/images/*.jpg')) image = Image.open(image_path).resize((800, 800)).convert('RGB') scores, boxes = detect(image, model, transform) plot_results(image, scores, boxes) ``` 此段代码展示了如何利用预训练好的 DETR 模型对给定的一系列图像执行对象检测操作,并可视化这些检测到的对象及其位置信息[^4]。 #### 开发 DETR 算法所需的工具包 对于希望深入研究和实践 DETR 模型的研究人员来说,建议使用以下几种流行的开源框架和技术栈来进行开发工作: - **PyTorch**: 提供灵活高效的深度学习平台支持快速原型设计; - **TensorFlow**: 可用于构建大规模分布式机器学习应用程序; - **OpenCV**: 辅助计算机视觉任务中的图像预处理与特征提取过程; 上述工具能够帮助开发者更便捷地搭建实验环境、调试程序逻辑并优化性能表现[^1]。 #### 自定义数据集上的 YOLOv4-Tiny 微调方法论 当面对特定领域内的应用场景时,可以通过修改YOLOv4-tiny架构适应新的需求。具体而言,在加载官方提供的预训练权重之后,针对所关心的数据分布特点调整网络结构参数,从而使得最终获得的模型具备更好的泛化能力和更高的精度水平[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小老大MUTA️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值