1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat srcImage = imread("4.jpg");
if (!srcImage.data)
{
printf("Oh, no, srcImage is error");
return -1;
}
namedWindow("srcImage");
namedWindow("Canny1");
namedWindow("Canny2");
namedWindow("Sobel");
namedWindow("Laplace");
namedWindow("Scharr");
imshow("srcImage", srcImage);
//一.最简单的Canny用法
Mat dstImage;
dstImage = srcImage.clone();
Canny(srcImage, dstImage, 3, 9, 3);
imshow("Canny1", dstImage);
//二.高阶的Canny用法, 转成灰度图,降噪,用Canny,最后将得到的边缘作为掩码,
//拷贝原图到效果图上,得到彩色的边缘图
Mat dst, edge, gray;
//1.创建与src同类型和大小的矩阵dst
dst.create(srcImage.size(), srcImage.type());
//2.将原图转换为灰色图像
cvtColor(srcImage, gray, CV_BGR2GRAY);
//3.先用使用3*3内核降噪
blur(gray, edge, Size(3, 3));
//4.运行Canny算子
Canny(edge, edge, 3, 9, 3);
//5.将dst内的所有元素设为0
dst = Scalar::all(0);
//6.使用Canny算子输出的边缘图g_cannyDetectedEdges作为掩码,来将原图srcImage拷到目标图dst中
srcImage.copyTo(dst, edge);
imshow("Canny2", dst);
//sobel算子
Mat dst_x, dst_y;
Mat s_dst_x, s_dst_y;
Mat ddst;
//1.求x方向的梯度
Sobel(srcImage, dst_x, CV_16S, 1, 0, 3, 1, 1, BORDER_DEFAULT);
convertScaleAbs(dst_x, s_dst_x);
imshow("X_Sobel", s_dst_x);
//2.求y方向的梯度
Sobel(srcImage, dst_y, CV_16S, 0, 1, 3, 1, 1, BORDER_DEFAULT);
convertScaleAbs(dst_y, s_dst_y);
imshow("Y_Sobel", s_dst_y);
//合并梯度
addWeighted(s_dst_x, 0.5, s_dst_y, 0.5, 0, ddst);
imshow("Sobel", ddst);
//Laplace算子
Mat l_gray, l_dst, l_abs_dst;
//1.使用高斯滤波消除噪声
GaussianBlur(srcImage, l_dst, Size(3, 3), 0, 0, BORDER_DEFAULT);
//2.转为灰度图
cvtColor(srcImage, l_gray, CV_RGB2GRAY);
//3.使用Laplace函数
Laplacian(l_gray, l_ds, CV_16S, 3, t1, 0, BORDER_DEFAULT);
//4.计算绝对值,并将结果转换成8位
convertScaleAbs(l_dst, l_abs_dst);
imshow("Laplace", l_abs_dst);
//Scharr滤波器
Mat s_x, s_y;
Mat s_abs_x, s_abs_y, s_dst;
//1.求X方向梯度
Scharr(srcImage, s_x, CV_16S, 1, 0, 1, 0, BORDER_DEFAULT);
convertScaleAbs(s_x, s_abs_x);
imshow("X_Scharr", s_abs_x);
//2.求Y方向梯度
Scharr(srcImage, s_y, CV_16S, 0, 1, 1, 0, BORDER_DEFAULT);
convertScaleAbs(s_y, s_abs_y);
imshow("Y_Scharr", s_abs_y);
//3.合并梯度
addWeighted(s_abs_x, 0.5, s_abs_y, 0.5, 0, s_dst);
imshow("Scharr", s_dst);
waitKey(0);
return 0;
}
|