beginner beginner - 1 month ago 6
C Question

Replace a section of an image using arrays in C

For an assignment, I've been given a rather large chunk of code that reads in a file name of a PGM image and then after running it through a function that has some for loops, it writes a new file. PGM are grayscale images that store a number 0~255 in a 2D array. I am supposed to adjust the for loops and the arrays within the function so that the new file is adjusted in some way. Here are some that I have written so far.

enter image description here

int i,j;

for (i=0;i<numRows/2;i++)
{ for (j=numCols/2;j<numCols;j++)
{
imgtemp[i+numRows/2-1][j+numCols/2-1] = imgtemp[i][j];
}
}


and

int i,j;

for (i=0;i<numRows;i++)
{ for (j=0;j<i;j++)
{
imgtemp[i][j] = 0;
}
}


I'm having some trouble figuring out how to flip selections both horizontally and vertically.

I thought it would be like this:

int i,j;

for (i=0;i<numRows;i++)
{ for (j=0;j<i;j++)
{
imgtemp[numCols-1-i][numRows-1-j] = imgtemp[i][j];
}
}


but it ends up flipping the wrong portion of the image. I'm not sure how to fix it.

Answer

You want to copy values from diagonal point (img[i][(int)(numCols*i/(float)numRows))]) to the right. So your j index should start at i*numCols/numRows-th position. (If image is square then just simply j = i in the second for)

int i,j;

for (i=0;i<numRows;i++)
{
    for (j=(int)((numCols*i/(float)numRows)); j<numCols; j++)
    {
        imgtemp[numRows-1-i][numCols-1-j] = imgtemp[i][j];
    }
}
Comments