http://blog.csdn.net/poem_qianmo/article/details/25560901
#include<iostream>
#include<opencv2/core/core.hpp>#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
Mat src, dst, gray;
Mat canny;
int cannylowThresh = 1;
Mat sobel_x, sobel_y;
Mat sobelAbs_x, sobelAbs_y;
int sobelKernelSize = 1;
Mat scharr_x, scharr_y;
Mat scharrAbs_x, scharrAbs_y;
static void showText();
static void on_Canny(int,void *);
static void on_Sobel(int,void *);
void Scharr();
int main(){
showText();
src = imread("1.jpg");
if (!src.data)
{
cout << "oh no wrong" << endl;
}
dst.create(src.size(), src.type());
//将原图转换成灰度图像
cvtColor(src,gray,CV_BGR2GRAY);
namedWindow("Canny");
namedWindow("Sobel");
createTrackbar("参数值:", "Canny", &cannylowThresh, 120, on_Canny);
createTrackbar("参数值:", "Sobel", &sobelKernelSize, 3, on_Sobel);
on_Canny(0,0);
on_Sobel(0,0);
Scharr();
while (char(waitKey(0) != 'q')){}
return 0;
}
void showText(){
cout << "开始作业啦~~~"
<< "q 时,退出"
<< endl;
}
//高阶的canny用法,转成灰度图,降噪,用canny,最后将得到的边缘作为掩码,拷贝原图到效果图上,得到彩色的边缘图
static void on_Canny(int, void *){
//先使用3X3内核来降噪
blur(gray,canny,Size(3,3));
Canny(canny, canny,cannylowThresh, cannylowThresh * 3, 3);
//先将dst内的所有元素设置为0
dst = Scalar::all(0);
//将canny算子输出的边缘图作为掩码,来将原图拷到目标图中
src.copyTo(dst,canny);
imshow("Canny",dst);
}
static void on_Sobel(int, void *){
//求x方向梯度
Sobel(src,sobel_x,CV_16S,1,0,(2*sobelKernelSize+1),1,1,BORDER_DEFAULT);
convertScaleAbs(sobel_x, sobelAbs_x);
//求Y方向梯度
Sobel(src, sobel_y, CV_16S, 0, 1, (2 * sobelKernelSize + 1), 1, 1, BORDER_DEFAULT);
convertScaleAbs(sobel_y, sobelAbs_y);
addWeighted(sobelAbs_x,0.5,sobelAbs_y,0.5,0,dst);
imshow("Sobel",dst);
}
void Scharr(){
//求x方向梯度
Scharr(src,scharr_x,CV_16S,1,0,1,0,BORDER_DEFAULT);
convertScaleAbs(scharr_x, scharr_x);
//求y方向梯度
Scharr(src, scharr_y, CV_16S, 0, 1, 0, 1, BORDER_DEFAULT);
convertScaleAbs(scharr_y, scharr_y);
//合并梯度
addWeighted(scharr_x, 0.5, scharr_y,0.5,0.,dst);
imshow("Scharr",dst);
}