如何在django中使用yolov5模型

xkftehaa  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(806)

我想在django中使用yolov5模型,但遇到了麻烦。
我想做的是,如果用户上传一张图片到django服务器,用yolov5模型进行对象检测,然后在web上显示结果。这个过程本身很简单。但是我不知道如何附加yolov5 api和django。
使用过yolo的人都知道,yolo基本上是基于命令运行api的。

!python train.py --img 512 --batch 16 --epochs 100 --data ~~   # for training
!python detect.py --weights'/content/yolov5/runs/~~            # for detection

有什么方法可以在Django的视图中运行这个吗?

我尝试了一些Python函数,比如execfile()和os.system(),它们在Python脚本中以解释器的方式执行命令,但是它们不能正常工作(我认为Django和Yolo之间的路径是扭曲的)。

事实上,如果可能的话,最好像Keras一样将yolo api作为模块加载,并像函数一样运行它,而不是命令方法。但是我找不到一种方法来像模块或类似的东西一样使用yolov5。

我怎样才能解决这个问题?请给予我一些建议。

ars1skjm

ars1skjm1#

使用Django和Yolov5进行对象检测
使用yolov5配置Django项目:
Models.py:

import os

from django.db import models
from django.utils.translation import gettext_lazy as _

class ImageModel(models.Model):
    image = models.ImageField(_("image"), upload_to='images')

    class Meta:
        verbose_name = "Image"
        verbose_name_plural = "Images"

    def __str__(self):
        return str(os.path.split(self.image.path)[-1])

Views.py:

import io
from PIL import Image as im
import torch

from django.shortcuts import render
from django.views.generic.edit import CreateView

from .models import ImageModel
from .forms import ImageUploadForm

class UploadImage(CreateView):
    model = ImageModel
    template_name = 'image/imagemodel_form.html'
    fields = ["image"]

    def post(self, request, *args, **kwargs):
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            img = request.FILES.get('image')
            img_instance = ImageModel(
                image=img
            )
            img_instance.save()

            uploaded_img_qs = ImageModel.objects.filter().last()
            img_bytes = uploaded_img_qs.image.read()
            img = im.open(io.BytesIO(img_bytes))

            # Change this to the correct path
            path_hubconfig = "absolute/path/to/yolov5_code"
            path_weightfile = "absolute/path/to/yolov5s.pt"  # or any custom trained model

            model = torch.hub.load(path_hubconfig, 'custom',
                               path=path_weightfile, source='local')

            results = model(img, size=640)
            results.render()
            for img in results.imgs:
                img_base64 = im.fromarray(img)
                img_base64.save("media/yolo_out/image0.jpg", format="JPEG")

            inference_img = "/media/yolo_out/image0.jpg"

            form = ImageUploadForm()
            context = {
                "form": form,
                "inference_img": inference_img
            }
            return render(request, 'image/imagemodel_form.html', context)

        else:
            form = ImageUploadForm()
        context = {
            "form": form
        }
        return render(request, 'image/imagemodel_form.html', context)

在www.example.com中有很多可以修改views.py,比如添加更多的函数和逻辑,但这里的目的是连接yolov5和Django。views.py中的配置是最重要的,因为它是yolov5 www.example.com文件的入口hubconf.py。
Forms.py

from django import forms
from .models import ImageModel

class ImageUploadForm(forms.ModelForm):
    class Meta:
        model = ImageModel
        fields = ['image']

Imagemodel_form.html

{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block leftbar %}
    <div class="col-sm-3">

    </div>
{% endblock leftbar %} 

{% block content %}
    <div class="col-sm-9">
        <div id="uploadedImage"></div>
            <div class="mt-4">
                <form action="" enctype="multipart/form-data" id="imageUploadForm" method="post"> 
                    {% csrf_token %}
                    {{ form|crispy }}
                    <button class="btn btn-outline-success" type="submit">Submit</button>
                </form>
            </div>
        </div>
        <div class="mt-4">
            {% if inference_img %}
                <img src="{{inference_img}}" class="img-fluid" />
            {% else %}
                The inferenced image will be displayed here.
            {% endif %}
        </div>    
    </div>
{% endblock content %}

简单的网页最初:

检测后:

相关问题