使用 Django 和 Yolov5 进行对象检测
我已经在 Github 上上传了Django-Yolov5 样板文件,方便参考。
模型.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])
视图.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)
在这个views.py中可以修改很多,比如添加更多的功能和逻辑,但这里的目的是连接yolov5和Django。views.py 中的配置是最重要的,因为它是 yolov5 hubconf.py 文件的网关。
表格.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 %}
最初的简单网页:
检测后: