OpenCV12.Sobel算子

tech2026-09-23  1

卷积应用-图像边缘提取

边缘是什么 – 是像素值发生跃迁的地方,是图像的显著特征之一,在图像特征提取、对象检测、模式识别等方面都有重要的作用。 如何捕捉/提取边缘 – 对图像求它的一阶导数 delta = f(x) – f(x-1), delta越大,说明像素在X方向变化越大,边缘信号越强

相关API

Sobel(

src, dst,

depth //输出图像深度,只能大于等于原来的深度

int dx //x方向几阶导数

int dy //y方向几阶导数

int ksize,Sobel算子kernel大小,必须为1、3、5或7)

输入深度输出深度CV_8U-1/CV_16S/CV_32F/CV_64FCV_16U/CV_16S-1/CV_32F/CV_64FCV_32F-1/CV_32F/CV_64FCV_64F-1/CV_64F

Scharr是OpenCv为Sobel的改进版

convertScaleAbs(a, b) //计算a的绝对值输出到b,可将任意类型的数据转化为CV_8UC1

对于src*alpha+beta的结果如果是负值且大于-255,则直接取绝对值;

对于src*alpha+beta的结果如果大于255,则取255;

对于src*alpha+beta的结果是负值,且小于-255,则取255;

对于src*alpha+beta的结果如果在0-255之间,则保持不变;

代码展示

#include <iostream> #include "opencv2/opencv.hpp" using namespace std; using namespace cv; int main() { Mat src; src = imread("F:/Opencvlearn/picture/2.jpg"); if (src.empty()) { printf("could not load image...\n"); return -1; } namedWindow("input", WINDOW_AUTOSIZE); imshow("input", src); Mat src_blur, gray; GaussianBlur(src, src_blur, Size(3, 3), 0, 0); cvtColor(src_blur, gray, COLOR_BGR2GRAY); imshow("gray_blur", gray); Mat Sobel_x, Sobel_y; Sobel(gray, Sobel_x, CV_16S, 1, 0, 3); Sobel(gray, Sobel_y, CV_16S, 0, 1, 3); //Scharr(gray, Sobel_x, CV_16S, 1, 0, 3); //OpenCV改进的Sobel算子 //Scharr(gray, Sobel_y, CV_16S, 0, 1, 3); convertScaleAbs(Sobel_x, Sobel_x); //对像素取绝对值并转换为uchar类型 convertScaleAbs(Sobel_y, Sobel_y); imshow("Sobel_x", Sobel_x); imshow("Sobel_y", Sobel_y); Mat Sobel_xy = Mat(Sobel_x.size(), Sobel_x.type()); addWeighted(Sobel_x, 1, Sobel_y, 1, 0, Sobel_xy); //两图像素相加 imshow("Sobel_xy", Sobel_xy); //手动方式 //for (int row = 0; row < Sobel_x.rows; ++row) //{ // for (int col = 0; col < Sobel_x.cols; ++col) // { // int x = Sobel_x.at<uchar>(row, col); // int y = Sobel_y.at<uchar>(row, col); // int xy = x + y; // Sobel_xy.at<uchar>(row, col) = saturate_cast<uchar>(xy); // } //} //imshow("final", Sobel_xy); waitKey(0); return 0; }
最新回复(0)