Reputation: 53
I'm currently writing a program for school that will allow me to load a .ppm file into main and then run a series of functions that will allow the user to manipulate the image file displayed (which is also done via another function) in various ways. One of the ways that I need to be able to manipulate this file is by doing a "flip" across the horizontal axis. Therefore I need my function to move the elements of each row to their "opposite" position. For example, if my array looked something like this [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] I need my function to turn it around [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].
Note: every 3 elements represent the RGB values of a single pixel, so I am unsure of how the middle 3 elements should behave, I would image that it needs to stay put though.
Here is my function so far:
def Switch(image_arry, cols, rows):
for y in range(rows):
for x in range(0, cols):
r1 = image_arry[y][x*3]
g1 = image_arry[y][x*3+1]
b1 = image_arry[y][x*3+2]
r2 = image_arry[y][x*3 -3]
g2 = image_arry[y][x*3 - 2]
b2 = image_arry[y][x*3 - 1]
image_arry[y][x*3] = image_arry[y][x*3 -3]
image_arry[y][x*3+1] = image_arry[y][x*3 - 2]
image_arry[y][x*3+2] = image_arry[y][x*3 - 1]
Note: Due to this being for a college course, I am unallowed to use anything in my program that we have not yet covered in this course (it's a 4 month, 100 level course so that scope is not very broad). And I am not allowed to use break, or while(1) statements either. Thank you very much for your help!
Upvotes: 2
Views: 1215
Reputation: 172259
Firstly, you should have each pixel as one entry in the array. That means you need to keep the RGB values in one object, instead of three, as in this case.
Since you can't use classes, I'd recommend having each pixel be a tuple or list. Hence a three pixel row with one black pixel, one gray and one green would look like this:
row = [(0,0,0,), (128, 128, 128), (0, 255, 0)]
You can now reverse that row like so:
row.reverse()
And the row will now be:
row = [(0,0,0,), (128, 128, 128), (0, 255, 0)]
The code to flip would be a simple:
for row in image:
row.reverse()
Upvotes: 2