将小numpy数组保存为大图像

时间:2018-01-27 16:47:09

标签: python arrays image

我有一个小的二进制numpy数组X

例如。

 1  22 serialization::archive 15 0 0 0 0 0 0

我使用

将其保存为图像
[[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]]

唯一的问题是图像在5x5分辨率下很小。如何在保持图像信息的同时提高图像的分辨率?

4 个答案:

答案 0 :(得分:1)

您可以使用PyPNG库。这个库可以非常简单,如

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

您也可以使用scipy,如下所示

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

答案 1 :(得分:0)

您可以使用Numpy来最大化数组的维度,并分别增加每个索引周围的数量:

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

答案 2 :(得分:0)

使用简单的numpy hack可以解决这个问题。调整数组大小并用零填充。

  1. 将X视为您现在的numpy数组

    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. 制作一个具有所需尺寸的新零数组

    new_X = np.zeros((new_height,new_width))
    
  3. 将原始数组添加到其中

    new_X[:X.shape[0], :X.shape[1]] = X
    
  4. new_X是必需的数组,现在使用您喜欢的任何方法保存它。

答案 3 :(得分:0)

具有更多像素的图像将保存更多信息,但像素可能是多余的。你可以制作一个更大的图像,其中每个矩形是黑色或白色:

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)