Problems with [] [] and if-statement

I have a bug in my program, which I will discuss below:

int[][]image =
    {
        {0,0,2,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0}//assume this rectangular image
    };  

    int[][]smooth = new int[image.length][image[0].length]; //new array equal to image[][]

      

Pay attention to the image [] []. It is a 2D array made up of a series of numbers. The code right below it initializes a new 2D array called smooth [] [], which is identical to image [] [].

I replace each element in smooth [] [] with the numerical average of the eight elements that surround it (plus the element itself) in the array. I did it.

However, notice the elements in the [] [] image that are at the edge of the array. These elements are located at row 0 and column 0. Any of these edge elements, I want to keep the same in smooth [] []. I am trying to do it with an if-statement, but it doesn't work. How to do it?

// compute the smoothed value of non-edge locations insmooth[][]
for (int r = 0; r < image.length - 1; r++) {// x-coordinate of element
    for (int c = 0; c < image[r].length - 1; c++) { // y-coordinate of
                                                    // element

        int sum1 = 0;// sum of each element 8 bordering elements and
                     // itself

        if (r == 0 && c == 0) {
            smooth[r][c] = image[r][c];
        }

        if (r >= 1 && c >= 1) {
            sum1 =    image[r - 1][c - 1] + image[r - 1][c]
                    + image[r - 1][c + 1] + image[r]    [c - 1]
                    + image[r]    [c]     + image[r]    [c + 1]
                    + image[r + 1][c - 1] + image[r + 1][c]
                    + image[r + 1][c + 1];
            smooth[r][c] = sum1 / 9; // average of considered elements
                                     // becomes new elements
        }
    }
}

      

+3


source to share


1 answer


As Phil said, your state should be checked for string == 0 OR col == 0



//compute the smoothed value of non-edge locations insmooth[][]
for(int r=0; r<image.length-1; r++){// x-coordinate of element
  for(int c=0; c<image[r].length-1; c++){ //y-coordinate of element

    int sum1 = 0; //sum of each element 8 bordering elements and itself

    if(r == 0 || c == 0) {
      smooth[r][c] = image[r][c];
    }
    else {
      sum1 = image[r-1][c-1] + image[r-1][c] + image[r-1][c+1] + image[r][c-1] + image[r][c] + image[r][c+1] +image[r+1][c-1] + image[r+1][c] + image[r+1][c+1];
      smooth[r][c]= sum1 / 9; //average of considered elements becomes new elements
    }
  }
}

      

+2


source







All Articles