MST
星途 面试题库

面试题:C语言多维数组指针在图像处理中的应用

在图像处理中,图像可以表示为一个二维数组(灰度图像)或三维数组(彩色图像,RGB三个通道)。假设我们有一个灰度图像,以二维数组形式存储,每个元素代表一个像素的灰度值。现在需要编写一个函数,使用多维数组指针实现图像的边缘检测(例如简单的Sobel算子)。函数原型为:unsigned char** edgeDetection(unsigned char** image, int height, int width)。要求在实现过程中合理使用指针操作提高效率,并且要正确处理图像边界情况。
29.0万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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函数进行边缘检测,最后输出结果并释放分配的内存。