Stella Lie
Stella Lie

Reputation: 124

How to crop an image based on 2d array

Let say I have an image based on coordinate of 2d array such below:

{
        { ' ', ' ', ' ', ' ' }, 
        { ' ', ' ', 'x', ' ' }, 
        { ' ', 'x', ' ', ' ' }, 
        { ' ', 'x', 'x', ' ' }
};

Would like to crop it into a smaller array like this:

{
        { ' ', 'x' }, 
        { 'x', ' ' }, 
        { 'x', 'x' }
};

Any takers?

Upvotes: 1

Views: 975

Answers (1)

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

Iterate array once.

While iterating, find the most left column (column, in which x first time appeared) and the most right (column, in which x last time appeared). The same for 2 rows: one on the top, one on the bottom. These 4 lines gives bounds for your image.

              left right
        { ' ', ' ', ' ', ' ' }, 
 top    { ' ', ' ', 'x', ' ' }, 
        { ' ', 'x', ' ', ' ' }, 
 bottom { ' ', 'x', 'x', ' ' }

Pseudocode:

int left = INT_MAX, right = -1, top = INT_MAX, bottom = -1
for (int y = 0; y < Y; y++)
  for (int x = 0; x < X; x++)
    if (t[x][y] == 'x')
    {
      if (left > x) left = x
      if (right < x) right = x
      if (top > y) top = y
      bottom = y // we don't need if! :)
    }

Given your input example, it will produce such indices:

left   == 1
right  == 2
top    == 1
bottom == 3

Taking submatrix with that bounds included will give your exemplary output image.

Upvotes: 1

Related Questions