0

I am a beginner with Python and I am learning how to treat images.

Given a square image (NxN), I would like to make it into a (N+2)x(N+2) image with a new layer of zeros around it. I would prefer not to use numpy and only stick with the basic python programming. Any idea on how to do so ?

Right now, I used .extend to add zeros on the right side and on the bottom but can't do it up and left.

Thank you for your help!

AyeAye
  • 63
  • 1
  • 8

2 Answers2

2

We can create a padding function that adds layers of zeros around an image (padding it).

def pad(img,layers):
    #img should be rectangular
    return [[0]*(len(img[0])+2*layers)]*layers    + \
           [[0]*layers+r+[0]*layers for r in img] + \
           [[0]*(len(img[0])+2*layers)]*layers

We can test with a sample image, such as:

i = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

So,

pad(i,2)

gives:

[[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 2, 3, 0, 0],
 [0, 0, 4, 5, 6, 0, 0],
 [0, 0, 7, 8, 9, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • (NxN) should become (N+2 x N+2), not (N+4 x N+4) as in your case – lenik Jul 20 '19 at 11:26
  • @lenik I didn't follow the OPs request for a shape argument directly; instead I have an "additional layers" argument. I feel this is more useable since padding on all sides is desired - i.e. if we had a shape argument and the amount of padding the new shape implied was an odd amount of layers how would we know whether to add to the top left bottom or right? – Joe Iddon Jul 20 '19 at 11:36
1

Im assuming that by image we're talking about a matrix, in that case you could do this:

img = [[5, 5, 5], [5, 5, 5], [5, 5, 5]]
row_len = len(img)
col_len = len(img[0])

new_image = list()
for n in range(col_len+2):  # Adding two more rows
    if n == 0 or n == col_len + 1:
        new_image.append([0] * (row_len + 2))  # First and last row is just zeroes
    else:
        new_image.append([0] + img[n - 1] + [0])  # Append a zero to the front and back of each row

print(new_image)  # [[0, 0, 0, 0, 0], [0, 5, 5, 5, 0], [0, 5, 5, 5, 0], [0, 5, 5, 5, 0], [0, 0, 0, 0, 0]]
Marcus Grass
  • 1,043
  • 2
  • 17
  • 38