'How to get opposite pixel in relation to center in 2d array?

I need to get all pairs of pixels that are opposite at the same distance from the fixed center of 2d array. Dimensions of this array will be always square and odd, ex: 5 by 5 with center in [2][2].

For example:

enter image description here

In a given array, center is [2][2]=12 Pixels with values 6,7,8,11,13,16,17,18 have 1 point of distance from center, it will be the first group. The opposites are always limited to the group. The opposites are: [1][1] and [3][3], [2][1] and [2][3], [3][1] and [1][3], [3][2] and [3][1]. The next group consists by pixels with values 0,1,2,3,4,9,14,19,24,23,22,21,20,15,10,5 that have 2 points of distance from center and will have the opposites in a same way as the first group.

The question is, how can I write an algorithm to get these pairs?

EDIT: Given the 2d array and pixel, I expect to get the opposite pixel with the same distance from center.



Solution 1:[1]

If you know length, l of your 2d square array which is odd then for a pixel at [x][y], the corresponding opposite pixel will be at [l-x-1][l-y-1].

e.g.

  • for [1][1], it will be [3][3]
  • for [0][3], it will be [4][1]
  • for [2][2], it will be [2][2] (center)

Adding bit of code to illustrate -

l = 5
matrix = [[l*i + j for j in range(l)] for i in range(l)]
print(matrix)

for i in range(l):
    for j in range(l):
        opposite = (l - i - 1, l - j - 1)
        print(f'{(i, j)}{matrix[i][j]} -- {opposite}{matrix[opposite[0]][opposite[1]]}')

outputs -

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]
(0, 0)0 -- (4, 4)24
(0, 1)1 -- (4, 3)23
(0, 2)2 -- (4, 2)22
(0, 3)3 -- (4, 1)21
(0, 4)4 -- (4, 0)20
(1, 0)5 -- (3, 4)19
(1, 1)6 -- (3, 3)18
(1, 2)7 -- (3, 2)17
(1, 3)8 -- (3, 1)16
(1, 4)9 -- (3, 0)15
(2, 0)10 -- (2, 4)14
(2, 1)11 -- (2, 3)13
(2, 2)12 -- (2, 2)12
(2, 3)13 -- (2, 1)11
(2, 4)14 -- (2, 0)10
(3, 0)15 -- (1, 4)9
(3, 1)16 -- (1, 3)8
(3, 2)17 -- (1, 2)7
(3, 3)18 -- (1, 1)6
(3, 4)19 -- (1, 0)5
(4, 0)20 -- (0, 4)4
(4, 1)21 -- (0, 3)3
(4, 2)22 -- (0, 2)2
(4, 3)23 -- (0, 1)1
(4, 4)24 -- (0, 0)0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1