不用opencv库c语言卷积实现灰度图像的膨胀和腐蚀,并将膨胀和腐蚀后的图像相减
时间: 2024-03-13 10:45:46 浏览: 128
以下是使用C语言实现的代码示例,其中使用了3x3的矩形结构元素:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 640
#define HEIGHT 480
// 灰度图像膨胀
void dilate(unsigned char *src, unsigned char *dst, int width, int height)
{
int i, j, k, l;
unsigned char max_val;
unsigned char kernel[3][3] = {
{1, 1, 1},
{1, 1, 1},
{1, 1, 1}
}; // 3x3的矩形结构元素
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] * kernel[k + 1][l + 1] > max_val) {
max_val = src[(i + k) * width + j + l] * kernel[k + 1][l + 1];
}
}
}
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;
unsigned char kernel[3][3] = {
{1, 1, 1},
{1, 1, 1},
{1, 1, 1}
}; // 3x3的矩形结构元素
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] * kernel[k + 1][l + 1] < min_val) {
min_val = src[(i + k) * width + j + l] * kernel[k + 1][l + 1];
}
}
}
dst[i * width + j] = min_val;
}
}
}
int main()
{
FILE *fp_in, *fp_out;
unsigned char *img_in, *img_out1, *img_out2;
int i, j;
// 读取灰度图像
fp_in = fopen("lena_gray.raw", "rb");
if (!fp_in) {
printf("Cannot open input file.\n");
return -1;
}
img_in = (unsigned char *)malloc(WIDTH * HEIGHT * sizeof(unsigned char));
fread(img_in, sizeof(unsigned char), WIDTH * HEIGHT, fp_in);
fclose(fp_in);
// 分配输出图像内存
img_out1 = (unsigned char *)malloc(WIDTH * HEIGHT * sizeof(unsigned char));
img_out2 = (unsigned char *)malloc(WIDTH * HEIGHT * sizeof(unsigned char));
// 灰度图像膨胀
dilate(img_in, img_out1, WIDTH, HEIGHT);
// 灰度图像腐蚀
erode(img_in, img_out2, WIDTH, HEIGHT);
// 相减得到膨胀和腐蚀后的图像差
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
img_out1[i * WIDTH + j] = img_out1[i * WIDTH + j] - img_out2[i * WIDTH + j];
}
}
// 输出图像差
fp_out = fopen("lena_diff.raw", "wb");
if (!fp_out) {
printf("Cannot open output file.\n");
return -1;
}
fwrite(img_out1, sizeof(unsigned char), WIDTH * HEIGHT, fp_out);
fclose(fp_out);
// 释放内存
free(img_in);
free(img_out1);
free(img_out2);
return 0;
}
```
该程序会读入名为"lena_gray.raw"的灰度图像,然后进行膨胀和腐蚀操作,并将两幅图像相减得到膨胀和腐蚀后的图像差,最后将差图像输出为"lena_diff.raw"文件。
阅读全文