Sunday, 17 January 2021

keras 12 vgg16 & django

code linkhttps://github.com/chuanshuoge6/keras-vgg16 

copy paste web image url, click submit

copy paste another web image url

browse image on computer

#views.py
import os
from django.shortcuts import render
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import imagenet_utils
import numpy as np
import urllib.request

# Create your views here.
def index(request):
    return render(request, 'index.html')

def local_image(request):
    image_file = request.FILES['image_file']

    with open('static/static-image.jpg', 'wb') as f:
        for chunk in image_file.chunks():
            f.write(chunk)

    prediction = predict_image('static/static-image.jpg')

    return render(request, 'index.html', {'prediction': prediction, "local_image_file": image_file})

def web_image(request):
    image_file = request.POST['image_file']

    urllib.request.urlretrieve(image_file, "static/static-image.jpg")

    prediction = predict_image('static/static-image.jpg')

    return render(request, 'index.html', {'prediction': prediction, "web_image_file": image_file})

def predict_image(file):
    # run on cpu
    os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

    vgg16 = tf.keras.applications.vgg16.VGG16()

    img = image.load_img(file, target_size=(224, 224))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)

    preprocessed_image = tf.keras.applications.vgg16.preprocess_input(img_array_expanded_dims)
    predictions = vgg16.predict(preprocessed_image)

    return imagenet_utils.decode_predictions(predictions)[0]

-----------------------
#index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VGG16</title>
    <style>
        table, th, td {
            border: 1px solid black;
        }
        tr:nth-child(even) {background-color: #f2f2f2;}
        th, td {padding: 10px;}
        img{height: 300px; width: 300px}
    </style>
</head>
<body>
    <h2>Predict Image with VGG16</h2>

    <h4>Select local image</h4>
    <form action="{% url 'local_image'  %}" enctype="multipart/form-data" method="post">
        {% csrf_token %}
        <input type="file" accept="image/*" name="image_file" id="local_image_file" onchange="local_image_change()">
        <input type="submit" id="submit_button" style="display:none">
    </form>

    <h4>Copy web image url</h4>
    <form action="{% url 'web_image'  %}" method="post">
        {% csrf_token %}
        {% if web_image_file %}
            <input name="image_file" type="url" id="web_image_url"
               value={{web_image_file}}
               onchange="web_image_change()">
        {% else %}
            <input name="image_file" type="url" id="web_image_url2"
               value="https://images.theconversation.com/files/308043/original/file-20191220-11924-iakhpb.jpeg?ixlib=rb-1.1.0&q=45&auto=format&w=754&fit=clip"
               onchange="web_image_change2()">
        {% endif %}
        <input type="submit" >
    </form>

    <h4>VGG16 input image</h4>
    {% if local_image_file %}
        {% load static %}
        <img id="selected_image3" src="{% static 'static-image.jpg' %}">
    {% elif web_image_file %}
        <img id="selected_image" src="{{web_image_file}}">
    {% else %}
        {% load static %}
        <img id="selected_image2" src="{% static 'spider.jpg' %}">
    {% endif %}

    <h4>VGG16 Prediction Result</h4>
    <table>
        <tr>
            <th>Object</th>
            <th>Probability</th>
        </tr>
        {% for row in prediction %}
            <tr>
                {% for col in row %}
                    {% if forloop.counter != 1 %}
                        <td>{{ col|safe }}</td>
                    {% endif %}
                {% endfor %}
            </tr>
        {% endfor %}
    </table>

    <script>
        function local_image_change(){
           var img_input = document.getElementById("local_image_file")
           try{document.getElementById("selected_image2").src = URL.createObjectURL(img_input.files[0])}catch(err){}
           try{document.getElementById("selected_image3").src = URL.createObjectURL(img_input.files[0])}catch(err){}
           document.getElementById("submit_button").click()
        }

        function web_image_change(){
           document.getElementById("selected_image").src =  document.getElementById("web_image_url").value
        }

        function web_image_change2(){
           document.getElementById("selected_image2").src =  document.getElementById("web_image_url2").value
        }
    </script>
</body>
</html>

-----------------------------------
#urls.py

from django.contrib import admin
from django.urls import path
from mobileNet import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('local_image/', views.local_image, name='local_image'),
    path('web_image/', views.web_image, name='web_image'),
]

--------------------------------
#settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

-------------------------------
#powershell

pip install whitenoise gunicorn
pip freeze > requirements.txt

------------------------------
#requirements

absl-py==0.11.0
asgiref==3.3.1
astunparse==1.6.3
cachetools==4.2.0
certifi==2020.12.5
chardet==4.0.0
Django==3.1.5
django-watchman==1.2.0
flatbuffers==1.12
gast==0.3.3
google-auth==1.24.0
google-auth-oauthlib==0.4.2
google-pasta==0.2.0
grpcio==1.32.0
gunicorn==20.0.4
h5py==2.10.0
idna==2.10
joblib==1.0.0
Keras-Preprocessing==1.1.2
Markdown==3.3.3
numpy==1.19.5
oauthlib==3.1.0
opt-einsum==3.3.0
Pillow==8.1.0
protobuf==3.14.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pytz==2020.5
requests==2.25.1
requests-oauthlib==1.3.0
rsa==4.7
scikit-learn==0.24.0
six==1.15.0
sklearn==0.0
sqlparse==0.4.1
tensorboard==2.4.1
tensorboard-plugin-wit==1.7.0
tensorflow==2.4.0
tensorflow-estimator==2.4.0
termcolor==1.1.0
threadpoolctl==2.1.0
typing-extensions==3.7.4.3
urllib3==1.26.2
Werkzeug==1.0.1
whitenoise==5.2.0
wrapt==1.12.1

reference:

save web image to local

django template table

django serve static image

django multipart form file upload

python copy InMemoryUploadedFile object to disk

heroku deploy slug size too large
 Compiled slug size: 526.6M is too large (max is 500M).

No comments:

Post a Comment