Sketchy – Sketch making Flask App – Interesting Project – 2024

Hey guys, here comes another interesting Project which I named Sketchy – a Sketch making Flask App. This is a very easy yet very interesting project for folks who are looking to try out their hands on Flask.

Snapshot of our Final app…

Sketch making Flask App
Sketch-making Flask App

This project mainly comprises of two files:

  • app.py
  • home.html

This is going to be a very interesting project, so without any further due, let’s do it…

Step 1 – Importing Required Libraries

import cv2
import os
from werkzeug.utils import secure_filename
from flask import Flask,request,render_template

UPLOAD_FOLDER = 'C:/Users/ashar/OneDrive/Desktop/Sketch-Flask-App/static/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
  • Here We are simply importing required libraries like cv2, os, flask, and werkzeug.
  • Also, we are defining some constants like UPLOAD_FOLDER and ALLOWED_EXTENSIONS for using them further.

Step 2 – Defining our Sketch making Flask App

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = "secret key"
  • Here we are defining a Flask app and we named it app.
  • Then we are adding some configurations to it like the UPLOAD_FOLDER. This means whenever we upload any file using this flask app it will automatically go into this upload folder.
  • SEND_FILE_MAX_AGE_DEFAULT says to remove that file from the cache after its use.

Step 3 – Defining the sketch function

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def make_sketch(img):
    grayed = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    inverted = cv2.bitwise_not(grayed)
    blurred = cv2.GaussianBlur(inverted, (19, 19), sigmaX=0, sigmaY=0)
    final_result = cv2.divide(grayed, 255 - blurred, scale=256)
    return final_result
  • In this step, we have defined an allowed_file function which basically checks whether the file we have uploaded is having an allowed extension or not. Remember the ALLOWED_EXTENSION set we declared in the first step.
  • Secondly, we have declared a make_sketch function which is the backbone of this app. This function simply takes an Image and returns its sketch.

Step 4 – Finally defining Flask routing functions

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/sketch',methods=['POST'])
def sketch():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        img = cv2.imread(UPLOAD_FOLDER+'/'+filename)
        sketch_img = make_sketch(img)
        sketch_img_name = filename.split('.')[0]+"_sketch.jpg"
        _ = cv2.imwrite(UPLOAD_FOLDER+'/'+sketch_img_name, sketch_img)
        return render_template('home.html',org_img_name=filename,sketch_img_name=sketch_img_name)


if __name__ == '__main__':
    app.run(debug=True)
  • Here we have defined two routing functions.
  • The first one is the home page function.
    • Its URL will be http://127.0.0.1:5000/
    • Notice the ‘/’ in the end. This is called the route.
  • The second is the sketch-making route function which will run when we hit the Submit Button after uploading the Image.
    • Its URL will be http://127.0.0.1:5000/sketch
    • Notice the ‘/sketch’ in the end. This is called the route.
  • And finally, the last part is to run the Flask app.

Code for our Sketch making Flask App…

app.py

import cv2
import os
from werkzeug.utils import secure_filename
from flask import Flask,request,render_template

UPLOAD_FOLDER = 'C:/Users/ashar/OneDrive/Desktop/Sketch-Flask-App/static/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = "secret key"

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def make_sketch(img):
    grayed = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    inverted = cv2.bitwise_not(grayed)
    blurred = cv2.GaussianBlur(inverted, (19, 19), sigmaX=0, sigmaY=0)
    final_result = cv2.divide(grayed, 255 - blurred, scale=256)
    return final_result

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/sketch',methods=['POST'])
def sketch():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        img = cv2.imread(UPLOAD_FOLDER+'/'+filename)
        sketch_img = make_sketch(img)
        sketch_img_name = filename.split('.')[0]+"_sketch.jpg"
        _ = cv2.imwrite(UPLOAD_FOLDER+'/'+sketch_img_name, sketch_img)
        return render_template('home.html',org_img_name=filename,sketch_img_name=sketch_img_name)


