0

我有 9 张关于一个人的照片,但对于 9 张照片中的每一张,他都站在不同的位置。第一个嵌套的 for 循环创建了一个三元组,其中 j=picture 并且 x 和 y 表示每张图片中像素的坐标。我使用 getpixel 函数将它们存储在这个三重循环中。我的问题在于第二个嵌套的 for 循环。我为每个像素的 rgb 值创建一个数组,然后对它们进行冒泡排序以找到中值。从理论上讲,这应该返回一个男人已经消失并且只剩下照片背景的图像。但是它不起作用,仍然显示与其中的人的图片。我究竟做错了什么?

  #include <iostream>
   #include <stdlib.h>
   #include <cmath>
   #include <ctime>
   #include <graphics.h>
   #include <stdio.h>

   using namespace std;

void loadImage(int imageNumber);
void bubbleSort(arr[], int n);

int main()
{
    //triple array to work with all 9 pics
    int picture[9][200][225];

    int redArray[9];
    int greenArray[9];
    int blueArray[9];

    //size of the 3 arrays to be used in bubble sort
    int n1=sizeof(redArray);
    int n2=sizeof(greenArray);
    int n3=sizeof(blueArray);

    //window that displays the picture
    initwindow(600, 625, "tourist");


    //stores the pixel value for all 9 pictures
    for(int j=0; j<9; j++)
    {
        loadImage(j);
        {
            for(int x=0; x<200; x++)
            {
                for(int y=0; y<225; y++)
                {   
                    picture[j][x][y]=getpixel(x, y);
                }   
            }
        }
    }

    //sets the rgb values of all the pixels of all the pictures  and bubble sorts them
    //using the median value of 9 elements(4th value) to remove the person from the picture
    for(int x=0; x<200; x++)
    {
        for(int y=0; y<225; y++)
        {
            for(int j=0; j<9; j++)
            {


                redArray[j]=RED_VALUE(picture[j][x][y]);
                greenArray[j]=GREEN_VALUE(picture[j][x][y]);
                blueArray[j]=BLUE_VALUE(picture[j][x][y]);
            }


            bubbleSort(redArray[], n1);
            bubbleSort(greenArray[], n2);
            bubbleSort(blueArray[], n3);

            //putpixel redarray[4]
            putpixel(x,y,Color(redArray[4], greenArray[4], blueArray[4]);

        }   
    }

    getch();    
}

//this is a BGI function that loads the image onto the current window
void loadImage(int imageNumber)
{
     char str[5];
     sprintf(str, "%i.jpg", imageNumber);
     readimagefile(str,0,0,200,225); 
}

void bubbleSort(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < n - i - 1; ++j)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }   


    }  

}   
4

1 回答 1

1

这条线

int n1=sizeof(redArray);

将 n1 设置为 9 个整数的大小,可能是 36(取决于您的机器架构)

然后,您将其用作冒泡排序的输入,这意味着您的冒泡排序超出了数组边界。这是未定义的行为,可能导致数组中的值不正确。

将行更改为

int n1=sizeof(redArray) / sizeof (redArray[0]);

或者甚至只是9在其他几个地方使用它(也许您可以将 a 定义const int为 9 以便您以后可以轻松更改它。

于 2016-04-14T23:55:55.747 回答