【问题标题】:How to load images from a directory on the computer in Python如何在 Python 中从计算机上的目录加载图像
【发布时间】:2020-05-06 01:47:46
【问题描述】:

您好,我是 python 新手,我想知道如何将计算机上的目录中的图像加载到 python 变量中。 我在磁盘上的一个文件夹中有一组图像,我想循环显示这些图像。

【问题讨论】:

    标签: image python-2.7 loading-image


    【解决方案1】:

    您可以使用 PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ 来加载图像。 然后你可以编写一个脚本来从目录中读取图像并将它们加载到 python,就像这样。

    #!/usr/bin/python
    from os import listdir
    from PIL import Image as PImage
    
    def loadImages(path):
        # return array of images
    
        imagesList = listdir(path)
        loadedImages = []
        for image in imagesList:
            img = PImage.open(path + image)
            loadedImages.append(img)
    
        return loadedImages
    
    path = "/path/to/your/images/"
    
    # your images in an array
    imgs = loadImages(path)
    
    for img in imgs:
        # you can show every image
        img.show()
    

    【讨论】:

    • 非常感谢,完成了这项工作:)
    【解决方案2】:

    pip install ThreadedFileLoader
    您可以使用ThreadedFileLoader 模块。它使用线程来加载图像。

    from ThreadedFileLoader.ThreadedFileLoader import *
    
    instance = ThreadedImageLoader("path_to_folder/*.jpg")
    instance.start_loading()
    images = instance.loaded_objects
    print(len(images))
    print(images[0].shape)
    

    【讨论】:

      【解决方案3】:

      您可以使用 glob 和 imageio python 包来实现相同的目的。以下是python 3中的代码:

      import glob
      import imageio
      
      for image_path in glob.glob("<your image directory path>\\*.png"):
          im = imageio.imread(image_path)
          print (im.shape)
          print (im.dtype)
      

      【讨论】:

        【解决方案4】:

        如果您的 google 驱动器中有图片,并且想要加载、调整大小和保存图片,那么下面的代码可以正常工作。

        import os, sys
        from os import listdir
        
        from PIL import Image
        from google.colab import drive
        import matplotlib.pyplot as plt
        drive.mount('/content/gdrive')
        
        # need to enter password to access your google drive
        
        from google.colab import files
        main_dir = "/content/gdrive/My Drive/Panda/"
        files = listdir(main_dir)
        # you can change file extension below to read other image types
        images_list = [i for i in files if i.endswith('.jpg')] ## output file names only
        
        for idx,image in enumerate(images_list):
          print(idx)
          img = Image.open(main_dir + image)
          #print(img.size)
          #plt.imshow(img)
          img = img.resize((480, 600))
          img.save(main_dir + image)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-13
          • 1970-01-01
          相关资源
          最近更新 更多