【问题标题】:Saving small numpy array as a large image将小 numpy 数组保存为大图像
【发布时间】:2018-01-27 16:47:08
【问题描述】:

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

例如。

[[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]]

我使用

将其保存到图像中
plt.imsave('file.png', X, cmap=cm.gray)

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

【问题讨论】:

    标签: python arrays image


    【解决方案1】:

    您可以使用PyPNG 库。这个库可以很简单,比如

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

    你也可以像下面这样使用scipy

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

    【讨论】:

    • 图像仍然很小,在这种情况下只有 5x5。我想在保留信息的同时放大保存的图像
    【解决方案2】:

    您可以使用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
       ....:     
    

    【讨论】:

      【解决方案3】:

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

      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) 
      

      【讨论】:

        【解决方案4】:

        这个问题可以通过简单的 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 是必需的数组,现在用你喜欢的任何方法保存它。

        【讨论】:

          猜你喜欢
          • 2010-10-28
          • 2020-05-25
          • 2011-10-18
          • 1970-01-01
          • 2020-07-07
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          相关资源
          最近更新 更多