4

I'm not sure how to go about scaling a 2-dimensional array. Given the array below, whose dimensions are 8x10, say I needed to scale it to 5x6 -- I've looked for concrete examples on wikipedia, but without much grounding in matrix math I'm a bit lost. If someone could point me in the right direction I'd really appreciate it!

[
 [0, 0, 1, 1, 1, 1, 0, 0],
 [0, 1, 1, 1, 1, 1, 1, 0],
 [0, 1, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 0, 1, 1],
 [0, 0, 1, 1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1, 1],
 [1, 1, 0, 0, 0, 0, 1, 1],
 [1, 1, 0, 0, 0, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1, 1],
 [0, 1, 1, 1, 1, 0, 1, 1]
]
coleifer
  • 24,887
  • 6
  • 60
  • 75
  • 2
    When you say scale, what exactly do you mean? Treat it as a picture? – configurator Dec 15 '10 at 06:39
  • Scaling has a specific meaning with regards to matrices (namely, it's a particular affine transformation), which does *not* change the size of the matrix. Thus I guess you're referring to something else here, but it's not clear what that is. – Adrian Petrescu Dec 15 '10 at 06:46
  • Yah, treat it like a picture. I think this is where my problems finding a solution have stemmed because matrix transformation seems to be a bit different. I'd like to "preserve" in some sense the data contained within while scaling down or up arbitrarily – coleifer Dec 15 '10 at 13:53

2 Answers2

10

Since your array looks like it is a binary image of a lower case 'a' letter, I'm guessing that you mean scaling in the image sense.

To do that, I would recommend using the imresize function in scipy.misc (which is taken from PIL, I believe). Here's an example:

import numpy as np
from scipy.misc import imresize

img = np.array([
 [0, 0, 1, 1, 1, 1, 0, 0],
 [0, 1, 1, 1, 1, 1, 1, 0],
 [0, 1, 0, 0, 0, 1, 1, 1],
 [0, 0, 0, 0, 0, 0, 1, 1],
 [0, 0, 1, 1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1, 1],
 [1, 1, 0, 0, 0, 0, 1, 1],
 [1, 1, 0, 0, 0, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1, 1],
 [0, 1, 1, 1, 1, 0, 1, 1]
])
newimg = imresize(img, (6,5))

and newimg is then

array([[  0,   0, 255, 255,   0],
       [  0, 255, 255, 255, 255],
       [  0,   0,   0,   0, 255],
       [255, 255, 255, 255, 255],
       [255, 255,   0,   0, 255],
       [255, 255, 255, 255, 255]], dtype=uint8)

which isn't perfect, but you can change the 255's to 1's easily enough. Also, if you get the development version of Scipy, currently version 9, then you have some other parameters(scroll down to imresize - no anchor) that you can input to imresize such as the interpolation method and PIL mode.

Justin Peel
  • 46,722
  • 6
  • 58
  • 80
2

When in doubt, use a library!

PIL has functions for resizing images, assuming that's the kind of scaling you're after. To convert your list of lists to a PIL image, first convert it to a numpy array, then to PIL format. After you're done, you can reverse the process to get a list of lists again (if you really want).

Community
  • 1
  • 1
perimosocordiae
  • 17,287
  • 14
  • 60
  • 76