【发布时间】:2018-05-05 15:22:03
【问题描述】:
我有一个数据集“数字”。该数据集包括 1797 个小图像(8x8 像素),每个图像都包含一个手写数字(0-9)。每个图像都被视为以像素为特征的数据样本。因此,要构建特征表,您必须将每个 8x8 图像转换为特征矩阵的行,其中 64 个特征列对应 64 个像素。如何为其构建特征矩阵和标签向量???
【问题讨论】:
标签: python matplotlib scikit-learn
我有一个数据集“数字”。该数据集包括 1797 个小图像(8x8 像素),每个图像都包含一个手写数字(0-9)。每个图像都被视为以像素为特征的数据样本。因此,要构建特征表,您必须将每个 8x8 图像转换为特征矩阵的行,其中 64 个特征列对应 64 个像素。如何为其构建特征矩阵和标签向量???
【问题讨论】:
标签: python matplotlib scikit-learn
您可以按照关于监督学习的 scikit-learn 教程进行操作,他们使用的是 Digit 数据集
http://scikit-learn.org/stable/tutorial/basic/tutorial.html#loading-an-example-dataset
更多细节here。如果按照示例加载数据集,则可以简单地重塑图像:
from sklearn import datasets
digits = datasets.load_digits()
# To apply a classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
这使得data 成为一个二维矩阵,具有n_samples 行和尽可能多的列以适应展平图像。
【讨论】:
如果您使用的是numpy 和cv2,您可以执行以下操作:
import numpy as np
import cv2
fname = "image1.jpg"
image = cv2.imread(fname) # (8, 8, 1)
feature = image.reshape(64) # (64,)
要读取一堆图像并加载到“特征矩阵”(numpy 数组)中,您可以执行以下操作:
N = 10 # number of images
data = np.zeros((N, 64))
for index in range(N):
# get the current image and convert to feature, as above
data[index] = np.copy(feature)
您的数据矩阵的每一行现在都是一个示例(64 个暗淡的特征列表)。
这有帮助吗?
标签向量可以只是一个一维numpy数组,即labels = np.zeros(N)
编辑:
有多种读取图像的方法:
(1)img = cv2.imread(filename)
(2) 使用matplotlib:
import matplotlib.image as mpimg
img = mpimg.imread(filename)
(3) 使用 PIL(或 PILLOW):
from PIL import Image
img = Image.open(filename)
在读取图像后检查图像的形状是值得的,这样您就知道它处于适合您的应用程序的正确通道、宽度、高度顺序。
【讨论】: