YOLOv5模型的API调用方式

调用API方式1

  1. 首先同目录下需要复制YOLOv5代码的models文件、utils文件、export文件。
  2. 返回格式为列表形式,存储所有的目标位置,置信度等
def detctapi(im):
    # Load Yolov5 model
    model_path = r'weights/yolo.pt'
    data = r'data/coco128.yaml'
    device = torch.device("cuda:0")

    @torch.no_grad()
    def init():
        weights = model_path
        device = 'cuda:0'  # cuda device, i.e. 0 or 0,1,2,3 or

        half = True  # use FP16 half-precision inference
        device = select_device(device)
        w = str(weights[0] if isinstance(weights, list) else weights)
        # model = torch.jit.load(w) if 'torchscript' in w else attempt_load(weights, device=device)
        model = DetectMultiBackend(w, device=device, dnn=False, data=data, fp16=half)

        model.eval()
        return model

    # model = torch.load(r'D:\yanyi\xianyu\1\facedetector_facemask3\facedetector_facemask3\untitled\weights\yolo.pt', map_location=torch.device('cuda'))
    model = init()
    conf_thres = 0.25  # confidence threshold
    iou_thres = 0.45  # NMS IOU threshold
    classes = int(0)
    max_det = 1000  # maximum detections per image


    # Load input image
    stride = 32
    imgsz = [320, 320]
    imgsz = check_img_size(imgsz, s=stride)  # check image size
    # Process image here
    fake_result = {}
    fake_result["model_data"] = {"objects": []}

    img = letterbox(im, imgsz)[0]
    print(img.shape)
    img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB
    img = np.ascontiguousarray(img)
    img = torch.from_numpy(img).to(device)
    img = img.half() if model.fp16 else img.float()  # uint8 to fp16/32
    img /= 255  # 0 - 255 to 0.0 - 1.0
    if len(img.shape) == 3:
        img = img[None]  # expand for batch dim
    names = {
        0: 'Right_mask',
        1: 'Error_mask',
        2: 'No_mask',
    }

    # Get predictions
    pred = model(img)
    pred = non_max_suppression(pred, conf_thres, iou_thres, None, False, max_det=max_det)
    re_boxes = list()
    re_confidence = list()
    re_classes = list()
    re_mask_id = list()
    for i, det in enumerate(pred):  # per image
        det[:, :4] = scale_boxes(img.shape[2:], det[:, :4], im.shape).round()
        for *xyxy, conf, cls in reversed(det):
            xyxy_list = torch.tensor(xyxy).view(1, 4).view(-1).tolist()
            conf_list = conf.tolist()
            label = names[int(cls)]
            re_boxes.append([int(xyxy_list[0]), int(xyxy_list[1]), int(xyxy_list[2]- xyxy_list[0]), int(xyxy_list[3]- xyxy_list[1])])
            re_confidence.append(conf_list)
            re_classes.append('face')
            re_mask_id.append(int(cls))
    print("Bounding Boxes:\n", re_boxes)
    print("Confidences:\n", re_confidence)
    print("Classes:\n", re_classes)
    print("Mask IDs:\n", re_mask_id)
    return re_boxes, re_confidence, re_classes, re_mask_id
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Yolov5 是一种常用的目标检测算法,可以用于识别图像中的不同物体。而FastAPI是一个用Python编写的Web框架,可以用于构建高性能的API。通过结合Yolov5和FastAPI,我们可以构建一个用于检测目标的API。 首先,我们需要安装Yolov5和FastAPI的依赖库。可以使用pip命令安装,例如: ``` pip install yolov5 fastapi ``` 接下来,我们需要创建一个FastAPI应用,并编写API端点来调用Yolov5模型。首先,导入必要的库: ```python from fastapi import FastAPI, UploadFile, File from PIL import Image import torch ``` 然后,加载训练好的Yolov5模型: ```python # 加载模型 model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt') ``` 接下来,创建一个FastAPI应用,并定义一个API端点来接收上传的图像文件,并使用Yolov5模型进行目标检测: ```python app = FastAPI() @app.post("/detect") async def detect_objects(file: UploadFile = File(...)): # 将上传的图像文件转换为PIL图像 image = Image.open(file.file) # 将PIL图像转换为模型可以接收的格式 image = torch.from_numpy(np.array(image)) # 运行Yolov5模型进行目标检测 results = model(image) # 处理检测结果 labels = results.pandas().xyxy[0] # 返回检测结果 return labels.to_dict(orient="records") ``` 最后,我们可以启动FastAPI应用并使用Yolov5来进行目标检测了: ```python if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` 以上就是通过FastAPI调用Yolov5进行目标检测的基本步骤。你可以根据自己的需求进行更多的定制和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一休哥※

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

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

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

打赏作者

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

抵扣说明:

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

余额充值