不使用opencv将膨胀后的图像和腐蚀后的图像相减c语言
时间: 2024-03-13 14:44:19 浏览: 49
c++不调用库函数实现图像的膨胀与腐蚀
5星 · 资源好评率100%
不使用OpenCV库也可以实现膨胀和腐蚀操作,并且可以通过自定义函数实现对两幅图像的相减操作。以下是实现的示例代码:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 膨胀操作
void dilate(unsigned char *src, unsigned char *dst, int width, int height)
{
int i, j, k, l;
unsigned char max_val;
for (i = 1; i < height - 1; i++)
{
for (j = 1; j < width - 1; j++)
{
max_val = 0;
for (k = -1; k <= 1; k++)
{
for (l = -1; l <= 1; l++)
{
if (src[(i + k) * width + j + l] > max_val)
{
max_val = src[(i + k) * width + j + l];
}
}
}
dst[i * width + j] = max_val;
}
}
}
// 腐蚀操作
void erode(unsigned char *src, unsigned char *dst, int width, int height)
{
int i, j, k, l;
unsigned char min_val;
for (i = 1; i < height - 1; i++)
{
for (j = 1; j < width - 1; j++)
{
min_val = 255;
for (k = -1; k <= 1; k++)
{
for (l = -1; l <= 1; l++)
{
if (src[(i + k) * width + j + l] < min_val)
{
min_val = src[(i + k) * width + j + l];
}
}
}
dst[i * width + j] = min_val;
}
}
}
// 图像相减操作
void subtract(unsigned char *src1, unsigned char *src2, unsigned char *dst, int width, int height)
{
int i, j;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
dst[i * width + j] = abs(src1[i * width + j] - src2[i * width + j]);
}
}
}
int main()
{
// 读取原始图像
FILE *fp = fopen("lena.raw", "rb");
if (fp == NULL)
{
printf("读取图像失败!\n");
return -1;
}
int width = 512;
int height = 512;
unsigned char *srcImage = (unsigned char *)malloc(width * height * sizeof(unsigned char));
fread(srcImage, sizeof(unsigned char), width * height, fp);
fclose(fp);
// 将原始图像转化为灰度图像
unsigned char *grayImage = (unsigned char *)malloc(width * height * sizeof(unsigned char));
int i, j;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
grayImage[i * width + j] = srcImage[i * width * 3 + j * 3] * 0.299 + srcImage[i * width * 3 + j * 3 + 1] * 0.587 + srcImage[i * width * 3 + j * 3 + 2] * 0.114;
}
}
// 对灰度图像进行膨胀操作
unsigned char *dilateImage = (unsigned char *)malloc(width * height * sizeof(unsigned char));
dilate(grayImage, dilateImage, width, height);
// 对灰度图像进行腐蚀操作
unsigned char *erodeImage = (unsigned char *)malloc(width * height * sizeof(unsigned char));
erode(grayImage, erodeImage, width, height);
// 对膨胀后的图像和腐蚀后的图像进行相减操作
unsigned char *subtractImage = (unsigned char *)malloc(width * height * sizeof(unsigned char));
subtract(dilateImage, erodeImage, subtractImage, width, height);
// 将差值图像保存为raw格式文件
fp = fopen("subtract.raw", "wb");
fwrite(subtractImage, sizeof(unsigned char), width * height, fp);
fclose(fp);
// 释放内存
free(srcImage);
free(grayImage);
free(dilateImage);
free(erodeImage);
free(subtractImage);
return 0;
}
```
在上述代码中,我们首先读取原始图像并将其转化为灰度图像,然后使用自定义的`dilate()`和`erode()`函数对灰度图像进行膨胀和腐蚀操作,最后使用自定义的`subtract()`函数对膨胀后的图像和腐蚀后的图像进行相减操作,得到差值图像。最后,我们将差值图像保存为raw格式文件。
阅读全文