c语言如何基于数学形态学的边缘检测算法的实现代码
时间: 2024-06-12 15:08:04 浏览: 126
基于数学形态学的边缘检测算法研究
以下是基于数学形态学的边缘检测算法的C语言实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define ROWS 256
#define COLS 256
int img[ROWS][COLS], edge[ROWS][COLS], dilated[ROWS][COLS], eroded[ROWS][COLS];
int main()
{
FILE *fp;
char *filename = "lena.raw";
int i, j, k, l, m, n, max_intensity = 0;
// 读取图像
if ((fp = fopen(filename, "rb")) == NULL) {
printf("Error: Cannot open file %s\n", filename);
return 1;
}
fread(img, sizeof(unsigned char), ROWS * COLS, fp);
fclose(fp);
// 计算梯度
for (i = 1; i < ROWS - 1; i++) {
for (j = 1; j < COLS - 1; j++) {
int gx = img[i + 1][j] - img[i - 1][j];
int gy = img[i][j + 1] - img[i][j - 1];
edge[i][j] = sqrt(gx * gx + gy * gy);
if (edge[i][j] > max_intensity) max_intensity = edge[i][j];
}
}
// 归一化
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
edge[i][j] = (int) (edge[i][j] * 255.0 / max_intensity);
}
}
// 二值化
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (edge[i][j] > 128) edge[i][j] = 255;
else edge[i][j] = 0;
}
}
// 膨胀
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
int max = 0;
for (k = -1; k <= 1; k++) {
for (l = -1; l <= 1; l++) {
if (i + k >= 0 && i + k < ROWS && j + l >= 0 && j + l < COLS) {
if (edge[i + k][j + l] > max) max = edge[i + k][j + l];
}
}
}
dilated[i][j] = max;
}
}
// 腐蚀
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
int min = 255;
for (k = -1; k <= 1; k++) {
for (l = -1; l <= 1; l++) {
if (i + k >= 0 && i + k < ROWS && j + l >= 0 && j + l < COLS) {
if (dilated[i + k][j + l] < min) min = dilated[i + k][j + l];
}
}
}
eroded[i][j] = min;
}
}
// 计算边缘
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
edge[i][j] = dilated[i][j] - eroded[i][j];
}
}
// 输出边缘图像
if ((fp = fopen("edge.raw", "wb")) == NULL) {
printf("Error: Cannot open file edge.raw\n");
return 1;
}
fwrite(edge, sizeof(unsigned char), ROWS * COLS, fp);
fclose(fp);
return 0;
}
阅读全文