python - 如何在Python中正确加载一组图像

标签 python

我正在尝试在 python 中打开一组图像,但我有点困惑我应该如何做到这一点。我知道如何处理一张图像,但不知道如何处理数百张图像。

我有一个文件夹,里面有几百张 .jpg 图像。我想将它们加载到 python 程序中以对它们进行机器学习。我怎样才能正确地做到这一点?

我还没有任何代码,因为我已经在为此苦苦挣扎。

但是我的伪代码想法是

dataset = load(images)
do some manipulations on it

我以前是如何做到的:

from sklearn.svm import LinearSVC
from numpy import genfromtxt,savetxt

load = lambda x: genfromtxt(open(x,"r"),delimiter = ",",dtype = "f8")[1:]
dataset = load("train.csv")
train = [x[1:] for x in dataset]
target = [x[0] for x in dataset]
test = load("test.csv")

linear = LinearSVC()
linear.fit(train,target)

savetxt("digit2.csv",linear.predict(test),delimiter = ",", fmt = "%d")

由于格式的原因,效果很好。所有数据都在一个文件中。

最佳答案

如果您想单独处理每个图像(假设您使用的是 PIL 或 Pillow),请按顺序执行此操作:

import os
from glob import glob

try:
    # PIL
    import Image
except ImportError:
    # Pillow
    from PIL import Image

def process_image(img_path):
    print "Processing image: %s" % img_path
    # Open the image
    img = Image.open(img_path)

    # Do your processing here
    print img.info

    # Not strictly necessary, but let's be explicit:
    # Close the image
    del img

images_dir = "/home/user/images"

if __name__ == "__main__":
    # List all JPEG files in your directory
    images_list = glob(os.path.join(images_dir, "*.jpg"))

    for img_filename in images_list:
        img_path = os.path.join(images_dir, img_filename)
        process_image(img_path)

关于python - 如何在Python中正确加载一组图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346731/

相关文章:

python - sys.stdout.write 对于 Windows 上的二进制文件无法正常工作

python - Tensorflow 对象检测 API : Multiple Objects coordinates

Python 将瀑布图转换为 plotly

python - 在 Ubuntu 中找不到(但已安装)模块

python - 有没有工具可以将用 C 编写的数学公式转换为 Python?

python - 如何将文件列表传递给 python open() 方法

python - Selenium(参数 --headless)+(木偶 = False)

python - 将像对象这样的文件保存到 s3 我收到错误 : Unicode-objects must be encoded before hashing

python - 如何在 Python 3 urllib.request.urlopen() 函数中传递带空格的 URL?

Python:threading.timer 不遵守间隔