国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

目標(biāo)檢測(cè)——detr源碼復(fù)現(xiàn)【 End-to-End Object Detection with Transformers】

這篇具有很好參考價(jià)值的文章主要介紹了目標(biāo)檢測(cè)——detr源碼復(fù)現(xiàn)【 End-to-End Object Detection with Transformers】。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

1、環(huán)境

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)

2、文檔

detr源碼地址
detr論文地址

3、數(shù)據(jù)集

自定義coco數(shù)據(jù)集

4、模型

在github上面下載

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)
鏈接:https://pan.baidu.com/s/1fmOYAOZ4yYx_rYquOS6Ycw
提取碼:74l5

5、權(quán)重文件

生成自己所需要的權(quán)重文件

import torch
# 修改路徑 預(yù)訓(xùn)練模型
pretrained_weights=torch.load('detr-r50.pth')
# 修改自己的類別
num_classes=3
pretrained_weights["model"]["class_embed.weight"].resize_(num_classes+1,256)
pretrained_weights["model"]["class_embed.bias"].resize_(num_classes+1)
torch.save(pretrained_weights,"detr_r50_%d.pth"%num_classes)

6、修改代碼

main.py相應(yīng)位置根據(jù)下圖更改

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)
model目錄下面的detr.py文件相應(yīng)位置更改類別 num_classes
deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)

7、訓(xùn)練模型

python main.py

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)

8、測(cè)試模型

import argparse
import random
import time
from pathlib import Path
import numpy as np
import torch
from models import build_model
from PIL import Image
import os
import torchvision
from torchvision.ops.boxes import batched_nms
import cv2
 

def get_args_parser():
    parser = argparse.ArgumentParser('Set transformer detector', add_help=False)
    parser.add_argument('--lr', default=1e-4, type=float)
    parser.add_argument('--lr_backbone', default=1e-5, type=float)
    parser.add_argument('--batch_size', default=2, type=int)
    parser.add_argument('--weight_decay', default=1e-4, type=float)
    parser.add_argument('--epochs', default=300, type=int)
    parser.add_argument('--lr_drop', default=200, type=int)
    parser.add_argument('--clip_max_norm', default=0.1, type=float,
                        help='gradient clipping max norm')
 
    # Model parameters
    parser.add_argument('--frozen_weights', type=str, default=None,
                        help="Path to the pretrained model. If set, only the mask head will be trained")
    # * Backbone
    # 如果設(shè)置為resnet101,后面的權(quán)重文件路徑也需要修改一下
    parser.add_argument('--backbone', default='resnet50', type=str,
                        help="Name of the convolutional backbone to use")
    parser.add_argument('--dilation', action='store_true',
                        help="If true, we replace stride with dilation in the last convolutional block (DC5)")
    parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),
                        help="Type of positional embedding to use on top of the image features")
 
    # * Transformer
    parser.add_argument('--enc_layers', default=6, type=int,
                        help="Number of encoding layers in the transformer")
    parser.add_argument('--dec_layers', default=6, type=int,
                        help="Number of decoding layers in the transformer")
    parser.add_argument('--dim_feedforward', default=2048, type=int,
                        help="Intermediate size of the feedforward layers in the transformer blocks")
    parser.add_argument('--hidden_dim', default=256, type=int,
                        help="Size of the embeddings (dimension of the transformer)")
    parser.add_argument('--dropout', default=0.1, type=float,
                        help="Dropout applied in the transformer")
    parser.add_argument('--nheads', default=8, type=int,
                        help="Number of attention heads inside the transformer's attentions")
    parser.add_argument('--num_queries', default=100, type=int,
                        help="Number of query slots")
    parser.add_argument('--pre_norm', action='store_true')
 
    # * Segmentation
    parser.add_argument('--masks', action='store_true',
                        help="Train segmentation head if the flag is provided")
 
    # Loss
    parser.add_argument('--no_aux_loss', dest='aux_loss', default='False',
                        help="Disables auxiliary decoding losses (loss at each layer)")
    # * Matcher
    parser.add_argument('--set_cost_class', default=1, type=float,
                        help="Class coefficient in the matching cost")
    parser.add_argument('--set_cost_bbox', default=5, type=float,
                        help="L1 box coefficient in the matching cost")
    parser.add_argument('--set_cost_giou', default=2, type=float,
                        help="giou box coefficient in the matching cost")
    # * Loss coefficients
    parser.add_argument('--mask_loss_coef', default=1, type=float)
    parser.add_argument('--dice_loss_coef', default=1, type=float)
    parser.add_argument('--bbox_loss_coef', default=5, type=float)
    parser.add_argument('--giou_loss_coef', default=2, type=float)
    parser.add_argument('--eos_coef', default=0.1, type=float,
                        help="Relative classification weight of the no-object class")
 
    # dataset parameters
    parser.add_argument('--dataset_file', default='coco')
    parser.add_argument('--coco_path', type=str, default="coco")
    parser.add_argument('--coco_panoptic_path', type=str)
    parser.add_argument('--remove_difficult', action='store_true')
 
    # 修改檢測(cè)的圖像路徑
    parser.add_argument('--source_dir', default='/root/autodl-tmp/Deformable-DETR-main/data/data-labelme/test',
                        help='path where to save, empty for no saving')
    # 修改檢測(cè)結(jié)果保存路徑
    parser.add_argument('--output_dir', default='result/',
                        help='path where to save, empty for no saving')
    parser.add_argument('--device', default='cpu',
                        help='device to use for training / testing')
    parser.add_argument('--seed', default=42, type=int)
    # 修改resnet50對(duì)應(yīng)的權(quán)重文件
    parser.add_argument('--resume', default='output/checkpoint0299.pth',
                        help='resume from checkpoint')
    parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
                        help='start epoch')
    parser.add_argument('--eval', default="True")
    parser.add_argument('--num_workers', default=2, type=int)
 
    # distributed training parameters
    parser.add_argument('--world_size', default=1, type=int,
                        help='number of distributed processes')
    parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
    return parser
 

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, size):
    img_w, img_h = size
    b = box_cxcywh_to_xyxy(out_bbox)
    b = b * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)
    return b
 

def filter_boxes(scores, boxes, confidence=0.7, apply_nms=True, iou=0.5):
    keep = scores.max(-1).values > confidence
    scores, boxes = scores[keep], boxes[keep]
 
    if apply_nms:
        top_scores, labels = scores.max(-1)
        keep = batched_nms(boxes, top_scores, labels, iou)
        scores, boxes = scores[keep], boxes[keep]
 
    return scores, boxes
 

# COCO classes
 
CLASSES = ['green','puple','yellow']
 

def plot_one_box(x, img, color=None, label=None, line_thickness=1):
    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
 
 
def main(args):
    print(args)
    device = torch.device(args.device)
    model, criterion, postprocessors = build_model(args)
 
    checkpoint = torch.load(args.resume, map_location='cpu')
    model.load_state_dict(checkpoint['model'],False)
    model.to(device)
 
    n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
    print("parameters:", n_parameters)
 
    image_Totensor = torchvision.transforms.ToTensor()
    image_file_path = os.listdir(args.source_dir)
 
    for image_item in image_file_path:
        print("inference_image:", image_item)
        image_path = os.path.join(args.source_dir, image_item)
        image = Image.open(image_path)
        image_tensor = image_Totensor(image)
        image_tensor = torch.reshape(image_tensor,
                                     [-1, image_tensor.shape[0], image_tensor.shape[1], image_tensor.shape[2]])
        image_tensor = image_tensor.to(device)
        time1 = time.time()
        inference_result = model(image_tensor)
        time2 = time.time()
        print("inference_time:", time2 - time1)
        probas = inference_result['pred_logits'].softmax(-1)[0, :, :-1].cpu()
        bboxes_scaled = rescale_bboxes(inference_result['pred_boxes'][0,].cpu(),
                                       (image_tensor.shape[3], image_tensor.shape[2]))
        scores, boxes = filter_boxes(probas, bboxes_scaled)
        scores = scores.data.numpy()
        boxes = boxes.data.numpy()
        for i in range(boxes.shape[0]):
            class_id = scores[i].argmax()
            label = CLASSES[class_id]
            confidence = scores[i].max()
            text = f"{label} {confidence:.3f}"
            print(text)
            image = np.array(image)
            plot_one_box(boxes[i], image, label=text)
        # cv2.imshow("images", cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
        # cv2.waitKey()
        image = Image.fromarray(image)
        image.save(os.path.join(args.output_dir, image_item))
 
 
