c语言实现灰度图像的腐蚀和膨胀代码
时间: 2023-06-15 15:04:04 浏览: 115
以下是使用C语言实现灰度图像的腐蚀和膨胀的代码示例:
腐蚀:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 512
#define HEIGHT 512
int main(void)
{
unsigned char img[HEIGHT][WIDTH];
unsigned char result[HEIGHT][WIDTH];
int i, j, x, y;
// 读取灰度图像
FILE *fp = fopen("lena512.raw", "rb");
fread(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 腐蚀运算
for (i = 1; i < HEIGHT - 1; i++) {
for (j = 1; j < WIDTH - 1; j++) {
unsigned char min = 255;
for (y = -1; y <= 1; y++) {
for (x = -1; x <= 1; x++) {
if (img[i + y][j + x] < min)
min = img[i + y][j + x];
}
}
result[i][j] = min;
}
}
// 保存结果
fp = fopen("erosion.raw", "wb");
fwrite(result, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
return 0;
}
```
膨胀:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 512
#define HEIGHT 512
int main(void)
{
unsigned char img[HEIGHT][WIDTH];
unsigned char result[HEIGHT][WIDTH];
int i, j, x, y;
// 读取灰度图像
FILE *fp = fopen("lena512.raw", "rb");
fread(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 膨胀运算
for (i = 1; i < HEIGHT - 1; i++) {
for (j = 1; j < WIDTH - 1; j++) {
unsigned char max = 0;
for (y = -1; y <= 1; y++) {
for (x = -1; x <= 1; x++) {
if (img[i + y][j + x] > max)
max = img[i + y][j + x];
}
}
result[i][j] = max;
}
}
// 保存结果
fp = fopen("dilation.raw", "wb");
fwrite(result, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
return 0;
}
```
阅读全文