Reputation: 83
I wrote some code to try and answer this problem.
I've been given a program to draw an image, grey scaled using X11.
I've been asked to write a function to flip the image horizontally/vertically.
Here is my code snippet
// flip the image, left-to-right, like in a mirror.
void flip_horizontal( uint8_t array[],
unsigned int cols,
unsigned int rows )
{
int i;
int j;
for (i=0; i<rows;i++)
{
for (j=0; j<cols;j++)
{
array[rows*i+j]=array[rows*i+(cols-1-j)];
}
}
}
// flip the image top-to-bottom.
void flip_vertical( uint8_t array[],
unsigned int cols,
unsigned int rows )
{
int i=0;
int j=0;
for (i=0; i<rows;i++)
{
for (j=0; j<cols;j++)
{
array[rows*i+j]=array[rows*(rows-1-i)+j];
}
}
return;
}
The problem I'm having is is that my horizontal function flips the image only half way, the other half retains its original values.
My vertical flip function is a mess as well and the image produced isn't at all looking like what it should so I'm trying to debug where I've made a mistake in the logic for writing the functions.
I'm using the flat index method for accessing 2D array values.
Upvotes: 0
Views: 1908
Reputation: 84
In your horizontal flip, the inner loop goes through all the columns and assigns the pixel its mirrored value. Let's say your leftmost pixel is 100 and the rightmost one is 23. After one step, leftmost becomes 23. Now when it comes to the rightmost one, it tries to look at the leftmost one and, viola, you get 23 again. The value 100 is already lost. That's why your right half of the image won't change.
Same problem for vertical flip.
Also you have indexing problems. I assume cols means number of columns and rows means number of rows. Assuming the image is stored row-major, meaning the layout in the flat array is row after row, like our reading order, then the pixel at row i and column j is at index cols*i+j, instead of rows*i+j. Unintuitively, cols is the number of columns , and at the same time the size of a row. Happy debugging :)
Upvotes: 2
Reputation: 4468
static uint8_t temp;
void flip_horizontal( uint8_t array[],
unsigned int cols,
unsigned int rows )
{
int i;
int j;
for (i=0; i<rows/2;i++)
{
for (j=0; j<cols;j++)
{
temp=array[rows*i+j];
array[rows*i+j]=array[rows*i+(cols-1-j)];
array[rows*i+(cols-1-j)]=temp;
}
}
}
// flip the image top-to-bottom.
void flip_vertical( uint8_t array[],
unsigned int cols,
unsigned int rows )
{
int i=0;
int j=0;
for (i=0; i<rows;i++)
{
for (j=0; j<cols/2;j++)
{
temp=array[rows*i+j];
array[rows*i+j]=array[rows*(rows-1-i)+j];
array[rows*(rows-1-i)+j]=temp;
}
}
return;
}
This code could stand a lot of efficiency improvement, but basically what I have done is halved the number of times you do swap operations, and I've introduced a temporary variable to hold data during the swap operation.
Upvotes: -1