nycynik
nycynik

Reputation: 7541

numpy multiply the shape of an array to make a larger array

I assume this is very easy, but I'm not seeing it.

I have a numpy array that is (800, 600) and I want to make a new array that is 3x the original size in both directions. When I multiply the shape I get a strange result. I know I can do this with the array notation, but is there a way to do it without that?

>>> img.shape
(800, 600)
>>> img.shape * 3
(800, 600, 800, 600, 800, 600)
>>> (img.shape[0] * 3, img.shape[1] * 3)
(2400, 1800)
>>> 

I have an original image X, and want to surround it with whitespace the size of the image in all directions. So:

x

www
wxw
www

I was thinking of using np.ones((new 3x size)) and then copying the image in with the offset width*height of the original image.

Upvotes: 0

Views: 610

Answers (1)

Ron U
Ron U

Reputation: 518

If you want to broadcast the multiplication you can the the python's tuple "shape" into a numpy array and then perform the calculation, i.e.:

expanded_shape = np.array(img.shape)*3

For the padding itself by the way you wanted to do it, you can do something like this:

expanded_img = np.ones(expanded_shape)
expanded_img[img.shape[0]:img.shape[0]*2, img.shape[1]:img.shape[1]*2] = img

However you can use np.pad function as well. It is well documented (look at the last example there, I think it is exactly what you need).

Upvotes: 1

Related Questions