使用 Python 和 OpenCV 实现边缘检测:分步指南
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《使用 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)
3. 运行应用程序
if __name__ == '__main__': app.run(debug=true)
使用 bootstrap 设计 web 应用程序的样式
在 html 模板中包含 bootstrap cdn 以进行样式设置。
1.上传.html
创建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>
2.结果.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>
运行和测试应用程序
1. 运行 flask 应用程序
python app.py
2. 访问应用程序
打开网络浏览器并导航至 http://localhost:5000。
- 上传图像并单击“上传并处理”。
- 查看边缘检测结果。
结果示例
结论
我们构建了一个简单的 web 应用程序,使用 sobel 算子和 canny 边缘检测器执行边缘检测。通过集成 python、opencv、flask 和 bootstrap,我们创建了一个交互式工具,允许用户上传图像并查看边缘检测结果。
后续步骤
- 增强应用程序:添加更多边缘检测选项或允许参数调整。
- 改进ui:融入更多bootstrap组件,提供更好的用户体验。
- 进一步探索:在 heroku 或 aws 等其他平台上部署应用程序。
github 存储库:边缘检测应用
本篇关于《使用 Python 和 OpenCV 实现边缘检测:分步指南》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

- 上一篇
- Go 语言中,为何对只有一个元素的切片从索引 1 开始截取不会报错?

- 下一篇
- 页面刷新时onload事件如何执行?
-
- 文章 · python教程 | 7小时前 |
- Python数据建模:Statsmodels使用教程
- 404浏览 收藏
-
- 文章 · python教程 | 7小时前 |
- PythonVR开发环境搭建教程
- 385浏览 收藏
-
- 文章 · python教程 | 8小时前 |
- Python字符串与列表反转技巧
- 188浏览 收藏
-
- 文章 · python教程 | 8小时前 |
- Windows编译RustPython扩展教程
- 290浏览 收藏
-
- 文章 · python教程 | 9小时前 |
- PostgreSQL处理万列CSV:JSONB与GIN索引实战指南
- 382浏览 收藏
-
- 文章 · python教程 | 9小时前 |
- Python发送HTTP请求教程详解
- 425浏览 收藏
-
- 文章 · python教程 | 9小时前 |
- Pythonbreak与continue用法详解
- 438浏览 收藏
-
- 文章 · python教程 | 10小时前 |
- OpenCV安装指南:Python中cv2模块怎么装
- 111浏览 收藏
-
- 文章 · python教程 | 10小时前 |
- Python判断路径是文件还是目录的两种方法
- 257浏览 收藏
-
- 文章 · python教程 | 10小时前 |
- Flask外使用SQLAlchemy查询数据库方法
- 174浏览 收藏
-
- 文章 · python教程 | 11小时前 |
- PyCharm中文设置方法详解
- 387浏览 收藏
-
- 文章 · python教程 | 11小时前 |
- Python去重赋ID技巧解析
- 460浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 515次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 499次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- AI Mermaid流程图
- SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
- 820次使用
-
- 搜获客【笔记生成器】
- 搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
- 837次使用
-
- iTerms
- iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
- 855次使用
-
- TokenPony
- TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
- 919次使用
-
- 迅捷AIPPT
- 迅捷AIPPT是一款高效AI智能PPT生成软件,一键智能生成精美演示文稿。内置海量专业模板、多样风格,支持自定义大纲,助您轻松制作高质量PPT,大幅节省时间。
- 808次使用
-
- Flask框架安装技巧:让你的开发更高效
- 2024-01-03 501浏览
-
- Django框架中的并发处理技巧
- 2024-01-22 501浏览
-
- 提升Python包下载速度的方法——正确配置pip的国内源
- 2024-01-17 501浏览
-
- Python与C++:哪个编程语言更适合初学者?
- 2024-03-25 501浏览
-
- 品牌建设技巧
- 2024-04-06 501浏览