if __name__ == '__main__':
    parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()])
    args = parser.parse_args()
    if args.output_dir:
        Path(args.output_dir).mkdir(parents=True, exist_ok=True)
    main(args)

9、結(jié)果

detr的測(cè)試對(duì)于小物體的檢測(cè)不是很好,相比來說deformable detr的效果更好

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)

deformable detr代碼復(fù)現(xiàn),深度學(xué)習(xí),# transform,目標(biāo)檢測(cè),計(jì)算機(jī)視覺,深度學(xué)習(xí)文章來源地址http://www.zghlxwxcb.cn/news/detail-570739.html

到了這里,關(guān)于目標(biāo)檢測(cè)——detr源碼復(fù)現(xiàn)【 End-to-End Object Detection with Transformers】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • DEFORMABLE DETR: DEFORMABLE TRANSFORMERS FOR END-TO-END OBJECT DETECTION 論文精讀筆記

    DEFORMABLE DETR: DEFORMABLE TRANSFORMERS FOR END-TO-END OBJECT DETECTION 論文精讀筆記

    DEFORMABLE DETR: DEFORMABLE TRANSFORMERS FOR END-TO-END OBJECT DETECTION 參考:AI-雜貨鋪-Transformer跨界CV又一佳作!Deformable DETR:超強(qiáng)的小目標(biāo)檢測(cè)算法! 摘要 摘要部分,作者主要說明了如下幾點(diǎn): 為了解決DETR中使用Transformer架構(gòu)在處理圖像特征圖時(shí)的局限性而導(dǎo)致的收斂速度慢,特征空間

    2024年02月10日
    瀏覽(19)
  • DINO:DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection

    DINO:DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection

    論文名稱: DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection 發(fā)表時(shí)間:ICLR2023 作者及組織:Shilong Liu, Feng Li等,來自IDEA、港中文、清華。 ?該篇論文在DN-DETR基礎(chǔ)上,額外引進(jìn)3個(gè)trick進(jìn)一步增強(qiáng)DETR的性能:在12epoch下coco上達(dá)到了49.0map。本文將分別介紹這3個(gè)trick,

    2024年01月18日
    瀏覽(26)
  • End-to-End Object Detection with Transformers(論文解析)

    End-to-End Object Detection with Transformers(論文解析)

    我們提出了一種將目標(biāo)檢測(cè)視為直接集合預(yù)測(cè)問題的新方法。我們的方法簡化了檢測(cè)流程,有效地消除了許多手工設(shè)計(jì)的組件的需求,如顯式編碼我們關(guān)于任務(wù)的先驗(yàn)知識(shí)的非極大值抑制過程或錨點(diǎn)生成。新框架的主要要素,稱為DEtection TRansformer或DETR,包括一個(gè)基于集合的全

    2024年02月09日
    瀏覽(27)
  • 《Dense Distinct Query for End-to-End Object Detection》論文筆記(ing)

    《Dense Distinct Query for End-to-End Object Detection》論文筆記(ing)

    作者這里認(rèn)為傳統(tǒng)個(gè)目標(biāo)檢測(cè)的anchor/anchorpoint其實(shí)跟detr中的query作用一樣,可以看作query (1)dense query:傳統(tǒng)目標(biāo)檢測(cè)生成一堆密集anchor,但是one to many需要NMS去除重復(fù)框,無法end to end。 (2)spare query 在one2one:egDETR,100個(gè)qeury,數(shù)量太少造成稀疏監(jiān)督,收斂慢召回率低。 (

    2024年01月25日
    瀏覽(23)
  • 圖像 跟蹤 - MOTR: End-to-End Multiple-Object Tracking with Transformer (ECCV 2022)

    圖像 跟蹤 - MOTR: End-to-End Multiple-Object Tracking with Transformer (ECCV 2022)

    聲明:此翻譯僅為個(gè)人學(xué)習(xí)記錄 文章信息 標(biāo)題: MOTR: End-to-End Multiple-Object Tracking with Transformer (ECCV 2022) 作者: Fangao Zeng*, Bin Dong*, Yuang Zhang*, Tiancai Wang, Xiangyu Zhang, and Yichen Wei (*Equal contribution, **Corresponding author) 文章鏈接:https://arxiv.org/pdf/2105.03247.pdf 文章代碼:https://github.co

    2024年02月13日
    瀏覽(25)
  • [文章閱讀] EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object ...

    [文章閱讀] EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object ...

    CVPR 2022 論文鏈接 源代碼:Github 1.1 論文試圖解決什么問題?這是否是一個(gè)新的問題? 試圖解決:基于PnPDE的單目物體位姿估計(jì),需要獲得圖像中點(diǎn)的3D深度(通過深度網(wǎng)絡(luò)之類的方法)以及2D-3D之間的關(guān)聯(lián),然后通過PnP求解得到物體位姿;而PnP本質(zhì)上不可導(dǎo),使得無法通過反

    2024年02月03日
    瀏覽(14)
  • 論文解讀《EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object Pose 》

    論文解讀《EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object Pose 》

    論文:《EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object Pose Estimation》 Code:https://github.com/tjiiv-cprg/epro-pnp (909 star) 作者的視頻簡單介紹:https://www.bilibili.com/video/BV13T411E7kb 摘要: 解決問題: 對(duì)于6D位姿估計(jì),基于幾何(PnP)的方法性能要好一些,但以前

    2024年02月03日
    瀏覽(21)
  • 深度學(xué)習(xí)中端到端(end-to-end)簡要理解

    深度學(xué)習(xí)中端到端(end-to-end)簡要理解

    端到端指的是輸入是原始數(shù)據(jù),輸出是最后的結(jié)果。而原來的輸入端不是直接的原始數(shù)據(jù)(raw data),而是在原始數(shù)據(jù)中提取的特征(features)。這一點(diǎn)在圖像問題上尤為突出,因?yàn)閳D像像素?cái)?shù)太多,數(shù)據(jù)維度高,會(huì)產(chǎn)生維度災(zāi)難,所以原來一個(gè)思路是手工提取(hand-crafted f

    2024年02月09日
    瀏覽(26)
  • END-TO-END OPTIMIZED IMAGE COMPRESSION論文閱讀

    END-TO-END OPTIMIZED IMAGE COMPRESSION論文閱讀

    END-TO-END OPTIMIZED IMAGE COMPRESSION 單詞 image compression 圖像壓縮 quantizer 量化器 rate–distortion performance率失真性能 a variant of 什么什么的一個(gè)變體 construct 構(gòu)造 entropy 熵 discrete value 離散值 摘要: We describe an image compression method, consisting of a nonlinear analysis transformation, a uniform quantizer,

    2024年02月12日
    瀏覽(26)
  • 【計(jì)算機(jī)視覺 | 目標(biāo)檢測(cè)】術(shù)語理解7:二值匹配(Binary Matching),DETR中的Object query的理解,匈牙利算法,DETR中的二分圖匹配

    【計(jì)算機(jī)視覺 | 目標(biāo)檢測(cè)】術(shù)語理解7:二值匹配(Binary Matching),DETR中的Object query的理解,匈牙利算法,DETR中的二分圖匹配

    當(dāng)涉及到計(jì)算機(jī)視覺中的二值匹配(Binary Matching),它是一種用于比較和匹配二值圖像的技術(shù)。二值圖像由黑色和白色像素組成,每個(gè)像素只有兩種可能的取值。二值匹配的目標(biāo)是確定兩個(gè)二值圖像之間的相似度或匹配度。 以下是幾種常見的二值匹配方法: 漢明距離:通過

    2024年02月07日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包