【发布时间】:2020-05-06 01:47:46
【问题描述】:
您好,我是 python 新手,我想知道如何将计算机上的目录中的图像加载到 python 变量中。 我在磁盘上的一个文件夹中有一组图像,我想循环显示这些图像。
【问题讨论】:
标签: image python-2.7 loading-image
您好,我是 python 新手,我想知道如何将计算机上的目录中的图像加载到 python 变量中。 我在磁盘上的一个文件夹中有一组图像,我想循环显示这些图像。
【问题讨论】:
标签: image python-2.7 loading-image
您可以使用 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()
【讨论】:
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)
【讨论】:
您可以使用 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)
【讨论】:
如果您的 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)
【讨论】: