search
HomeBackend DevelopmentPython TutorialImplementing Edge Detection with Python and OpenCV: A Step-by-Step Guide

Introduction

Edge detection is fundamental in computer vision, allowing us to identify object boundaries within images. In this tutorial, we'll implement edge detection using the Sobel operator and the Canny edge detector with Python and OpenCV. We'll then create a simple web application using Flask, styled with Bootstrap, to allow users to upload images and view the results.

DEMO LINK: Edge Detection Demo

Prerequisites

  • Python 3.x installed on your machine.
  • Basic knowledge of Python programming.
  • Familiarity with HTML and CSS is helpful but not required.

Setting Up the Environment

1. Install Required Libraries

Open your terminal or command prompt and run:

pip install opencv-python numpy Flask

2. Create the Project Directory

mkdir edge_detection_app
cd edge_detection_app

Implementing Edge Detection

1. The Sobel Operator

The Sobel operator calculates the gradient of image intensity, emphasizing edges.

Code Implementation:

import cv2

# Load the image in grayscale
image = cv2.imread('input_image.jpg', cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error loading image")
    exit()

# Apply Sobel operator
sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)  # Horizontal edges
sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)  # Vertical edges

2. The Canny Edge Detector

The Canny edge detector is a multi-stage algorithm for detecting edges.

Code Implementation:

# Apply Canny edge detector
edges = cv2.Canny(image, threshold1=100, threshold2=200)

Creating a Flask Web Application

1. Set Up the Flask App

Create a file named app.py:

from flask import Flask, request, render_template, redirect, url_for
import cv2
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads/'
OUTPUT_FOLDER = 'static/outputs/'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER

# Create directories if they don't exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

2. Define Routes

Upload Route:

@app.route('/', methods=['GET', 'POST'])
def upload_image():
    if request.method == 'POST':
        file = request.files.get('file')
        if not file or file.filename == '':
            return 'No file selected', 400
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        process_image(file.filename)
        return redirect(url_for('display_result', filename=file.filename))
    return render_template('upload.html')

Process Image Function:

def process_image(filename):
    image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # Apply edge detection
    sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)
    edges = cv2.Canny(image, 100, 200)

    # Save outputs
    cv2.imwrite(os.path.join(app.config['OUTPUT_FOLDER'], 'sobelx_' + filename), sobelx)
    cv2.imwrite(os.path.join(app.config['OUTPUT_FOLDER'], 'edges_' + filename), edges)

Result Route:

@app.route('/result/<filename>')
def display_result(filename):
    return render_template('result.html',
                           original_image='uploads/' + filename,
                           sobelx_image='outputs/sobelx_' + filename,
                           edges_image='outputs/edges_' + filename)
</filename>

3. Run the App

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

Styling the Web Application with Bootstrap

Include Bootstrap CDN in your HTML templates for styling.

1. upload.html

Create a templates directory and add upload.html:



    <meta charset="UTF-8">
    <title>Edge Detection App</title>
    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">


    <div class="container mt-5">
        <h1 id="Upload-an-Image-for-Edge-Detection">Upload an Image for Edge Detection</h1>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <form method="post" enctype="multipart/form-data" class="border p-4">
                    <div class="form-group">
                        <label for="file">Choose an image:</label>
                        <input type="file" name="file" accept="image/*" required class="form-control-file" id="file">
                    </div>
                    <button type="submit" class="btn btn-primary btn-block">Upload and Process</button>
                </form>
            </div>
        </div>
    </div>


2. result.html

Create result.html in the templates directory:



    <meta charset="UTF-8">
    <title>Edge Detection Results</title>
    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">


    <div class="container mt-5">
        <h1 id="Edge-Detection-Results">Edge Detection Results</h1>
        <div class="row">
            <div class="col-md-6 mb-4">
                <h4 id="Original-Image">Original Image</h4>
                <img src="%7B%7B%20url_for('static',%20filename=original_image)%20%7D%7D" alt="Original Image" class="img-fluid rounded mx-auto d-block">
            </div>
            <div class="col-md-6 mb-4">
                <h4 id="Sobel-X">Sobel X</h4>
                <img src="%7B%7B%20url_for('static',%20filename=sobelx_image)%20%7D%7D" alt="Sobel X" class="img-fluid rounded mx-auto d-block">
            </div>
            <div class="col-md-6 mb-4">
                <h4 id="Canny-Edges">Canny Edges</h4>
                <img src="%7B%7B%20url_for('static',%20filename=edges_image)%20%7D%7D" alt="Canny Edges" class="img-fluid rounded mx-auto d-block">
            </div>
        </div>
        <div class="text-center mt-4">
            <a href="%7B%7B%20url_for('upload_image')%20%7D%7D" class="btn btn-secondary">Process Another Image</a>
        </div>
    </div>


Running and Testing the Application

1. Run the Flask App

python app.py

2. Access the Application

Open your web browser and navigate to http://localhost:5000.

  • Upload an image and click Upload and Process.
  • View the edge detection results.

SAMPLE RESULT

Implementing Edge Detection with Python and OpenCV: A Step-by-Step Guide

Conclusion

We've built a simple web application that performs edge detection using the Sobel operator and the Canny edge detector. By integrating Python, OpenCV, Flask, and Bootstrap, we've created an interactive tool that allows users to upload images and view edge detection results.

Next Steps

  • Enhance the Application: Add more edge detection options or allow parameter adjustments.
  • Improve the UI: Incorporate more Bootstrap components for a better user experience.
  • Explore Further: Deploy the app on other platforms like Heroku or AWS.

GitHub Repository: Edge Detection App

The above is the detailed content of Implementing Edge Detection with Python and OpenCV: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

How do you create a Python array? Give an example.How do you create a Python array? Give an example.May 04, 2025 am 12:10 AM

Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

What are some alternatives to using a shebang line to specify the Python interpreter?What are some alternatives to using a shebang line to specify the Python interpreter?May 04, 2025 am 12:07 AM

In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft