Zito Relova
Zito Relova

Reputation: 1041

Saving small numpy array as a large image

I have a small binary numpy array X

eg.

[[0,0,0,0,0],
 [0,0,1,0,0],
 [0,1,0,1,0],
 [0,0,1,0,0],
 [0,0,0,0,0]]

I save it to an image using

plt.imsave('file.png', X, cmap=cm.gray)

the only problem is that the image is tiny at 5x5 resolution. How could I increase the resolution of the image while still keeping the information in the image?

Upvotes: 2

Views: 364

Answers (4)

skt7
skt7

Reputation: 1235

This problem can be solved using a simply numpy hack. Resize the array and fill it with zeros.

  1. Consider X as your present numpy array

    X = np.array([[0,0,0,0,0],
                  [0,0,1,0,0],
                  [0,1,0,1,0],
                  [0,0,1,0,0],
                  [0,0,0,0,0]])
    
  2. Making a new array of zeros with the required dimensions

    new_X = np.zeros((new_height,new_width))
    
  3. Add your original array to it

    new_X[:X.shape[0], :X.shape[1]] = X
    
  4. new_X is required array, now save it using any method you like.

Upvotes: 0

Bennett Brown
Bennett Brown

Reputation: 5383

An image that has more pixels will hold more information, but the pixels could be redundant. You could make a larger image in which each rectangle is black or white:

your_data = [[0,0,0,0,0],
    [0,0,1,0,0],
    [0,1,0,1,0],
    [0,0,1,0,0],
    [0,0,0,0,0]]
def enlarge(old_image, horizontal_resize_factor, vertical_resize_factor):
    new_image = []
    for old_row in old_image:
        new_row = []
        for column in old_row:
            new_row += column*horizontal_resize_factor
        new_image += [new_row]*vertical_resize_factor
    return new_image
# Make a 7x7 rectangle of pixels for each of your 0 and 1s
new_image = enlarge(your_data, 7, 7) 

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

You can use Numpy to maximize the dimension of your array and increase the number of ones around each index respectively:

In [48]: w, h = a.shape

In [49]: new_w, new_h = w * 5, h * 5

In [50]: new = np.zeros((new_w, new_h))

In [51]: def cal_bounding_square(x, y, new_x, new_y):
             x = x * 5 
             y = y * 5
             return np.s_[max(0, x-5):min(new_x, x+5),max(0, y-5):min(new_y, y+5)]
   ....: 

In [52]: one_indices = np.where(a)

In [53]: for i, j in zip(*one_indices):
             slc = cal_bounding_square(i, j, new_w, new_h)
             new[slc] = 1
   ....:     

Upvotes: 0

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You can use PyPNG Library. It can be very simple with this library like

import png
png.from_array(X, 'L').save("file.png")

You can also use scipy like following

import scipy.misc
scipy.misc.imsave('file.png', X)

Upvotes: 1

Related Questions