Image 如何在Python中从计算机上的目录加载图像

Image 如何在Python中从计算机上的目录加载图像,image,python-2.7,loading-image,Image,Python 2.7,Loading Image,您好,我是python新手,我想知道如何将图像从计算机上的目录加载到python变量中。 我在磁盘上的文件夹中有一组图像,我想在循环中显示这些图像。您可以使用PIL(Python图像库)加载图像。 然后,您可以制作一个脚本,从目录中读取图像并将其加载到python中,类似于下面的内容 #!/usr/bin/python from os import listdir from PIL import Image as PImage def loadImages(path): # retur

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

您可以使用PIL(Python图像库)加载图像。 然后,您可以制作一个脚本,从目录中读取图像并将其加载到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()

您可以使用glob和imageiopython包来实现同样的功能。下面是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)
导入全局
导入图像
对于glob.glob(\\*.png)中的图像\u路径:
im=imageio.imread(图像路径)
打印(im.shape)
打印(im.dtype)

如果您的谷歌硬盘中有图像,并且希望加载、调整和保存这些图像,那么下面的代码可以正常工作

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)

pip安装ThreadedFileLoader

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

来自ThreadedFileLoader.ThreadedFileLoader导入*
instance=ThreadedImageLoader(“路径\到\文件夹/*.jpg”)
instance.start_加载()
images=instance.loaded\u对象
打印(透镜(图像))
打印(图像[0]。形状)

非常感谢,完成了任务:)