2

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?

4 Answers 4

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The image is still tiny, only 5x5 in this case. I want to enlarge the image I am saving while retaining information
0

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
   ....:     

Comments

0

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) 

Comments

0

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.

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.