open-cv でライブ映像を取得して、ボタンをクリックしたところで一枚の画像を生成して、
image.htmlで撮られた写真を表示しています。
image.htmlでは、2つのボタンが表示されていて、一つは 再度写真を撮り直すボタン、一つはその写真を使ってpost requestを djangoに送るボタンです。
htmlに表示された画像を post requestで送りたいのですが、どのように画像をhtmlから取得できるのでしょうか?
image.html
python
1{% block content %} 2 3<p class="border" style="padding:10px;">Use this photo 4 <a class="btn btn-outline-info" href="/send" role="button">Select</a> 5</p> 6 7<p class="border" style="padding:10px;">Take an another photo 8 <a class="btn btn-outline-info" href="{{request.META.HTTP_REFERER}}" role="button">Take an another photo</a> 9</p> 10 11 12<p> 13 <img src="/image_feed" width="810" height="540"/> 14</p> 15 16 17{% endblock %} 18 19 20 21 22
python
1# ストリーミング画像・映像を表示するview 2class IndexView(View): 3 def get(self, request): 4 return render(request, 'index.html', {}) 5 6# ストリーミング画像を定期的に返却するview 7def video_feed_view(): 8 return lambda _: StreamingHttpResponse(generate_frame(), content_type='multipart/x-mixed-replace; boundary=frame') 9 10# # フレーム生成・返却する処理 11def generate_frame(): 12 capture = cv2.VideoCapture(0) # USBカメラから 13 14 while True: 15 if not capture.isOpened(): 16 print("Capture is not opened.") 17 break 18 # カメラからフレーム画像を取得 19 ret, frame = capture.read() 20 if not ret: 21 print("Failed to read frame.") 22 break 23 # フレーム画像バイナリに変換 24 ret, jpeg = cv2.imencode('.jpg', frame) 25 byte_frame = jpeg.tobytes() 26 # フレーム画像のバイナリデータをユーザーに送付する 27 yield (b'--frame\r\n' 28 b'Content-Type: image/jpeg\r\n\r\n' + byte_frame + b'\r\n\r\n') 29 capture.release() 30 31 32#一枚の写真を表示するための処理 33class ImageView(View): 34 def get(self, request): 35 return render(request, 'image.html', {}) 36 37def image_feed_view(): 38 return lambda _: HttpResponse(generate_one_frame(), content_type='image/jpeg') 39 40from django.http import HttpResponse 41def generate_one_frame(): 42 43 capture = cv2.VideoCapture(0) 44 count=0 45 while True: 46 count=count+1 47 if count>=10: 48 break 49 50 if not capture.isOpened(): 51 print("Capture is not opened.") 52 break 53 54 # カメラからフレーム画像を取得 55 ret, frame = capture.read() 56 if not ret: 57 print("Failed to read frame.") 58 break 59 60 # フレーム画像バイナリに変換 61 ret, jpeg = cv2.imencode('.jpg', frame) 62 byte_frame = jpeg.tobytes() 63 # フレーム画像のバイナリデータをユーザーに送付する 64 65 capture.release() 66 return byte_frame 67 68
urls.py
python
1from django.contrib.staticfiles.urls import staticfiles_urlpatterns 2from django.conf.urls.static import static 3from django.urls import path 4from . import views 5 6urlpatterns = [ 7 path('', views.IndexView.as_view()), 8 path('video_feed', views.video_feed_view(), name="video_feed"), 9 10 path('image',views.ImageView.as_view(), name='image'), 11 path('image_feed',views.image_feed_view(), name="image_feed"), 12] 13urlpatterns += staticfiles_urlpatterns() 14
https://deecode.net/?p=382 引用サイト。




