栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【OpenCV4】使用 filter2D() 函数实现基础的边缘检测

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【OpenCV4】使用 filter2D() 函数实现基础的边缘检测

原理

在图像中边缘的地方,像素值会出现大幅的波动,这时候像素变化的导数增大,所以只要求一定范围内(比如滤波器范围内)像素值的变化程度即可。

测试代码
#include 
#include 

using namespace std;

int main()
{
	cv::Mat kernel_1 = (cv::Mat_(1, 2) << 1, -1); // 检测垂直边缘
	cv::Mat kernel_2 = (cv::Mat_(1, 3) << 1, 0, -1); // 检测垂直边缘
	cv::Mat kernel_3 = (cv::Mat_(3, 1) << 1, 0, -1); // 检测水平边缘
	cv::Mat kernel_RU = (cv::Mat_(2, 2) << 1, 0, 0, -1); // 右上到左下的边缘检测
	cv::Mat kernel_LU = (cv::Mat_(2, 2) << 0, -1, 1, 0); // 左上到右下的边缘检测

	// 显示滤波器形态
	cout << kernel_1 << endl;
	cout << kernel_2 << endl;
	cout << kernel_3 << endl;
	cout << kernel_RU << endl;
	cout << kernel_LU << endl;
	
	cv::Mat img = cv::imread("box.jpg", 0);
	if (img.empty())
	{
		cout << "Image read failed~" << endl;
		return;
	}
	cv::Mat result_1, result_2, result_3, result_4, result_5, result_6, result_7;

	cv::filter2D(img, result_1, CV_16S, kernel_1);
	cv::convertScaleAbs(result_1, result_1);

	cv::filter2D(img, result_2, CV_16S, kernel_2);
	cv::convertScaleAbs(result_2, result_2);

	cv::filter2D(img, result_3, CV_16S, kernel_3);
	cv::convertScaleAbs(result_3, result_3);

	// 把垂直和水平的边缘检测结果组合
	result_4 = result_2 + result_3;

	cv::filter2D(img, result_5, CV_16S, kernel_RU);
	cv::convertScaleAbs(result_5, result_5);

	cv::filter2D(img, result_6, CV_16S, kernel_LU);
	cv::convertScaleAbs(result_6, result_6);

	// 把两个斜向的边缘检测结果组合
	result_7 = result_5 + result_6;

	cv::imshow("vertical_1", result_1);
	cv::imshow("vertical_2", result_2);
	cv::imshow("horizontal", result_3);
	cv::imshow("combine_1", result_4);
	cv::imshow("right_up", result_5);
	cv::imshow("left_up", result_6);
	cv::imshow("combine_2", result_7);
	cv::waitKey(0);
	return 0;
}
测试图片

测试结果



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/718040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号