numpy如何保存数据大小一致的矩阵

我现在有一批图像想转化成numpy数据保存起来,但是图片大小不固定(不希望resize)

比如说a.shape=(3,2,9),b.shape=(3,3,8),怎么将a,b合并成c呢?即如实现c[0]=a,c[1]=b?

所以想问一下就是有什么办法可以把这些尺寸不一致的图片用numpy.array的形式保存起来?

阅读 5.9k
1 个回答

用 pillow 模块把各式图片转换成像素集,然后转成 numpy 数组,最后保存到文件。

请参考下面的代码

# -*- coding: utf-8 -*-
from PIL import Image
import numpy as np


def images_to_array(image_files, array_file):
    """ 将多个图像文件保存成 numpy 数组,并存储到 .npy 文件。
    """
    data = []
    for filename in image_files:
        data.append(np.array(Image.open(filename)))
    np.save(array_file, data)


def load_images(array_file):
    """ 从 .npy 文件读取所有图像数组。
    """
    return np.load(array_file)


images_to_array(['1.png', '2.png'], '1.npy')
load_images('1.npy')

参考资料

  1. https://pillow.readthedocs.io...
  2. https://docs.scipy.org/doc/nu...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题