VS2015+OpenCV4.5.2 Sobel梯度算子源码

该篇博客介绍了如何使用OpenCV库在C++中实现Sobel梯度算子进行图像锐化。首先读取图像,然后通过扩充边界以适应卷积操作。接着,博主展示了Sobel算子的卷积过程,通过对图像每个像素应用Sobel核来计算梯度,并通过求平方根得到最终的锐化效果。最后,使用medianBlur函数进行中值滤波以平滑噪声,显示了原图、滤波后的图像以及锐化结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

附上源码,多多指教。

#include<opencv.hpp>
#include<iostream>

using namespace std;
using namespace cv;

int main()
{
	//1、读入图片
	Mat src, dst;
	src = imread("Bone.jpg", 0);
    //2、扩充边界以进行卷积
	copyMakeBorder(src, dst, 2, 2, 2, 2, BORDER_CONSTANT, Scalar(0));
	//3、Sobel梯度算子锐化
	Mat image_sobel;
	dst.copyTo(image_sobel);
	for (int i = 2; i < src.rows - 2; i++)
	{
		uchar *current = dst.ptr(i);
		uchar *upper = dst.ptr(i - 1);
		uchar *lower = dst.ptr(i + 1);
		uchar *result = image_sobel.ptr(i);
		//开始遍历
		for (int j = 2; j < dst.cols - 2; j++)
		{
			//Sobel算子卷积核:
		    //x方向:Mat x<<-1,-2,-1,0,0,0,1,2,1     y方向:Mat y<<-1,0,1,-2,0,2,-1,0,1
			int x = lower[j - 1] + 2 * lower[j] + lower[j + 1] - upper[j - 1] - 2 * upper[j] - upper[j + 1];
			int y = upper[j + 1] + 2 * current[j + 1] + lower[j + 1] - upper[j - 1] - 2 * current[j] - lower[j - 1];
			result[j] = sqrt(x*x + y*y);
		}
	}
	imshow("Src image", src);
	Mat filter;
	//boxFilter(image_sobel,filter, image_sobel.depth(),Size(3,3));
	//GaussianBlur(image_sobel, filter, Size(13, 13), 2);
	medianBlur(image_sobel, filter, 3);
	imshow("Image of filter", filter);
	imshow("Result image", image_sobel);
	while (waitKey(0) != 'q') {};
	return 0;
}

原图:
在这里插入图片描述
Sobel算子处理:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值