sobel代码实现
Sobel主要用于初步寻找图像的边缘信息,同时也可以起到图像锐化作用。常用的3*3的模板卷积实现,主要是通过水平和垂直两个方向卷积实现。
#include <opencv2/opencv.hpp>
#include <iostream>
#include <iostream>
using namespace std;
using namespace cv;
using namespace cv;
Mat sobel(Mat src,Mat dst)
{
int y, x;
int w = src.cols;
int h = src.rows;
int gx = 0, gy = 0;
for (y = 1; y < h - 1; y++)
{
for (x = 1; x < w - 1; x++)
{
gx=src.at<uchar>(y-1,x+1)+src.at<uchar>(y,x+1)*2+src.at<uchar>(y+1,x+1)-src.at<uchar>(y-1,x-1)-src.at<uchar>(y,x-1)*2-src.at<uchar>(y+1,x-1);
gy=src.at<uchar>(y-1,x-1)+src.at<uchar>(y-1,x)*2+src.at<uchar>(y-1,x+1)-src.at<uchar>(y+1,x-1)-src.at<uchar>(y+1,x)*2-src.at<uchar>(y+1,x+1);
dst.at<uchar>(y,x)= abs(gx)+abs(gy) ;
}
}
return dst;
}
int main()
{
char ad[128]={0};
int filename = 0,filenum=0;
Mat img = imread("xjh.jpg");
Mat gray;
Mat dst;
cvtColor(img, gray, CV_BGR2GRAY);
gray.copyTo(dst);
imshow("灰度图",gray);
dst=sobel(gray,dst);
imshow("sobel",dst);
cvWaitKey(0);
return 0;
}
{
int y, x;
int w = src.cols;
int h = src.rows;
int gx = 0, gy = 0;
for (y = 1; y < h - 1; y++)
{
for (x = 1; x < w - 1; x++)
{
gx=src.at<uchar>(y-1,x+1)+src.at<uchar>(y,x+1)*2+src.at<uchar>(y+1,x+1)-src.at<uchar>(y-1,x-1)-src.at<uchar>(y,x-1)*2-src.at<uchar>(y+1,x-1);
gy=src.at<uchar>(y-1,x-1)+src.at<uchar>(y-1,x)*2+src.at<uchar>(y-1,x+1)-src.at<uchar>(y+1,x-1)-src.at<uchar>(y+1,x)*2-src.at<uchar>(y+1,x+1);
dst.at<uchar>(y,x)= abs(gx)+abs(gy) ;
}
}
return dst;
}
int main()
{
char ad[128]={0};
int filename = 0,filenum=0;
Mat img = imread("xjh.jpg");
Mat gray;
Mat dst;
cvtColor(img, gray, CV_BGR2GRAY);
gray.copyTo(dst);
imshow("灰度图",gray);
dst=sobel(gray,dst);
imshow("sobel",dst);
cvWaitKey(0);
return 0;
}