抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

遍历图像像素

2.1指针扫描

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
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main()
{
Mat image1, output_image; //定义输入图像和输出图像
image1 = imread("lena.png"); //读取图像;
if (image1.empty())
{
cout << "读取错误" << endl;
return -1;
}
output_image = Mat(image1.size(), image1.type()); //定义输出图像大小
output_image = image1.clone(); //克隆原图像素值

int rows = image1.rows; //原图行数
int stepx = image1.channels(); //原图通道数
int cols = (image1.cols) * image1.channels(); //矩阵总列数,在BGR彩色图像中,每个像素的BGR通道按顺序排列,因此总列数=像素宽度*通道数

for (int row =1 ; row < (rows - 1); row++) //对行遍历
{
const uchar* previous = image1.ptr<uchar>(row - 1); //原图上一行指针
const uchar* current = image1.ptr<uchar>(row); //原图当前行指针
const uchar* next = image1.ptr<uchar>(row + 1); //原图下一行指针
uchar* output = output_image.ptr<uchar>(row); //输出图像当前行指针

for (int col = stepx; col < (cols- stepx); col++) //对列遍历
{
output[col] = saturate_cast<uchar>(5*current[col] - (previous[col]+ current[col- stepx]+ current[col + stepx]+ next[col]));
//saturate_cast<uchar>(a),当a在0—255时输出a,当a小于0输出0,当a大于255输出255,保证a的值在0~255之间
}
}

imshow("image1", image1);
imshow("output_image", output_image);

waitKey(0); //暂停,保持图像显示,等待按键结束
return 0;
}

2.2 opencv自带的卷积运算:filter2D

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
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat image1, output_image; //定义输入图像和输出图像
image1 = imread("lena.png"); //读取图像;
if (image1.empty())
{
cout << "读取错误" << endl;
return -1;
}
Mat kernel = (Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
/*
内核值布局:
[ 0, -1, 0 ]
[-1, 5, -1 ]
[ 0, -1, 0 ]
这是一个常见的锐化滤波器,中心像素权重为5,上下左右相邻像素权重为-1,四角为0。通过突出中心像素与周围像素的差异,增强边缘对比度。
卷积核对应相乘再相加
*/
filter2D(image1, output_image, image1.depth(), kernel); //卷积
//image1.depth():指定输出图像的位深与输入一致(如CV_8U表示8位无符号整型)。
imshow("image1", image1);
imshow("output_image", output_image);
waitKey(0); //暂停,保持图像显示,等待按键结束
return 0;
}

评论