边缘检测是计算机视觉的基础,使我们能够识别图像中的对象边界。在本教程中,我们将使用 sobel 算子和 canny 边缘检测器以及 python 和 opencv 来实现边缘检测。然后,我们将使用 flask 创建一个简单的 web 应用程序,并使用 bootstrap 进行样式设计,以允许用户上传图像并查看结果。
演示链接:边缘检测演示
打开终端或命令提示符并运行:
pip install opencv-python numpy flask
mkdir edge_detection_app cd edge_detection_app
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
canny 边缘检测器是一种用于检测边缘的多级算法。
代码实现:
# apply canny edge detector edges = cv2.canny(image, threshold1=100, threshold2=200)
创建一个名为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)
上传路线:
@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)
if __name__ == '__main__':
app.run(debug=true)
在 html 模板中包含 bootstrap cdn 以进行样式设置。
立即学习“Python免费学习笔记(深入)”;
创建templates目录并添加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>
在templates目录下创建result.html:
<!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
打开网络浏览器并导航至 http://localhost:5000。

我们构建了一个简单的 web 应用程序,使用 sobel 算子和 canny 边缘检测器执行边缘检测。通过集成 python、opencv、flask 和 bootstrap,我们创建了一个交互式工具,允许用户上传图像并查看边缘检测结果。
后续步骤
github 存储库:边缘检测应用
以上就是使用 Python 和 OpenCV 实现边缘检测:分步指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号