使用c++而不用Opencv实现任务: 1)常见格式图像的读写(灰度图); 2)设计并实现上述平滑算子和锐化算子; 3)(选作)查阅其他的平滑和锐化算子并实现; 4)可视化展示处理前后图像的变化,并尝试进行分析。
时间: 2024-02-24 15:55:40 浏览: 67
以下是使用C++和STB库(stb_image.h和stb_image_write.h)实现平滑和锐化操作的示例代码:
```
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <iostream>
#include "stb_image.h"
#include "stb_image_write.h"
using namespace std;
// 定义高斯平滑算子
const float gaussian_kernel[5][5] = {
{0.003, 0.013, 0.022, 0.013, 0.003},
{0.013, 0.059, 0.097, 0.059, 0.013},
{0.022, 0.097, 0.159, 0.097, 0.022},
{0.013, 0.059, 0.097, 0.059, 0.013},
{0.003, 0.013, 0.022, 0.013, 0.003}
};
// 定义拉普拉斯锐化算子
const float laplacian_kernel[3][3] = {
{0, -1, 0},
{-1, 5, -1},
{0, -1, 0}
};
// 读入灰度图像
unsigned char* read_image(const char* filename, int& width, int& height, int& channels)
{
unsigned char* data = stbi_load(filename, &width, &height, &channels, 1);
if (!data)
{
cerr << "Failed to read image: " << filename << endl;
exit(1);
}
return data;
}
// 写入灰度图像
void write_image(const char* filename, unsigned char* data, int width, int height)
{
stbi_write_png(filename, width, height, 1, data, width);
}
// 高斯平滑
void gaussian_blur(unsigned char* src, unsigned char* dst, int width, int height)
{
for (int i = 2; i < height - 2; i++)
{
for (int j = 2; j < width - 2; j++)
{
float sum = 0;
for (int m = -2; m <= 2; m++)
{
for (int n = -2; n <= 2; n++)
{
sum += src[(i + m) * width + (j + n)] * gaussian_kernel[m + 2][n + 2];
}
}
dst[i * width + j] = (unsigned char)sum;
}
}
}
// 拉普拉斯锐化
void laplacian_sharpen(unsigned char* src, unsigned char* dst, int width, int height)
{
for (int i = 1; i < height - 1; i++)
{
for (int j = 1; j < width - 1; j++)
{
float sum = 0;
for (int m = -1; m <= 1; m++)
{
for (int n = -1; n <= 1; n++)
{
sum += src[(i + m) * width + (j + n)] * laplacian_kernel[m + 1][n + 1];
}
}
if (sum > 255) sum = 255;
if (sum < 0) sum = 0;
dst[i * width + j] = (unsigned char)sum;
}
}
}
int main()
{
// 读入灰度图像
int width, height, channels;
unsigned char* data = read_image("image.jpg", width, height, channels);
// 高斯平滑
unsigned char* smoothed = new unsigned char[width * height];
gaussian_blur(data, smoothed, width, height);
// 拉普拉斯锐化
unsigned char* sharpened = new unsigned char[width * height];
laplacian_sharpen(data, sharpened, width, height);
// 写入灰度图像
write_image("smoothed.png", smoothed, width, height);
write_image("sharpened.png", sharpened, width, height);
// 释放内存
stbi_image_free(data);
delete[] smoothed;
delete[] sharpened;
return 0;
}
```
在该实现中,我们使用STB库来读写图像,使用数组定义高斯平滑算子和拉普拉斯锐化算子,并实现了相应的高斯平滑和拉普拉斯锐化函数。最后,我们将处理后的图像写入到对应的文件中。
需要注意的是,在读入灰度图像时,我们需要指定`channels`为1,即只读入一个通道。在写入灰度图像时,我们需要指定通道数为1,并传入单通道的灰度数据。
通过对处理前后图像的对比可以发现,在经过高斯平滑处理后,图像的噪点和细节都被模糊化了,整体视觉效果更加平滑、柔和;在经过拉普拉斯锐化处理后,图像的边缘信息被突出了,整体视觉效果更加清晰、鲜明。
阅读全文