【问题标题】:Using train_test_split with images from my local directory将 train_test_split 与我本地目录中的图像一起使用
【发布时间】:2016-01-24 13:52:01
【问题描述】:

我已从本地目录读取图像如下:

from PIL import Image
import os

root = '/Users/xyz/Desktop/data'

for path, subdirs, files in os.walk(root):
    for name in files:
        img_path = os.path.join(path,name)

我有两个子目录:category-1category-2,每个子目录都包含属于每个类别的图像文件 (.jpg)。

如何通过 Scikit-Learn 中的 train_test_split() 函数使用这些图像和两个类别?也就是说,安排训练和测试数据?

谢谢。

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    您必须从图像中读取像素数据并将其存储在 Pandas DataFrame 或 numpy 数组中。同时,您必须将对应的类别值category-1 (1)category-2 (2) 存储在列表或numpy 数组中。这是一个粗略的草图:我将假设您有一些商店 categories 根据图像名称返回 12

    X = numpy.array([])
    y = list()
    
    for path, subdirs, files in os.walk(root):
      for name in files:
        img_path = os.path.join(path,name)
        correct_cat = categories[img_path]
        img_pixels = list(Image.open(img_path).getdata())
        X = numpy.vstack((X, img_pixels))
        y.append(correct_cat)
    

    您正在有效地存储图像像素和类别值(转换为整数)。可能有其他方法可以做到这一点:例如Check this

    拥有Xy 列表后,您可以在它们上调用train_test_split

    X_train, X_test, y_train, y_test = train_test_split(X, y)
    

    【讨论】:

    • 不错。 X 可以是一个列表。使用 np.array(X) 有一个 numpy 数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多