if __name__ == '__main__':
    app.run(debug=True)

home.html

<!doctype html>
<html lang="en">

<style type='text/css'>
    body {
        font-family: sans-serif;
        margin-top: 40px;
    }

    .regform {
        width: 800px;
        background-color: rgb(0, 0, 0, 0.8);
        margin: auto;
        color: #FFFFFF;
        padding: 10px 0px 10px 0px;
        text-align: center;
        border-radius: 15px 15px 0px 0px;

    }

    .main-form {
        width: 800px;
        margin: auto;
        background-color: rgb(0, 0, 0, 0.7);
        padding-left: 50px;
        padding-right: 50px;
        padding-bottom: 20px;
        color: #FFFFFF;
    }

    img {
        max-height: 400px;
        max-width: 500px;
        height: auto;
        width: auto;
    }
</style>


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Sketchy</title>
</head>

<body>

    <div class='regform mt-3'>
        <h1>Sketchy</h1>
    </div>

    <form action='/sketch' class='main-form' method="POST" enctype="multipart/form-data">

        <div class='text-center'>
            <input type="file" id="file" name='file' style="margin-top:10px;margin-bottom:10px;">
            <button type='submit' class='btn btn-outline-success'> Make Sketch
            </button>
        </div>

    </form>

    {% if sketch_img_name %}
    <div class="row" style="margin-top:10px;margin-bottom:10px;">
        <div class="col text-center">
            <h2>Original Image</h2><img src='../static/uploads/{{ org_img_name }}'
                style="display: block;margin-left: auto;margin-right: auto;">
        </div>
        <div class="col text-center">
            <h2>Sketch Image</h2><img src='../static/uploads/{{ sketch_img_name }}'
                style="display: block;margin-left: auto;margin-right: auto;">
        </div>
    </div>
    {% endif %}

</body>

</html>

Folders Hierarchy

Sketch making Flask App folder hierarchy
  • Create a file app.py and copy-paste the code from above to that file.
  • Now create a folder called templates and create a home.html file in it and copy-paste the code from above to that file.
  • Now create a folder called static.
  • Create one more folder called uploads inside static.
  • Both static and uploads are empty folders.
  • _pycache_ is automatically created (You can ignore this).

How to run Sketchy – Sketch making Flask App

  • Open the terminal in the folder where app.py is located.
  • Now simply run the flask run command and it should successfully run on your localhost.

Snapshot of our Sketch-making Flask App

Sketch making Flask App
Sketch-making Flask App

Finally, Let’s see the working of our Sketch-making Flask App…

Download Source Code

Do let me know if there’s any query regarding Sketch making Flask App by contacting me via email or LinkedIn.

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time …

Read my previous post: Best way to Explore Data using Interactive EDA Reports in Python

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projects, and Flask projects at machinelearningprojects.net.

4 Comments

  1. root@ubuntu-host ~/app3 via 🐍 v3.10.6 ➜ flask run
    Usage: flask run [OPTIONS]
    Try ‘flask run –help’ for help.

    Error: While importing ‘app’, an ImportError was raised:

    Traceback (most recent call last):
    File “/usr/local/lib/python3.10/dist-packages/flask/cli.py”, line 218, in locate_app
    __import__(module_name)
    File “/root/app3/app.py”, line 1, in
    import cv2
    File “/usr/local/lib/python3.10/dist-packages/cv2/__init__.py”, line 181, in
    bootstrap()
    File “/usr/local/lib/python3.10/dist-packages/cv2/__init__.py”, line 153, in bootstrap
    native_module = importlib.import_module(“cv2”)
    File “/usr/lib/python3.10/importlib/__init__.py”, line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: libGL.so.1: cannot open shared object file: No such file or directory

    I GET THIS ERROR WHEN I RUN FLASK RUN, PLEASE HELP!!

Leave a Reply

Your email address will not be published. Required fields are marked *