3

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

4

4 回答 4

10

You can use PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ to load images. Then you can make an script to read images from a directory and load them to python, something like this.

#!/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()
于 2016-04-21T17:54:10.307 回答
1

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)
于 2020-05-05T17:47:46.320 回答
0

您可以使用 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)
于 2017-12-15T08:29:31.790 回答
0

如果您的 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)
于 2020-03-30T17:12:08.830 回答