How would I scale a two-dimensional array in python?

I am not sure how to scale a two-dimensional array. Given the array below, whose dimensions are 8x10, let's say I needed to scale it to 5x6 - I was looking for specific examples on Wikipedia, but without significant grounding in matrix math, I got a little lost. If someone can point me in the right direction, I would 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] ] 
+4
source share
2 answers

Since your array looks like a binary image of the lowercase letter "a", I assume that you mean scaling in the sense of the image.

To do this, I would recommend using the imresize function in scipy.misc (which, in my opinion, is taken from PIL). Here is 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 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 is not ideal, but you can easily change 255 to 1. In addition, if you get the version for Scipy development, currently version 9, then you have some other options (scroll down to imresize - no anchor), which you can enter to increase such as interpolation method and PIL mode.

+8
source

If in doubt, use the library!

PIL has functions for resizing images, suggesting what type of scaling you are after. To convert a list of lists to a PIL image, first convert it to a numpy array, then to the PIL format . Once you're done, you can modify the process to get the list of lists again (if you really want to).

+2
source

Source: https://habr.com/ru/post/1332188/


All Articles