一些图像处理的函数
Published in:2024-04-29 | category: 智能车
Words: 379 | Reading time: 2min | reading:

中值滤波

卷积核大小为7:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Mat medianFilter(Mat imgO) {
// 创建一个新的Mat对象用于存储滤波后的图像
Mat img1 = Mat::zeros(imgO.rows - 6, imgO.cols - 6, CV_8U);

// 对输入图像进行中值滤波
for (int y = 3; y < imgO.rows - 3; y++) {
for (int x = 3; x < imgO.cols - 3; x++) {
vector<uchar> values;
for (int j = -3; j <= 3; j++) {
for (int i = -3; i <= 3; i++) {
values.push_back(imgO.at<uchar>(y + j, x + i));
}
}
// 对values数组中的值进行排序
sort(values.begin(), values.end());

// 计算中值并赋值给输出图像
img1.at<uchar>(y - 3, x - 3) = values[values.size() / 2];
}
}

return img1;
}

效果

sobel算子边缘检测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Mat sobel3(Mat inputImg) {
int gx, gy;
Mat tempImg;
inputImg.copyTo(tempImg); // 为了能够在输出图像中访问原始输入图像的像素值

Mat outputImg = Mat::zeros(inputImg.size(), inputImg.type());

for (int y = 1; y < inputImg.rows - 1; y++) {
for (int x = 1; x < inputImg.cols - 1; x++) {
gx = (-1 * tempImg.at<uchar>(y - 1, x - 1) + 1 * tempImg.at<uchar>(y - 1, x + 1) +
-2 * tempImg.at<uchar>(y, x - 1) + 2 * tempImg.at<uchar>(y, x + 1) +
-1 * tempImg.at<uchar>(y + 1, x - 1) + 1 * tempImg.at<uchar>(y + 1, x + 1)) / 4;
gy = (1 * tempImg.at<uchar>(y - 1, x - 1) + 2 * tempImg.at<uchar>(y - 1, x) + 1 * tempImg.at<uchar>(y - 1, x + 1) +
-1 * tempImg.at<uchar>(y + 1, x - 1) - 2 * tempImg.at<uchar>(y + 1, x) - 1 * tempImg.at<uchar>(y + 1, x + 1));

outputImg.at<uchar>(y, x) = (abs(gx) + abs(gy)) / 2;
}
}

return outputImg.clone(); // 返回outputImg的副本
}

效果

Prev:
C++多线程
Next:
AuTop代码整理