介绍
边缘检测是计算机视觉的基础,使我们能够识别图像中的对象边界。在本教程中,我们将使用 Sobel 算子和 Canny 边缘检测器以及 Python 和 OpenCV 来实现边缘检测。然后,我们将使用 Flask 创建一个简单的 Web 应用程序,并使用 Bootstrap 进行样式设计,以允许用户上传图像并查看结果。
演示链接:边缘检测演示
先决条件
- 您的计算机上已安装 Python 3.x。
- Python 编程基础知识。
- 熟悉 HTML 和 CSS 会有所帮助,但不是必需的。
设置环境
1.安装所需的库
打开终端或命令提示符并运行:
1 | pip install opencv-python numpy Flask
|
登录后复制
2.创建项目目录
1 2 | mkdir edge_detection_app
cd edge_detection_app
|
登录后复制
实施边缘检测
1. 索贝尔算子
Sobel 算子计算图像强度的梯度,强调边缘。
代码实现:
1 2 3 4 5 6 7 8 9 10 11 | 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 边缘检测器是一种用于检测边缘的多级算法。
代码实现:
1 2 | # Apply Canny edge detector
edges = cv2.Canny(image, threshold1=100, threshold2=200)
|
登录后复制
创建 Flask Web 应用程序
1. 设置 Flask 应用程序
创建一个名为app.py的文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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. 定义路线
上传路线:
1 2 3 4 5 6 7 8 9 10 11 | @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' )
|
登录后复制
处理图像函数:
1 2 3 4 5 6 7 8 9 10 11 | 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)
|
登录后复制
结果路线:
1 2 3 4 5 6 | @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)
|
登录后复制
3. 运行应用程序
1 2 | if __name__ == '__main__' :
app.run(debug=True)
|
登录后复制
使用 Bootstrap 设计 Web 应用程序的样式
在 HTML 模板中包含 Bootstrap CDN 以进行样式设置。
1.上传.html
创建templates目录并添加upload.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!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>
|
登录后复制
2.结果.html
在templates目录下创建result.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!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>
|
登录后复制
运行和测试应用程序
1. 运行 Flask 应用程序
2. 访问应用程序
打开网络浏览器并导航至 http://localhost:5000。
- 上传图像并单击“上传并处理”。
- 查看边缘检测结果。
结果示例

结论
我们构建了一个简单的 Web 应用程序,使用 Sobel 算子和 Canny 边缘检测器执行边缘检测。通过集成 Python、OpenCV、Flask 和 Bootstrap,我们创建了一个交互式工具,允许用户上传图像并查看边缘检测结果。
后续步骤
- 增强应用程序:添加更多边缘检测选项或允许参数调整。
- 改进UI:融入更多Bootstrap组件,提供更好的用户体验。
- 进一步探索:在 Heroku 或 AWS 等其他平台上部署应用程序。
GitHub 存储库:边缘检测应用
以上是使用 Python 和 OpenCV 实现边缘检测:分步指南的详细内容。更多信息请关注PHP中文网其他相关文章!