18 - Sobel 算子测试
代码和理解注释:
#include<opencv2/opencv.hpp>;
using namespace cv;
int main(int argc,char* argv) { // 18 - Sobel算子
Mat source1,change1;
source1 = imread("F:\\OpenCV-Test\\TestPicture\\SourcePicture1\\1.PNG");
if (!source1.data) { printf("can not load image ... \n"); return -1; }
imshow("source1",source1);
Mat source1Gray;
GaussianBlur(source1,change1,Size(3,3),0,0);
cvtColor(change1,source1Gray,6);
imshow("source1Gray",source1Gray);
Mat Xgrad, Ygrad;
// Scharr(source1Gray, Xgrad, CV_16S, 1, 0); //Scharr是Sobel加强版: XY -10 +10,增加权重扩大XY梯度
// Scharr(source1Gray, Ygrad,CV_16S,0,1);
Sobel(source1Gray, Xgrad, CV_16S, 1, 0, 3); // XY -2 +2,增加权重扩大XY梯度
// (输入图像,输出图像,输出图像位图深度,X方向,Y方向,卷积核3*3): X方向Sobel算子
Sobel(source1Gray, Ygrad, CV_16S, 0, 1, 3); // Y方向Sobel算子
convertScaleAbs(Xgrad, Xgrad); // 像素值 反转
convertScaleAbs(Ygrad, Ygrad);
// imshow("Xgrad-Scharr", Xgrad);
// imshow("Ygrad-Scharr", Ygrad);
Mat XYgrad = Mat(Xgrad.size(), Xgrad.type());
addWeighted(Xgrad, 0.5, Ygrad, 0.5, 0, XYgrad);
// 将每个像素点XY方向Sobel算法之后0.5权重相加的像素值赋给新图像,像素点的值四分之一; 图像轮廓
imshow("XYgrad - 权重",XYgrad);
//printf("type= %d\n",XYgrad);
int cols = Xgrad.cols;
int rows = Xgrad.rows;
for (int row = 0; row < rows;row++) {
for (int col = 0; col < cols;col++) {
int Xg = Xgrad.at<char>(row, col);
int Yg = Ygrad.at<char>(row,col);
int XY = Xg + Yg;
XYgrad.at<char>(row, col) = saturate_cast<uchar>(XY);
// 将每个像素点XY方向Sobel算法之后相加的像素值赋给新图像,算出整个图像Sobel算法; 图像轮廓
}
}
imshow("XYgrad-XY相加",XYgrad);
waitKey(0);
return 0;
}
代码演示效果:
一:Sobel-XY方向算法图像
二: Scharr - XY 方向算法图像
三:18 - Sobel XYGrad-之后对XY方向像素 2种不同处理结果
四:Scharr XYGrad-之后对XY方向像素 2种不同处理结果