1

I am working with a thematic raster of land use classes. The goal is to split the raster into smaller tiles of a given size. For example, I have a raster of 1490 pixels and I want to split it into tiles of 250x250 pixels. To get tiles of equal size, I would want to increase the width of the raster to 1500 pixels to fit in exactly 6 tiles. To do so, I need to increase the size of the raster by 10 pixels.

I am currently opening the raster with the rasterio library, which returns a NumPy ndarray. Is there a function to add a buffer around this array? The goal would be something like this:

import numpy as np

a = np.array([
    [1,4,5],
    [4,5,5],
    [1,2,2]
])

a_with_buffer = a.buffer(a, 1) # 2nd argument refers to the buffer size

Then a_with_buffer would look as following:

[0,0,0,0,0]
[0,1,4,5,0],
[0,4,5,5,0],
[0,1,2,2,0],
[0,0,0,0,0]

2 Answers 2

2

You can use np.pad:

>>> np.pad(a, 1)
array([[0, 0, 0, 0, 0],
       [0, 1, 4, 5, 0],
       [0, 4, 5, 5, 0],
       [0, 1, 2, 2, 0],
       [0, 0, 0, 0, 0]])
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, exactly what I was looking for!
Would it be possible to set the padding width and height at different values? I could not find it in the docs.
@Sytze Sure, it's possible to provide one 2-tuple per dimension, specifying left and right padding: [(l1, r1), (l2, r2)]. It's mentioned in the docs at parameter pad_width.
1

you can create np.zeros then insert a in the index what you want like below.

Try this:

>>> a = np.array([[1,4,5],[4,5,5],[1,2,2]])

>>> b = np.zeros((5,5))

>>> b[1:1+a.shape[0],1:1+a.shape[1]] = a

>>> b
array([[0., 0., 0., 0., 0.],
       [0., 1., 4., 5., 0.],
       [0., 4., 5., 5., 0.],
       [0., 1., 2., 2., 0.],
       [0., 0., 0., 0., 0.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.