膨胀腐蚀代码纯C++,不调用opencv
时间: 2024-02-07 09:03:22 浏览: 158
以下是使用纯C++实现的膨胀和腐蚀操作的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义结构元素
const int SE_SIZE = 3;
const int SE[SE_SIZE][SE_SIZE] = {
{0, 1, 0},
{1, 1, 1},
{0, 1, 0}
};
// 膨胀操作
void dilate(const vector<vector<int>>& src, vector<vector<int>>& dst)
{
int rows = src.size();
int cols = src[0].size();
dst.resize(rows, vector<int>(cols, 0));
for (int i = 1; i < rows - 1; i++)
{
for (int j = 1; j < cols - 1; j++)
{
int max_val = 0;
for (int m = -1; m <= 1; m++)
{
for (int n = -1; n <= 1; n++)
{
int val = src[i + m][j + n] + SE[m + 1][n + 1];
if (val > max_val)
max_val = val;
}
}
dst[i][j] = max_val;
}
}
}
// 腐蚀操作
void erode(const vector<vector<int>>& src, vector<vector<int>>& dst)
{
int rows = src.size();
int cols = src[0].size();
dst.resize(rows, vector<int>(cols, 0));
for (int i = 1; i < rows - 1; i++)
{
for (int j = 1; j < cols - 1; j++)
{
int min_val = 255;
for (int m = -1; m <= 1; m++)
{
for (int n = -1; n <= 1; n++)
{
int val = src[i + m][j + n] - SE[m + 1][n + 1];
if (val < min_val)
min_val = val;
}
}
dst[i][j] = min_val;
}
}
}
int main()
{
// 读取图像
Mat src = imread("lena.jpg", IMREAD_GRAYSCALE);
// 转换为二维数组
vector<vector<int>> src_vec(src.rows, vector<int>(src.cols, 0));
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
src_vec[i][j] = src.at<uchar>(i, j);
}
}
// 膨胀操作
vector<vector<int>> dilate_img;
dilate(src_vec, dilate_img);
// 腐蚀操作
vector<vector<int>> erode_img;
erode(src_vec, erode_img);
// 转换为Mat类型并显示结果
Mat dilate_mat(src.rows, src.cols, CV_8UC1);
Mat erode_mat(src.rows, src.cols, CV_8UC1);
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
dilate_mat.at<uchar>(i, j) = dilate_img[i][j];
erode_mat.at<uchar>(i, j) = erode_img[i][j];
}
}
imshow("src", src);
imshow("dilate", dilate_mat);
imshow("erode", erode_mat);
waitKey(0);
return 0;
}
```
在代码中,我们首先读取图像,然后将其转换为二维数组。接着,我们定义了膨胀和腐蚀操作的函数,利用定义的结构元素对图像进行操作。最后,我们将结果转换为Mat类型并输出。
阅读全文