Pengesanan tepi adalah asas dalam penglihatan komputer, membolehkan kami mengenal pasti sempadan objek dalam imej. Dalam tutorial ini, kami akan melaksanakan pengesanan tepi menggunakan operator Sobel dan pengesan tepi Canny dengan Python dan OpenCV. Kami kemudiannya akan mencipta aplikasi web mudah menggunakan Flask, digayakan dengan Bootstrap, untuk membolehkan pengguna memuat naik imej dan melihat hasilnya.
PAUT DEMO: Demo Pengesanan Tepi
Buka terminal atau command prompt anda dan jalankan:
pip install opencv-python numpy Flask
mkdir edge_detection_app cd edge_detection_app
Pengendali Sobel mengira kecerunan keamatan imej, menekankan tepi.
Pelaksanaan Kod:
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
Pengesan tepi Canny ialah algoritma berbilang peringkat untuk mengesan tepi.
Pelaksanaan Kod:
# Apply Canny edge detector edges = cv2.Canny(image, threshold1=100, threshold2=200)
Buat fail bernama 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)
Laluan Muat Naik:
@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')
Fungsi Imej Proses:
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)
Laluan Keputusan:
@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)
if __name__ == '__main__': app.run(debug=True)
Sertakan CDN Bootstrap dalam templat HTML anda untuk penggayaan.
Buat direktori templat dan tambah upload.html:
<!DOCTYPE html> <html lang="en"> <head> <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"> </head> <body> <div class="container mt-5"> <h1 class="text-center mb-4">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> </body> </html>
Buat result.html dalam direktori templat:
<!DOCTYPE html> <html lang="en"> <head> <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"> </head> <body> <div class="container mt-5"> <h1 class="text-center mb-5">Edge Detection Results</h1> <div class="row"> <div class="col-md-6 mb-4"> <h4 class="text-center">Original Image</h4> <img src="{{ url_for('static', filename=original_image) }}" alt="Original Image" class="img-fluid rounded mx-auto d-block"> </div> <div class="col-md-6 mb-4"> <h4 class="text-center">Sobel X</h4> <img src="{{ url_for('static', filename=sobelx_image) }}" alt="Sobel X" class="img-fluid rounded mx-auto d-block"> </div> <div class="col-md-6 mb-4"> <h4 class="text-center">Canny Edges</h4> <img src="{{ url_for('static', filename=edges_image) }}" alt="Canny Edges" class="img-fluid rounded mx-auto d-block"> </div> </div> <div class="text-center mt-4"> <a href="{{ url_for('upload_image') }}" class="btn btn-secondary">Process Another Image</a> </div> </div> </body> </html>
python app.py
Buka pelayar web anda dan navigasi ke http://localhost:5000.
Kami telah membina aplikasi web ringkas yang melakukan pengesanan tepi menggunakan pengendali Sobel dan pengesan tepi Canny. Dengan menyepadukan Python, OpenCV, Flask dan Bootstrap, kami telah mencipta alat interaktif yang membolehkan pengguna memuat naik imej dan melihat hasil pengesanan tepi.
Langkah Seterusnya
Repositori GitHub: Apl Pengesanan Tepi
Atas ialah kandungan terperinci Melaksanakan Pengesanan Tepi dengan Python dan OpenCV: Panduan Langkah demi Langkah. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!