Как я могу поместить переменную из файла python в html-файл в Django?
Я пытаюсь сделать страницу распознавания лиц с помощью PyTorch. Когда лицо распознано, я хочу перейти на следующую страницу и напечатать имя распознанного человека.
Я написал код, но на следующей странице не печатается None. В моем терминале неоднократно печатается "POST / HTTP/1.1" 200 532. иногда печатается "GET /page HTTP/1.1" 200 308.
То есть, я хочу вывести имя и min_dist из get_frame файла camera2.py в файл page.html.
(camera2.py) name, min_dist ---post---> (page.html) name, min_dist
urls.py
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('detectme', views.detectme, name='detectme'),
path('page', views.get_post, name='page')
]
views.py
from django.shortcuts import render
from django.views.decorators import gzip
from django.http import StreamingHttpResponse
from detectme.camera2 import FaceDetect
def home(request):
return render(request, 'home.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@gzip.gzip_page
def detectme(request):
return StreamingHttpResponse(gen(FaceDetect()), content_type="multipart/x-mixed-replace;boundary=frame")
def check(request):
return render(request, "page.html")
def get_post(request):
if request.method == 'POST':
student = request.POST.get('student')
pred = request.POST.get('pred')
data = {
'name' : student,
'pred' : pred
}
return render(request, 'page.html', data)
if request.method == 'GET':
student = request.POST.get('student')
pred = request.POST.get('pred')
data = {
'name' : student,
'pred' : pred
}
return render(request, 'page.html', data)
camera2.py
import cv2
import threading
import torch
from facenet_pytorch import MTCNN, InceptionResnetV1
from PIL import Image
import requests
font = cv2.FONT_HERSHEY_SIMPLEX
mtcnn0 = MTCNN(image_size=240, margin=0, keep_all=False, min_face_size=40)
mtcnn = MTCNN(image_size=240, margin=0, keep_all=True, min_face_size=40)
resnet = InceptionResnetV1(pretrained='vggface2').eval()
class FaceDetect(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
(self.grabbed, self.frame) = self.video.read()
threading.Thread(target=self.update, args=()).start()
def get_frame(self):
load_data = torch.load('C:\coding\/face2\detectme\data.pt')
embedding_list = load_data[0]
name_list = load_data[1]
url = "http://127.0.0.1:8000"
while True:
frame = self.frame
img = Image.fromarray(frame)
img_cropped_list, prob_list = mtcnn(img, return_prob=True)
if img_cropped_list is not None:
boxes, _ = mtcnn.detect(img)
for i, prob in enumerate(prob_list):
if prob>0.90:
emb = resnet(img_cropped_list[i].unsqueeze(0)).detach()
dist_list = []
for idx, emb_db in enumerate(embedding_list):
dist = torch.dist(emb, emb_db).item()
dist_list.append(dist)
min_dist = min(dist_list)
min_dist_idx = dist_list.index(min_dist)
name = name_list[min_dist_idx]
box = boxes[i]
min_dist = round(min_dist, 3)
#original_frame = frame.copy()
datas = {
'student' : name,
'pred' : min_dist
}
response = requests.post(url, data=datas)
if min_dist<0.90:
frame = cv2.putText(frame, name+' '+ str(min_dist), (int(box[0]),int(box[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0),1, cv2.LINE_AA)
frame = cv2.rectangle(frame, (int(box[0]),int(box[1])) , (int(box[2]),int(box[3])), (255,0,0), 2)
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
def update(self):
while True:
(self.grabbed, self.frame) = self.video.read()
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>video</h1>
<table>
<tr>
<td width="50%">
<img src="http://127.0.0.1:8000/detectme" style="width:400px, height:400px"/>
</td>
<td width="50%">
{% block content%}
<form name="contents" method="post" action="{% url 'page' %}">
<a href="{% url 'page' %}">post</a>
</form>
{{ name }}
{% endblock %}
</td>
</tr>
</table>
</body>
</html>
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> post test </h1>
{% block content %}
{% csrf_token %}
name : {{ name }} <br>
pred : {{ pred }}<br>
{%endblock%}
</body>
</html>