{"id":890,"date":"2022-11-17T19:05:00","date_gmt":"2022-11-17T13:35:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=890"},"modified":"2023-08-15T15:50:09","modified_gmt":"2023-08-15T10:20:09","slug":"flask-app-for-image-recognition","status":"publish","type":"post","link":"https:\/\/geekpython.in\/flask-app-for-image-recognition","title":{"rendered":"Build Flask App For Image Recognition Using Deep Learning Model"},"content":{"rendered":"\n<p>The web app we will make is about predicting the image of a hand sign digit. The model is trained on the dataset named &#8220;<a target=\"_blank\" href=\"https:\/\/www.kaggle.com\/datasets\/rayeed045\/american-sign-language-digit-dataset\" rel=\"noreferrer noopener\">American Hand Digit Sign Language<\/a>&#8221; found on Kaggle.<\/p>\n\n\n\n<p>This tutorial will focus on making a web app using the Flask web framework, so all the necessary backend processes, including data preparation, data preprocessing, and training a model, are already done.<\/p>\n\n\n\n<p>We will implement our model in action by embedding it on the client side.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-overview\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-overview\"><\/a>Overview<\/h2>\n\n\n\n<p>The web app has a good-looking user interface in which we have an&nbsp;<strong>image upload<\/strong>&nbsp;area and an&nbsp;<strong>image preview<\/strong>&nbsp;section where we can see the preview of the uploaded image. All were made using&nbsp;<strong>Bootstrap, CSS, and JS<\/strong>. The web app has a&nbsp;<strong><em>Submit<\/em><\/strong>&nbsp;button responsible for handling the prediction and rendering the prediction page, where we will see the result obtained by predicting the image using our custom model.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"837\" height=\"626\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/1-4.png\" alt=\"A preview of the web app\" class=\"wp-image-893\"\/><\/figure>\n\n\n\n<p>Click&nbsp;<a target=\"_blank\" href=\"https:\/\/user-images.githubusercontent.com\/72191416\/201943098-c8f5fd8b-ec7d-4e5d-883d-8b69109b946f.mp4\" rel=\"noreferrer noopener\">here<\/a>&nbsp;to see a glimpse of the app.<\/p>\n\n\n\n<p>We used&nbsp;<strong>Bootstrap<\/strong>&nbsp;to build our client interface and to preview the image the user will upload, we used&nbsp;<strong>custom CSS and JS<\/strong>, and we used&nbsp;<strong>Keras, NumPy, and Pillow<\/strong>&nbsp;to recognize and predict the image in the backend.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-dependencies\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-dependencies\"><\/a>Dependencies<\/h2>\n\n\n\n<p>We need the following dependencies to get started on this project.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Flask<\/strong><\/li>\n\n\n\n<li><strong>TensorFlow (Keras)<\/strong><\/li>\n\n\n\n<li><strong>NumPy<\/strong><\/li>\n\n\n\n<li><strong>Pillow (PIL)<\/strong><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-installing-the-dependencies\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-installing-the-dependencies\"><\/a>Installing the dependencies<\/h3>\n\n\n\n<p>We need to install the dependencies we&#8217;ve seen above. Open your terminal and run the following command to install the libraries using the&nbsp;<strong><em>pip<\/em><\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:ps decode:true \">pip install Flask tensorflow numpy Pillow<\/pre><\/div>\n\n\n\n<p>The command will begin installing the libraries in your base Python environment. If the libraries have already been installed in your environment, then the command will upgrade the libraries to the updated version or prompt the message stating requirements are already satisfied.<\/p>\n\n\n\n<p>However, it is recommended that you use&nbsp;<strong>virtual environments<\/strong>&nbsp;that keep the libraries in an&nbsp;<strong>isolated Python environment<\/strong>, avoiding conflict between the different versions of the same dependencies so that your other projects might not get&nbsp;<strong>affected<\/strong>&nbsp;due to the change in dependency version.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>To create a Python virtual environment, see the detailed guide below.<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-geekpython wp-block-embed-geekpython\"><div class=\"wp-block-embed__wrapper\">\n<div class=\"oceanwp-oembed-wrap clr\"><blockquote class=\"wp-embedded-content\" data-secret=\"ptnduUbgJ3\"><a href=\"https:\/\/geekpython.in\/how-to-create-virtual-environments-using-venv-in-python\">How To Create Virtual Environments Using venv In Python<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;How To Create Virtual Environments Using venv In Python&#8221; &#8212; GeekPython\" src=\"https:\/\/geekpython.in\/how-to-create-virtual-environments-using-venv-in-python\/embed#?secret=nWZ1ac2n9B#?secret=ptnduUbgJ3\" data-secret=\"ptnduUbgJ3\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe><\/div>\n<\/div><\/figure>\n<\/blockquote>\n\n\n\n<p>After successfully setting up the virtual environment in the project directory and installing the required dependencies, move on to the coding part.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-creating-a-flask-server\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-creating-a-flask-server\"><\/a>Creating a Flask server<\/h2>\n\n\n\n<p>We&#8217;ll create a basic Flask server to start our web app on the localhost with default&nbsp;<strong>port number 5000<\/strong>.<\/p>\n\n\n\n<p>In the root folder of the project directory, create a file named&nbsp;<code>app.py<\/code>&nbsp;and add the following code to start a Flask server.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from flask import Flask\n\napp = Flask(__name__)\n\n@app.route('\/')\ndef hello_world():\n    return '&lt;h1&gt;Hello, World!&lt;\/h1&gt;'<\/pre><\/div>\n\n\n\n<p>To run the app, open your terminal and change the directory to the project directory, or open the&nbsp;<strong>terminal integrated with the IDE<\/strong>&nbsp;(PyCharm) or&nbsp;<strong>code editor<\/strong>&nbsp;(VS Code) and execute the following command.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:ps decode:true \">&gt;flask --app app.py run<\/pre><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Learn how to run the flask apps from the terminal. The following guide will help let you know the usage of the&nbsp;<code>flask run<\/code>&nbsp;command with different flags.<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-geekpython wp-block-embed-geekpython\"><div class=\"wp-block-embed__wrapper\">\n<div class=\"oceanwp-oembed-wrap clr\"><blockquote class=\"wp-embedded-content\" data-secret=\"eWpZw2M8lI\"><a href=\"https:\/\/geekpython.in\/run-flask-app-from-the-command-line-in-windows\">How To Run Flask App From The Command Line In Windows<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;How To Run Flask App From The Command Line In Windows&#8221; &#8212; GeekPython\" src=\"https:\/\/geekpython.in\/run-flask-app-from-the-command-line-in-windows\/embed#?secret=JRji26n9FF#?secret=eWpZw2M8lI\" data-secret=\"eWpZw2M8lI\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe><\/div>\n<\/div><\/figure>\n<\/blockquote>\n\n\n\n<p>This will start our development server on the&nbsp;<strong>localhost<\/strong>&nbsp;with port number&nbsp;<strong>5000<\/strong>, and we can access the web app on the web address&nbsp;<code>http:\/\/127.0.0.1:5000<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1067\" height=\"317\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/2-5.png\" alt=\"Sample of the web app\" class=\"wp-image-894\"\/><\/figure>\n\n\n\n<p>Our Flask app is ready, and we&#8217;ll start structuring our app into a good web app. But first, we&#8217;ll have to code our&nbsp;<strong>backend<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-coding-the-backend\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-coding-the-backend\"><\/a>Coding the backend<\/h2>\n\n\n\n<p>Before coding our user interface, we&#8217;ll need to create the&nbsp;<strong>functions<\/strong>&nbsp;which will handle the&nbsp;<strong>preprocessing of the uploaded image and the prediction on that uploaded image<\/strong>.<\/p>\n\n\n\n<p>Create a Python file named&nbsp;<code>model.py<\/code>&nbsp;where all our functions to handle the image preprocessing and prediction will go.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"model.py\"># Importing required libs\nfrom keras.models import load_model\nfrom keras.utils import img_to_array\nimport numpy as np\nfrom PIL import Image\n\n# Loading model\nmodel = load_model(\"D:\/SACHIN\/Models\/Hand-Sign-Digit-Language\/digit_model.h5\")\n\n\n# Preparing and pre-processing the image\ndef preprocess_img(img_path):\n    op_img = Image.open(img_path)\n    img_resize = op_img.resize((224, 224))\n    img2arr = img_to_array(img_resize) \/ 255.0\n    img_reshape = img2arr.reshape(1, 224, 224, 3)\n    return img_reshape\n\n\n# Predicting function\ndef predict_result(predict):\n    pred = model.predict(predict)\n    return np.argmax(pred[0], axis=-1)<\/pre><\/div>\n\n\n\n<p>First, we imported the libraries we will use further in the code.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>load_model<\/strong>&nbsp;from&nbsp;<code>keras.model<\/code>&nbsp;will be used to load the model.<\/li>\n\n\n\n<li><strong>img_to_array<\/strong>&nbsp;from&nbsp;<code>keras.utils<\/code>&nbsp;will be used for converting the image into an array.<\/li>\n\n\n\n<li><strong>numpy<\/strong>&nbsp;is used for converting images into an array, but we&#8217;ll use it in the prediction function.<\/li>\n\n\n\n<li><strong>Image<\/strong>&nbsp;from&nbsp;<strong>PIL<\/strong>&nbsp;(Python Imaging Library) will be used for loading the image.<\/li>\n<\/ul>\n\n\n\n<p>In the next section, we loaded our model using the&nbsp;<code>load_model<\/code>&nbsp;function, specified the path of our trained model inside it, and stored it in the variable named&nbsp;<code>model<\/code>.<\/p>\n\n\n\n<p>Then, we defined the function to preprocess the image, which takes the&nbsp;<strong>path<\/strong>&nbsp;of an image, and then we loaded that image using the&nbsp;<code>Image.open<\/code>&nbsp;function. Then we resized the loaded image into&nbsp;<strong>224 x 224<\/strong>&nbsp;dimensions because we trained our model using the transfer learning technique.&nbsp;<strong>The&nbsp;<a target=\"_blank\" href=\"https:\/\/keras.io\/api\/applications\/mobilenet\/\" rel=\"noreferrer noopener\">MobileNet<\/a>&nbsp;model we used for transfer learning is pre-trained with the images having 224 x 224 dimensions<\/strong>. Then we created the&nbsp;<strong>array<\/strong>&nbsp;of that resized image and, by dividing it by&nbsp;<strong>255.0<\/strong>, we converted the image pixel range from&nbsp;<strong>0 to 1<\/strong>, then reshaped it to the required shape and returned it.<\/p>\n\n\n\n<p>In the end, we created a function to predict the result of the preprocessed image using our model.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-coding-the-frontend\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-coding-the-frontend\"><\/a>Coding the frontend<\/h2>\n\n\n\n<p>The backend part is completed. Now we&#8217;ll code the frontend part of our web app. In the&nbsp;<code>app.py<\/code>&nbsp;file, add the following code.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"app.py\"># Importing required libs\nfrom flask import Flask, render_template, request\nfrom model import preprocess_img, predict_result\n\n# Instantiating flask app\napp = Flask(__name__)\n\n\n# Home route\n@app.route(\"\/\")\ndef main():\n    return render_template(\"index.html\")\n\n\n# Prediction route\n@app.route('\/prediction', methods=['POST'])\ndef predict_image_file():\n    try:\n        if request.method == 'POST':\n            img = preprocess_img(request.files['file'].stream)\n            pred = predict_result(img)\n            return render_template(\"result.html\", predictions=str(pred))\n\n    except:\n        error = \"File cannot be processed.\"\n        return render_template(\"result.html\", err=error)\n\n\n# Driver code\nif __name__ == \"__main__\":\n    app.run(port=9000, debug=True)<\/pre><\/div>\n\n\n\n<p>Initially, we imported the required libraries and functions to help us advance in this code.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Flask<\/strong>&nbsp;will be used to create or serve our application.<\/li>\n\n\n\n<li><strong>render_template<\/strong>&nbsp;will be used for rendering our HTML files.<\/li>\n\n\n\n<li><strong>request<\/strong>&nbsp;for accessing the image uploaded by the user in the frontend of our application.<\/li>\n<\/ul>\n\n\n\n<p><code>preprocess_img<\/code>&nbsp;and&nbsp;<code>predict_result<\/code>&nbsp;are the functions we created in our&nbsp;<code>model.py<\/code>&nbsp;file.<\/p>\n\n\n\n<p>After that, we created the home route where we defined the decorator&nbsp;<code>@app.route(\"\/\")<\/code>&nbsp;with path (<code>\/<\/code>) and the function&nbsp;<code>main<\/code>&nbsp;to render the HTML template&nbsp;<code>index.html<\/code>.<\/p>\n\n\n\n<p>The&nbsp;<strong>index.html<\/strong>&nbsp;file includes the web app&#8217;s user interface, which has a form for uploading the image, an image preview section, and a submit button.<\/p>\n\n\n\n<p>Add the HTML files in the Flask application. Create a folder named&nbsp;<code>templates<\/code>&nbsp;in the root folder of the directory and then create the files named&nbsp;<code>layout.html<\/code>&nbsp;and&nbsp;<code>index.html<\/code>.<\/p>\n\n\n\n<p><strong><em>layout.html<\/em><\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:xhtml decode:true \" title=\"layout.html\">&lt;!doctype html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;!-- Required meta tags --&gt;\n    &lt;meta charset=\"utf-8\"&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"&gt;\n\n    &lt;!-- Bootstrap CSS --&gt;\n    &lt;link rel=\"stylesheet\" href=\"https:\/\/cdn.jsdelivr.net\/npm\/bootstrap@4.3.1\/dist\/css\/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH\/1fQ784\/j6cY\/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"&gt;\n      &lt;link href=\"{{url_for('static', filename='css\/custom.css')}}\" rel=\"stylesheet\"\/&gt;\n\n    &lt;title&gt;\n        {% block title %}\n        {% endblock %}\n    &lt;\/title&gt;\n  &lt;\/head&gt;\n&lt;body&gt;\n{% block content %}\n{% endblock %}\n    &lt;script src=\"https:\/\/code.jquery.com\/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i\/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"&gt;&lt;\/script&gt;\n    &lt;script src=\"https:\/\/cdn.jsdelivr.net\/npm\/bootstrap@4.3.1\/dist\/js\/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf\/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"&gt;&lt;\/script&gt;\n  &lt;script src=\"{{url_for('static', filename='js\/image_upload.js')}}\"&gt;&lt;\/script&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;<\/pre><\/div>\n\n\n\n<p>The&nbsp;<strong>layout.html<\/strong>&nbsp;file contains the HTML boilerplate in which we included the custom CSS and JS files.<\/p>\n\n\n\n<p><strong><em>index.html<\/em><\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:xhtml decode:true \" title=\"index.html\">{% extends \"layout.html\"%}\n{% block title %}\nHand Sign Digit Recognition\n{% endblock %}\n\n{% block content %}\n&lt;div class=\"container py-5\"&gt;\n\n    &lt;header class=\"text-white text-center\"&gt;\n        &lt;h1 class=\"display-4\"&gt;Hand Sign Digit Language Detection&lt;\/h1&gt;\n        &lt;p class=\"lead mb-5\"&gt;A webapp to detect a digit using hand sign language. Just drop an image of Hand Digit Sign\n            and see the magic.&lt;\/p&gt;\n    &lt;\/header&gt;\n\n\n    &lt;div class=\"row py-4\"&gt;\n        &lt;div class=\"col-lg-6 mx-auto\"&gt;\n\n            &lt;!-- Upload image input--&gt;\n            &lt;form action=\"{{ url_for('predict_image_file') }}\" enctype=\"multipart\/form-data\" method=\"POST\"&gt;\n                &lt;div class=\"input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm\"&gt;\n                    &lt;input class=\"form-control border-0\" id=\"upload\" name=\"file\" type=\"file\"&gt;\n                    &lt;label class=\"font-weight-light text-muted\" for=\"upload\" id=\"upload-label\"&gt;Choose file&lt;\/label&gt;\n                    &lt;div class=\"input-group-append\"&gt;\n                        &lt;label class=\"btn btn-light m-0 rounded-pill px-4\" for=\"upload\"&gt; &lt;i\n                                class=\"fa fa-cloud-upload mr-2 text-muted\"&gt;&lt;\/i&gt;&lt;small\n                                class=\"text-uppercase font-weight-bold text-muted\"&gt;Choose file&lt;\/small&gt;&lt;\/label&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n\n\n                &lt;!-- Uploaded image area--&gt;\n                &lt;p class=\"font-italic text-white text-center\"&gt;The image uploaded will be rendered inside the box\n                    below.&lt;\/p&gt;\n                &lt;div class=\"image-area mt-4\"&gt;&lt;img alt=\"\" class=\"img-fluid rounded shadow-sm mx-auto d-block\"\n                                                  id=\"imageResult\" name=\"imageResult\"\n                                                  src=\"#\"&gt;&lt;\/div&gt;\n\n                &lt;!-- Submit button--&gt;\n                &lt;div class=\"container\"&gt;\n                    &lt;div class=\"row\"&gt;\n                        &lt;div class=\"col text-center\"&gt;\n                            &lt;input class=\"btn btn-primary my-3\" type=\"submit\"\/&gt;\n                        &lt;\/div&gt;\n                    &lt;\/div&gt;\n                &lt;\/div&gt;\n            &lt;\/form&gt;\n\n        &lt;\/div&gt;\n    &lt;\/div&gt;\n&lt;\/div&gt;\n\n{% endblock %}<\/pre><\/div>\n\n\n\n<p>In the image upload section, we added the&nbsp;<strong>URL<\/strong>&nbsp;that will handle the&nbsp;<strong>image uploading, preprocessing, and prediction<\/strong>. Additionally, we added the&nbsp;<code>method='post'<\/code>&nbsp;to handle the&nbsp;<strong>POST<\/strong>&nbsp;request. We will define the logic for&nbsp;<code>predict_image_file<\/code>&nbsp;ahead of this tutorial.<\/p>\n\n\n\n<p>Now, add the custom CSS and JS files that will add the style and function to preview the uploaded image by the user.<\/p>\n\n\n\n<p>Create a folder name&nbsp;<code>static<\/code>&nbsp;in the root folder of the project directory and then create the subfolders&nbsp;<code>css<\/code>&nbsp;and&nbsp;<code>js<\/code>&nbsp;inside the&nbsp;<strong><em>static<\/em><\/strong>&nbsp;folder and then add the&nbsp;<code>custom.css<\/code>&nbsp;and&nbsp;<code>image_upload.js<\/code>&nbsp;files, respectively.<\/p>\n\n\n\n<p><strong><em>custom.css<\/em><\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:css decode:true \" title=\"custom.css\">#upload {\n    opacity: 0;\n}\n\n#upload-label {\n    position: absolute;\n    top: 50%;\n    left: 1rem;\n    transform: translateY(-50%);\n}\n\n.image-area {\n    border: 2px dashed rgba(255, 255, 255, 0.7);\n    padding: 4rem;\n    position: relative;\n}\n\n.image-area::before {\n    content: 'Image Preview';\n    color: #fff;\n    font-weight: bold;\n    text-transform: uppercase;\n    position: absolute;\n    top: 50%;\n    left: 50%;\n    transform: translate(-50%, -50%);\n    font-size: 0.8rem;\n    z-index: 1;\n}\n\n\n.image-area img {\n    z-index: 2;\n    position: relative;\n}\n\n\nbody {\n    min-height: 100vh;\n    background-color: #757f9a;\n    background-image: linear-gradient(147deg, #9b5de5 0%, #f15bb5 100%);\n}<\/pre><\/div>\n\n\n\n<p>This&nbsp;<strong>CSS<\/strong>&nbsp;file gives additional styles to our web app&#8217;s user interface.<\/p>\n\n\n\n<p><strong><em>image_upload.js<\/em><\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:js decode:true \" title=\"image_upload.js\">\/*  ==========================================\n    SHOW UPLOADED IMAGE\n* ========================================== *\/\nfunction readURL(input) {\n    if (input.files &amp;&amp; input.files[0]) {\n        var reader = new FileReader();\n\n        reader.onload = function (e) {\n            $('#imageResult')\n                .attr('src', e.target.result);\n        };\n        reader.readAsDataURL(input.files[0]);\n    }\n}\n\n$(function () {\n    $('#upload').on('change', function () {\n        readURL(input);\n    });\n});\n\n\/*  ==========================================\n    SHOW UPLOADED IMAGE NAME\n* ========================================== *\/\nvar input = document.getElementById( 'upload' );\nvar infoArea = document.getElementById( 'upload-label' );\n\ninput.addEventListener( 'change', showFileName );\nfunction showFileName( event ) {\n  var input = event.srcElement;\n  var fileName = input.files[0].name;\n  infoArea.textContent = 'File name: ' + fileName;\n}<\/pre><\/div>\n\n\n\n<p>This&nbsp;<strong>JS<\/strong>&nbsp;file displays the preview of the image uploaded on our web app.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>The reference for making the UI of our web app is taken from&nbsp;<a target=\"_blank\" href=\"https:\/\/jsfiddle.net\/bootstrapious\/8w7a50n2\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<p>After adding all the HTML, CSS, and JS files, here comes the interesting part.<\/p>\n\n\n\n<p>Then we defined another route that contains the code for a&nbsp;<strong>POST<\/strong>&nbsp;request,&nbsp;<strong>preprocessing of the image<\/strong>, and then the&nbsp;<strong>prediction<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"prediction_route.py\"># Prediction route\n@app.route('\/prediction', methods=['POST'])\ndef predict_image_file():\n    try:\n        if request.method == 'POST':\n            img = preprocess_img(request.files['file'].stream)\n            pred = predict_result(img)\n            return render_template(\"result.html\", predictions=str(pred))\n\n    except:\n        error = \"File cannot be processed.\"\n        return render_template(\"result.html\", err=error)<\/pre><\/div>\n\n\n\n<p>In this section of the&nbsp;<code>app.py<\/code>&nbsp;file, we created the prediction route using the decorator&nbsp;<code>@app.route('\/prediction', methods=['POST'])<\/code>&nbsp;in which we specified the path&nbsp;<code>\/prediction<\/code>&nbsp;and set the method to&nbsp;<code>POST<\/code>&nbsp;to handle the&nbsp;<strong>post request<\/strong>.<\/p>\n\n\n\n<p>Then defined, the function&nbsp;<code>predict_image_file<\/code>&nbsp;in which the code takes the&nbsp;<strong>image stream<\/strong>&nbsp;of the image uploaded by the user and&nbsp;<strong>performs the preprocessing<\/strong>&nbsp;using the function&nbsp;<code>preprocess_img<\/code>, which is coming from the&nbsp;<code>model.py<\/code>&nbsp;file and then&nbsp;<strong>predicts the result<\/strong>&nbsp;using the&nbsp;<code>predict_result<\/code>&nbsp;function and then ultimately rendered the&nbsp;<code>result.html<\/code>&nbsp;page where we can see the result.<\/p>\n\n\n\n<p>To avoid any error, we wrapped the code in the&nbsp;<code>try-except<\/code>&nbsp;block, in which if the user uploads a file that cannot be processed, then the code will show the error in the frontend.<\/p>\n\n\n\n<p>To add the result page, create a file named&nbsp;<code>result.html<\/code>&nbsp;in the templates folder and add the following HTML.<\/p>\n\n\n\n<p><strong><em>result.html<\/em><\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:xhtml decode:true \" title=\"result.html\">{% extends \"layout.html\"%}\n{% block title %}\nPrediction - Hand Sign Digit Recognition\n{% endblock %}\n\n{% block content %}\n&lt;div class=\"container py-5\"&gt;\n\n    &lt;header class=\"text-white text-center\"&gt;\n        &lt;h1 class=\"display-4\"&gt;Hand Sign Digit Language Detection&lt;\/h1&gt;\n        &lt;p class=\"lead mb-5\"&gt;You will see the prediction of the input image.&lt;\/p&gt;\n    &lt;\/header&gt;\n\n    &lt;header class=\"text-white text-center\"&gt;\n        &lt;h1 class=\"display-5\"&gt;Prediction&lt;\/h1&gt;\n        {% if predictions %}\n        &lt;h2 class=\"display-4 text-dark font-weight-bold\"&gt;{{predictions}}&lt;\/h2&gt;\n        {% else %}\n        &lt;h2 class=\"display-4 text-dark font-weight-bold\"&gt;{{err}}&lt;\/h2&gt;\n        {% endif %}\n    &lt;\/header&gt;\n&lt;\/div&gt;\n{% endblock %}<\/pre><\/div>\n\n\n\n<p>This page is responsible for displaying the prediction if the image uploaded by the user is processed successfully. Otherwise, the error message will be displayed.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Get the source code of this app\ud83d\udc47\ud83d\udc47<\/strong><\/p>\n\n\n\n<p>GitHub &#8211; <a href=\"https:\/\/github.com\/Sachin-crypto\/Flask_Image_Recognition\" target=\"_blank\" rel=\"noopener\">Flask Image Recognition App Using Deep Learning Model<\/a><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition#heading-conclusion\"><\/a>Conclusion<\/h2>\n\n\n\n<p>In this tutorial, we&#8217;ve learned to create the Flask app for image recognition which is based on the deep-learning model.<\/p>\n\n\n\n<p>Some key points that we learned while making the app:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>implementing the deep learning model into the app<\/strong><\/li>\n\n\n\n<li><strong>creating the Flask app<\/strong><\/li>\n\n\n\n<li><strong>using the custom model to predict the images<\/strong><\/li>\n\n\n\n<li><strong>image preprocessing<\/strong><\/li>\n<\/ul>\n\n\n\n<p>To get started with this project, head over to my&nbsp;<a target=\"_blank\" href=\"https:\/\/github.com\/Sachin-crypto\/Flask_Image_Recognition\" rel=\"noreferrer noopener\">GitHub<\/a>&nbsp;for source code.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The web app we will make is about predicting the image of a hand sign digit. The model is trained on the dataset named &#8220;American Hand Digit Sign Language&#8221; found on Kaggle. This tutorial will focus on making a web app using the Flask web framework, so all the necessary backend processes, including data preparation, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":895,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2,5],"tags":[36,12,31],"class_list":["post-890","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-flask","tag-flask","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/890","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=890"}],"version-history":[{"count":7,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/890\/revisions"}],"predecessor-version":[{"id":1341,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/890\/revisions\/1341"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/895"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=890"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=890"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=890"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}