c - 实现 Sobel 过滤器时出现奇怪的结果

标签 c image-processing

<分区>

我一直在学习计算机视觉,想用 C 语言实现一些简单的技术。对于第一种技术,我正在做 Sobel 边缘检测滤波器。我了解它的工作原理,因此我认为编码应该相当容易,但我得到的结果却很奇怪。

我正在使用下面的图片:

Box

并得到这个结果

Filtered box

新结果!

Filtered box...a little more correct

请注意,我使用的是.ppm图片格式(链接是jpgs,因为我找不到支持.ppm的图片主机)

无论如何,这是我实现 Sobel 的代码部分:

/**********************************************************
This program takes in an image file and applies the Sobel
Filter edge detection technique to it.
**********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ppmReader.h"

void sobelFilter(){


    //Sobel kernels dx (horizontal) and dy (vertical)
    int horizFilter[3][3] = {{ 1,   0,  -1},
                             { 2,   0,  -2},
                             { 1,   0,  -1}};
    int vertFilter[3][3]  = {{ 1,   2,   1},
                             { 0,   0,   0},
                             {-1,  -2,  -1}};
    int pixVal = 0; 
    int horizPixVal = 0;
    int vertPixVal = 0;
    int x, y, i, j;

    //Quick check to make sure dimensions are correct
    printf("Using a Width of: %d\n", width);
    printf("Using a Height of: %d\n\n", height);

    //Start filtering process here
    for(x = 0; x < width; x++){
        for(y = 0; y < height; y++){
            pixVal = 0;
            horizPixVal = 0;
            vertPixVal = 0;
            if(!((x == 0) || (x == width-1) || (y == 0) || (y == height-1))){           //If the current pixel is along the border, ignore it and set to zero
                for(i = -1; i <= 1; i++){                                               //because the kernel does not align to it
                    for(j = -1; j <= 1; j++){
                        horizPixVal += (int)(image[y + j][x + i][0]) * horizFilter[i + 1][j + 1];       //Only need to focus on one of the RGB values since the output is
                        vertPixVal  += (int)(image[y + j][x + i][0]) * vertFilter[i + 1][j + 1];        //greyscale and all three values are the same
                    }
                }
            }
            pixVal = sqrt((horizPixVal * horizPixVal) + (vertPixVal * vertPixVal));     //Calculate magnitude
            pixVal = sqrt(horizPixVal * horizPixVal);
            if(pixVal > 255) pixVal = 255;                                              //Clamp value within 8-bit range
            filteredImage[y][x][0] = (unsigned char)pixVal;                             
        }
    }
}

这是读取 .ppm 文件的代码:

unsigned char image[MAX_IMAGE_HEIGHT][MAX_IMAGE_WIDTH][3];
unsigned char filteredImage[MAX_IMAGE_HEIGHT][MAX_IMAGE_WIDTH][3];

void readPPMImageData(){
    char fileName[MAX_NAME];
    char imageBuff[MAX_BUFF];
    width = 0;
    height = 0;
    maxColor = 0;
    int x;
    int y;

    FILE* file;

    printf("------------------------------------------------------------\n");
    printf("Now attempting to read in the .ppm image file data...\n");
    printf("------------------------------------------------------------\n\n");
    printf("What is the image file name (*.ppm)?  : ");
    scanf("%s", fileName);
    file = fopen(fileName, "rb");               //open the file specified by the user in binary read mode
    if(file == NULL){                           //but if the file was not found, terminate program
        printf("\nThe file %s could not be found! Terminating program...\n", fileName);
        exit(1);
    }

    //The first step is to read in the file type and check it agains P6 (file type of .ppm images)
    fgets(imageBuff, MAX_BUFF, file);
    if(imageBuff[0] != 'P' || imageBuff[1] != '6'){
        printf("\nInvalid image type! Acceptable type is: %s --- Received type is: %c%c\n\n", "P6", imageBuff[0], imageBuff[1]);
    }
    printf("Magic Number is: %c%c\n", imageBuff[0], imageBuff[1]);

    while(width == 0 || height == 0){
        fgets(imageBuff, MAX_BUFF, file);
        if(imageBuff[0] != '#') {
            sscanf(imageBuff, "%d %d", &width, &height);
        }
    }
    printf("Width is: %d\n", width);
    printf("Height is: %d\n", height);
    //if(feof(file)){
    //
    //}

    while(maxColor == 0){
        fgets(imageBuff, MAX_BUFF, file);
        if(imageBuff[0] != '#') {
            sscanf(imageBuff, "%d", &maxColor);
        }
    }
    printf("Maximum color value is: %d\n", maxColor);

    for(x = 0; x < width; x++){
        for(y = 0; y < height; y++){
            image[y][x][0] = (unsigned char)fgetc(file); //Get Red value
            image[y][x][1] = (unsigned char)fgetc(file); //Get Green value
            image[y][x][2] = (unsigned char)fgetc(file); //Get Blue value
        }
    }
    printf("Finished reading image data!\n\n");

    fclose(file);
}

下面是过滤后创建新 .ppm 文件的代码:

void createPPMImage(){
    char fileName[MAX_NAME]; 
    FILE* file;
    int x;
    int y;

    printf("------------------------------------------------------------\n");
    printf("Now attempting to create new .ppm image file...\n");
    printf("------------------------------------------------------------\n\n");
    printf("What is the name of the output image file (*.ppm)?  : ");
    scanf("%s", fileName);

    printf("Width is: %d\n", width);
    printf("Height is: %d\n", height);
    printf("Maximum color value is: %d\n", maxColor);

    file = fopen(fileName, "wb");
    fputs("P6\n", file);
    fprintf(file, "%d %d\n", width, height);
    fprintf(file, "%d\n", maxColor);

    for(x = 0; x < width; x++){
        for(y = 0; y < height; y++){
            fputc(filteredImage[y][x][0], file); //Write Red value
            fputc(filteredImage[y][x][0], file); //Write Green value
            fputc(filteredImage[y][x][0], file); //Write Blue value
        }
    }
    printf("Finished creating new filtered image!\n\n");

    fclose(file);
}

我 100% 确定问题不在于图像的读取或写入,因为我在没有应用过滤器的情况下测试了这些函数,并且只有在我使用上述函数后才会出现问题。

感谢任何帮助,因为据我所知,索引/公式似乎已正确实现,但这显然不是真的。

编辑:正如 Dave 和其他人所指出的,我不再 100% 确定错误在 Sobel 函数内,看起来这只是我在使用.ppm 格式。我继续发布了我的 .ppm 读取器/写入器函数的代码以及应用下面 anatolyg 提出的 [y][x][color] 方案后我得到的新结果。如果我的帖子太长,我很抱歉,如果是的话,请告诉我,因为这是我的第一篇帖子,我还不完全确定什么是合适的。

最佳答案

图像通常首先使用 y 坐标进行索引,然后使用 x 坐标进行索引,如下所示:

... image[y + j][x + i] ...

这是一种防止人们在用 C 处理图像时感到困惑的约定。不幸的是,它与 Matlab 使用的约定有点矛盾,所以我只希望你在 C 中完成这一切。

此外,PPM format specification说红/绿/蓝值是交错的,所以“颜色平面”必须是最后一个索引:

... image[y + j][x + i][0] ...

除非在将输入文件加载到内存中时对输入文件进行了一些重新排序。您没有显示从文件中读取的代码,因此很难知道它是否进行了任何重新排序。


补充:读写文件要按照光栅顺序,即读完一行像素再进行下一行:

for(y = 0; y < height; y++){
    for(x = 0; x < width; x++){
        ...
    }
}

同样推荐采用这种方式进行处理;这不是绝对必须的,但它会减少混淆,并可能使您的处理速度更快(通过更有效地使用 CPU 缓存)。

关于c - 实现 Sobel 过滤器时出现奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886793/

相关文章:

c - 使用自定义 openssl 二进制文件构建 OpenVPN(无源)

python - 如何在Python中仅打开10%放大的jpeg图像?

matlab - 如何在 MATLAB 中向量化这些 while 和嵌套 for 循环?

c - 双链表。我做的好吗?

c - 2 个管道,一个 fork ,bc 和 execlp (C)

c - 将错误文本与 C 中的错误代码相关联

python - 我应该向我的 CNN 提供什么?大输入矩阵还是 10,000 个小输入矩阵?

c - 打印第一位带零的数字

python - 我应该如何将 float32 图像转换为 uint8 图像?

python - 重新着色图像