1 /*
2 矩阵的掩膜操作
3
4 0 掩膜mask 在这里进行增强对比度:
5 [
6 [ 0,-1, 0 ],
7 [-1, 5, -1],
8 [ 0,-1, 0 ]
9 ]
10 使用mask滑动图片每一个位置,进行卷积运算
11 这里这个mask会增强图片的对比度
12
13 1 获取图像指针
14 const uchar* current = Mat对象.ptr<uchar>(row)
15 获取了 当前图像的 第row行像素的数组
16
17 p(row, col) = current[col]
18 获取了第row行第col列的点
19
20 2 像素范围处理 确保值在0到255之间
21 saturate_cast<uchar>(值)
22 传入值小于0时候返回0
23 大于255时候 返回255
24 在0-255之间 返回正常数
25
26 3 定义掩膜
27 Mat kernel = (Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
28 定义了一个3*3大小的掩膜,里面的内容:
29 [
30 [ 0,-1, 0 ],
31 [-1, 5, -1],
32 [ 0,-1, 0 ]
33 ]
34 4 掩膜运算
35 filter2D(src, dst, src.depth(), kernel)
36 src: 原图像
37 dst: 输出图像
38 src.depth() 原图像的深度 32 24 8 等
39 kernel: 掩膜核
40 */
41
42 #include <opencv2/opencv.hpp>
43 #include <iostream>
44 #include <math.h>
45 using namespace cv;
46
47 int main() {
48 Mat src, dst;
49 src = imread("d:/图片/m2.jpg"); // 载入原图像
50 if (!src.data) { // 如果有读取到
51 printf("没有找到图片");
52 return -1;
53 }
54 // 显示原始图像
55 namedWindow("输入图片", CV_WINDOW_AUTOSIZE);
56 imshow("输入图片", src);
57
58 // 输出图像的初始化 与原图像相同,像素值初始化为0
59 dst = Mat::zeros(src.size(), src.type());
60
61 /*
62 // 手动实现一个掩膜操作
63
64 // 图像的宽度 为 宽度*通道数
65 int cols = (src.cols) * src.channels(); // 列数 宽度
66 int rows = src.rows; // 行数 高度
67 int offsetx = src.channels(); // 通道数 存在列里面
68
69 // 掩膜操作没有从0 0 开始是为了把边界让开,掩膜是3*3的, 中间一个是目标位置。
70 for (int row = 1; row < rows - 1; row++) {
71 // 获取通道对应的指针
72 const uchar* previous = src.ptr<uchar>(row - 1);
73 const uchar* current = src.ptr<uchar>(row);
74 const uchar* next = src.ptr<uchar>(row + 1);
75 uchar* output = dst.ptr<uchar>(row);
76 for (int col = offsetx; col < cols - offsetx ; col++) {
77 // 掩膜运算 并且控制像素值在0到255之间
78 output[col] = saturate_cast<uchar>( // 控制像素值0到255之间
79 5 * current[col] - // 当前像素值
80 (
81 current[col - offsetx] + // 左边像素值
82 current[col + offsetx] + // 右边像素值
83 previous[col]+next[col] // 上合下的像素值
84 )
85 );
86 }
87 }
88
89 */
90 // 计算时间花费
91 double t = getTickCount();
92
93 // 调用掩膜运算
94 // 初始化一个掩膜
95 Mat kernel = (Mat_<char>(3, 3) <<
96 0, -1, 0,
97 -1, 5, -1,
98 0, -1, 0);
99 filter2D(src, dst, src.depth(), kernel);
100
101 // 计算时间花费
102 double time_cost = (getTickCount() - t) /getTickFrequency();
103 printf("花费时间:%f", time_cost);
104
105 namedWindow("掩膜操作", CV_WINDOW_AUTOSIZE);
106 imshow("掩膜操作", dst);
107
108 waitKey(0);
109 return 0;
110 }