【问题标题】:Array of images in pythonpython中的图像数组
【发布时间】:2015-01-08 13:43:09
【问题描述】:

我正在使用 numpy 和 matplotlib 在 python 中导入图像。我想创建一个 3d 数组,这样在第 1 和第 2 轴我有像素值,在第 0 轴我有图像编号。到目前为止,我得到了这样的东西:

from PIL import Image                                                            
import numpy                                                                     
import matplotlib.pyplot as plt                                                  
import glob

imageFolderPath = '/home/B/Pictures/'
imagePath = glob.glob(imageFolderPath+'/*.JPG') 

im_array = numpy.array(Image.open(imagePath[0]).convert('L'), 'f')               
im_array = numpy.expand_dims(im_array, axis=0)                                   

for c in range(1, len(imagePath)):                                               
     im_array_new = numpy.array(Image.open(imagePath[c]).convert('L'), 'f')       
     im_array_new = numpy.expand_dims(im_array_new, axis=0)                       
     im_array = numpy.append(im_array, im_array_new, axis=0)  

这项工作,但它有点难看。我不喜欢我必须扩展二维数组的维度然后将它们附加在一起的事实。 在python中有没有更优雅的方法来做到这一点?可能无需预先分配一个巨大的 3d 数组(n 张照片,x 维,y 维)

【问题讨论】:

    标签: python arrays python-3.x numpy matplotlib


    【解决方案1】:

    您可以从列表推导中创建一个数组,而不是 for 循环:

    from PIL import Image                                                            
    import numpy                                                                     
    import glob
    
    imageFolderPath = '/home/B/Pictures/'
    imagePath = glob.glob(imageFolderPath + '/*.JPG') 
    
    im_array = numpy.array( [numpy.array(Image.open(img).convert('L'), 'f') for img in imagePath] )
    

    【讨论】:

    • 这比我的要优雅得多。谢谢
    猜你喜欢
    • 2012-11-16
    • 2016-11-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    相关资源
    最近更新 更多