加载OpenCV图像到Scikit学习



我正在编写一个机器学习脚本来拍照并标记它。我有我的数据集在一个文件夹中,我将它们添加到数组中,并为标签创建另一个数组。当我尝试使用svm。它给出了错误:

File "scikit.py", line 43, in <module>
    clf.fit(arrayimg, arraylabel)
  File "/home/mkmeral/.local/lib/python2.7/site-packages/sklearn/svm/base.py", line 151, in fit
    X, y = check_X_y(X, y, dtype=np.float64, order='C', accept_sparse='csr')
  File "/home/mkmeral/.local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 521, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)
  File "/home/mkmeral/.local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 405, in check_array
    % (array.ndim, estimator_name))
ValueError: Found array with dim 3. Estimator expected <= 2.

下面是我写的脚本:

import cv2
import numpy as py
from sklearn import svm
camera_port = 0
camera = cv2.VideoCapture(camera_port)
ramp_frames = 5
def getImage():
    retval, im = camera.read()
    gray_image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    return gray_image
def insertToArray(arrayone, arraytwo, no, true):
    if (true==1):
        directory = "/home/mkmeral/Desktop/opencv/strue/"
        arraytwo.append(1)
    else:
        directory = "/home/mkmeral/Desktop/opencv/sfalse/"
        arraytwo.append(0)
    im = cv2.imread(directory + str(no) + ".png")
    gray_image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    arrayone.append(gray_image)
arrayimg = []
arraylabel = []
count = 1
while (count<43):
    insertToArray(arrayimg, arraylabel, count, 1)
    print("True = " , count)
    count = count + 1
count = 0
while (count<43):
    insertToArray(arrayimg, arraylabel, count, 0)
    print("False = ", count)
    count = count + 1
print("Done adding to arrays")
clf = svm.SVC()
print("Done adding to arrayssss")
clf.fit(arrayimg, arraylabel)
print("Done fitting")
for i in xrange(ramp_frames):
    temp = getImage()
testimage = getImage()
clf.predict(testimage)

我如何将这些图像适合Scikit学习,预测从网络摄像头拍摄的图像会有问题吗?

我不是图像处理方面的专家,但我猜您的getImage函数为每个图像返回一个2d数组。其中,sckit-learn将为每个训练实例期望一个1d数组。假设所有的图像都是相同的大小,那么下面的代码应该可以工作

def getImage():
    retval, im = camera.read()
    gray_image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    return gray_image.flatten()

这将把您的每个图像转换为1d数组。如果你的图片大小不一样,那么你需要做一些图像处理步骤,比如调整大小或缩小采样。

相关内容

  • 没有找到相关文章

最新更新