面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 计算Sobel算子在x方向的梯度
int sobelX(int g[3][3]) {
return g[0][0] + 2 * g[0][1] + g[0][2] - g[2][0] - 2 * g[2][1] - g[2][2];
}
// 计算Sobel算子在y方向的梯度
int sobelY(int g[3][3]) {
return g[0][0] + 2 * g[1][0] + g[2][0] - g[0][2] - 2 * g[1][2] - g[2][2];
}
unsigned char** edgeDetection(unsigned char** image, int height, int width) {
unsigned char** edges = (unsigned char**)malloc(height * sizeof(unsigned char*));
for (int i = 0; i < height; i++) {
edges[i] = (unsigned char*)malloc(width * sizeof(unsigned char));
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height - 1 || j == 0 || j == width - 1) {
edges[i][j] = 0; // 边界像素设为0
} else {
int g[3][3];
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
g[x + 1][y + 1] = image[i + x][j + y];
}
}
int gradX = sobelX(g);
int gradY = sobelY(g);
int grad = abs(gradX) + abs(gradY);
if (grad > 255) {
grad = 255;
}
edges[i][j] = (unsigned char)grad;
}
}
}
return edges;
}
可以使用如下方式调用:
int main() {
// 简单示例,构建一个小的图像
int height = 5;
int width = 5;
unsigned char** image = (unsigned char**)malloc(height * sizeof(unsigned char*));
for (int i = 0; i < height; i++) {
image[i] = (unsigned char*)malloc(width * sizeof(unsigned char));
for (int j = 0; j < width; j++) {
image[i][j] = (unsigned char)(i * width + j);
}
}
unsigned char** edges = edgeDetection(image, height, width);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("%3d ", edges[i][j]);
}
printf("\n");
}
// 释放内存
for (int i = 0; i < height; i++) {
free(image[i]);
free(edges[i]);
}
free(image);
free(edges);
return 0;
}
上述代码实现了一个基于Sobel算子的边缘检测函数edgeDetection
,该函数接收一个二维数组形式存储的灰度图像、图像的高度和宽度作为参数,并返回一个经过边缘检测后的二维数组。在函数内部,通过指针操作遍历图像的每个像素,并使用Sobel算子计算梯度,从而检测出图像的边缘。在main
函数中构建了一个简单的图像示例,并调用edgeDetection
函数进行边缘检测,最后输出结果并释放分配的内存。