搜尋
首頁後端開發Python教學使用 Python 和 OpenCV 實現邊緣檢測:逐步指南

介紹

邊緣偵測是電腦視覺的基礎,使我們能夠辨識影像中的物件邊界。在本教程中,我們將使用 Sobel 算子和 Canny 邊緣偵測器以及 Python 和 OpenCV 來實作邊緣偵測。然後,我們將使用 Flask 創建一個簡單的 Web 應用程序,並使用 Bootstrap 進行樣式設計,以允許用戶上傳圖像並查看結果。

示範連結:邊緣偵測示範

先決條件

  • 您的電腦上已安裝 Python 3.x。
  • Python 程式設計基礎。
  • 熟悉 HTML 和 CSS 會有所幫助,但不是必要的。

設定環境

1.安裝所需的庫

開啟終端機或命令提示字元並執行:

pip install opencv-python numpy Flask

2.建立專案目錄

mkdir edge_detection_app
cd edge_detection_app

實施邊緣偵測

1. 索貝爾算子

Sobel 算子計算影像強度的梯度,強調邊緣。

程式碼實作:

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. Canny 邊緣偵測器

Canny 邊緣偵測器是一種用於偵測邊緣的多層演算法。

程式碼實作:

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

建立 Flask Web 應用程式

1. 設定 Flask 應用程式

建立一個名為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. 定義路線

上傳路線:

@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')

處理影像函數:

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)

結果路線:

@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. 運行應用程式

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

使用 Bootstrap 設計 Web 應用程式的樣式

在 HTML 範本中包含 Bootstrap CDN 以進行樣式設定。

1.上傳.html

建立templates目錄並加入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.結果.html

在templates目錄下建立result.html:



    <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>


運行和測試應用程式

1. 運行 Flask 應用程式

python app.py

2. 存取應用程式

開啟網頁瀏覽器並導航至 http://localhost:5000。

  • 上傳圖像並點擊「上傳並處理」。
  • 查看邊緣偵測結果。

結果範例

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

結論

我們建立了一個簡單的 Web 應用程序,使用 Sobel 算子和 Canny 邊緣偵測器執行邊緣偵測。透過整合 Python、OpenCV、Flask 和 Bootstrap,我們創建了一個互動式工具,讓用戶上傳圖像並查看邊緣檢測結果。

後續步驟

  • 增強應用程式:新增更多邊緣偵測選項或允許參數調整。
  • 改進UI:融入更多Bootstrap元件,提供更好的使用者體驗。
  • 進一步探索:在 Heroku 或 AWS 等其他平台上部署應用程式。

GitHub 儲存庫:邊緣偵測應用程式

以上是使用 Python 和 OpenCV 實現邊緣檢測:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

Python列表串聯性能:速度比較Python列表串聯性能:速度比較May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何將元素插入python列表中?您如何將元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表動態陣列或引擎蓋下的鏈接列表?Python是否列表動態陣列或引擎蓋下的鏈接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何從python列表中刪除元素?如何從python列表中刪除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版