It's just a memo, so I'll omit the detailed settings of Django. The project is image_pred and the app name is myapp. The settings are only basic, as in the first part of the official page.
From index.html, send the image using the form.
index.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id = "input_form">
<form action="{% url 'index' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Send" />
</form>
</div>
<!--<div id = "prevent"><img src="{{question_id}}"></div>-->
<div id = "predict">{{urls}}</div>
</body>
</html>
forms.py
from django import forms
class PhotoForm(forms.Form):
image = forms.ImageField(label='Please select an image')
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import PhotoForm
class MyappView(TemplateView):
def __init__(self):
self.params={'form': PhotoForm()}
def get(self, req):
return render(req, 'index.html', self.params)
def post(self, req):
form = PhotoForm(req.POST, req.FILES)
if not form.is_valid():
raise ValueError('invalid form')
image = form.cleaned_data['image']
self.url_get(req, image)
return render(req, 'index.html', self.params)
def url_get(self, req, url):
from PIL import Image
import base64
import io
from io import BytesIO
img = Image.open(url)
with io.BytesIO() as output:
img.save(output,format="JPEG")
contents = output.getvalue()
data = base64.b64encode(contents)
#print('data:image/jpeg;base64,' + str(data)[2:-1])
self.params['urls'] = 'data:image/jpeg;base64,' + str(data)[2:-1]
This is the first image. Select the file and click Recognize.
I think you will see a result like this, so you can display the image based on this.
Since the creation of the project etc. is based on this material, there are many parts of the program that are the same. https://trafalbad.hatenadiary.jp/entry/2018/09/11/105500
Recommended Posts