Search code examples
pythonpython-3.xzero-padding

Zero-Padding an image without numpy


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!


Solution

  • 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]]