0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DjangoとTensorFlowのデータ受け渡しについて

Posted at

全体の流れ

  1. ユーザーがWebサイトから画像をアップロード
  2. Djangoがその画像を受け取って保存
  3. TensorFlowモデルに画像を渡して分類を実行
  4. 分類結果を受け取り、DjangoがWebページに結果を表示

データを「渡す」ときのルール(Django → TensorFlow)

Django内の関数やモジュールとして実行できる
直接関数を呼ぶ方式が一般的

TensorFlowをPythonコードとして呼び出すパターン
views.py

def classify_image_view(request):
    if request.method == 'POST' and request.FILES['image']:
        image_file = request.FILES['image']
        
        # 画像を一時保存
        temp_path = f'temp_images/{image_file.name}'
        with open(temp_path, 'wb+') as f:
            for chunk in image_file.chunks():
                f.write(chunk)

        # TensorFlowモデルに画像パスを渡す
        from .ai_model import classify_image
        result = classify_image(temp_path)

        return render(request, 'result.html', {'result': result})

ai_model.py の例(TensorFlowを使う部分)
ai_model.py

import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np

labels = ['動物', '風景', 'スポーツ', '機械', '文字']

def classify_image(img_path):
    model = tf.keras.models.load_model('model.h5')

    img = image.load_img(img_path, target_size=(224, 224))
    img_array = image.img_to_array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    predictions = model.predict(img_array)
    predicted_index = np.argmax(predictions)
    return labels[predicted_index]

データを「戻す」ときのルール(TensorFlow → Django)

TensorFlowが返すのは基本的に 分類ラベル or 数値のリスト です。

  • Django側で HTMLに結果を埋め込んで表示すればOK
  • あるいはJSONで返してJavaScriptに渡す場合も可能です(非同期表示にしたいとき)
HTMLで返す例

<!-- result.html -->
<h2>画像分類の結果:</h2>
<p>この画像は「{{ result }}」と判定されました。</p>

まとめ:処理の設計ポイント

処理フェーズ 内容 技術
画像アップロード HTMLフォーム+Djangoのrequest.FILES Django
一時保存 with open()などで保存 Python
モデル実行 TensorFlowで画像分類 TensorFlow + NumPy
結果を返す ラベル名や信頼度を文字列で返す Python
表示処理 render() でテンプレートに埋め込む Django Template Engine
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?