【问题标题】:Create numpy array from images in different folders从不同文件夹中的图像创建 numpy 数组
【发布时间】:2019-03-26 22:01:13
【问题描述】:

我是 Python、scikit-learn 和 numpy 的初学者。我有一组包含图像的文件夹,我想为其应用不同的机器学习算法。然而,我正在努力将这些图像转换为我可以使用的 numpy 数据。

这些是我的先决条件:

  • 每个文件夹名称都保存着图像的关键。例如 /birds/abc123.jpg 和 /birds/def456.jpg 都是“鸟”
  • 每张图片为 100x100px jpg
  • 我使用的是 Python 2.7
  • 共有 2800 张图片

据我所知,这是我的代码:

# Standard scientific Python imports
import matplotlib.pyplot as plt

# Import datasets, classifiers and performance metrics
from sklearn import svm, metrics

import numpy as np

import os # Working with files and folders

from PIL import Image # Image processing

rootdir = os.getcwd()
key_array = []
pixel_arr = np.empty((0,10000), int)

for subdir, dirs, files in os.walk('data'):
  dir_name = subdir.split("/")[-1]
  if "x" in dir_name:
    key_array.append(dir_name)
    for file in files:
      if ".DS_Store" not in file:
        file = os.path.join(subdir, file)
        im = Image.open(file)
        im_bw = im.convert('1') #Black and white
        new_np = np.array(im_bw2).reshape(1,-1)
        print new_np.shape
        pixel_arr = np.append(pixel_arr, new_np, axis=0)

在此代码中起作用的是浏览文件夹、获取文件夹名称并获取正确的文件/图像。我无法开始工作的是创建一个 2800,10000 的 numpy 数组(或者正确的可能是 10000,2800),即 2800 行,每行有 10000 个值。

这个解决方案(我不确定它是否有效)虽然超级慢,但我很确定一定有一个比这个更快、更优雅的解决方案!

如何创建这个 2800x10000 的 numpy 数组,最好附上 key_array 的索引号?

【问题讨论】:

  • 这与 scikit-learn 无关。为了所有神圣的爱,升级到 python 3。
  • 谢谢。我认为这是我无知的一部分——我不确定 scikit-learns 从哪里开始和结束。我会考虑升级 - 老实说,我不确定为什么我最终会使用 2.7。
  • 这些输入图像是 RGB 吗?
  • 是的。输入图像是 RGB。我(尝试)使用 im.convert('1') 将它们转换为 BW。

标签: python numpy python-imaging-library


【解决方案1】:

如果您不需要同时使用所有图像,可以使用生成器。

def get_images():
  for subdir, dirs, files in os.walk('data'):
    dir_name = subdir.split("/")[-1]
    if "x" in dir_name:
      key_array.append(dir_name)
      for file in files:
        if ".DS_Store" not in file:
          file = os.path.join(subdir, file)
          im = Image.open(file)
          im_bw = im.convert('1') #Black and white

          yield np.array(im_bw2).reshape(1,-1)

这样您就不会同时将所有图像保存在内存中,这可能会对您有所帮助。

使用你会做的图像:

for image in get_images():
  ...

【讨论】:

  • 谢谢!这不是我想要的,而是解决我问题的方法。
猜你喜欢
  • 2017-12-28
  • 2016-03-23
  • 2020-09-10
  • 1970-01-01
  • 2012-10-26
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多