SVM图像预测Python

时间:2019-02-27 17:34:42

标签: python image-processing scikit-learn svm

我从火车数据集中的图像中提取了一些特征,然后应用了这些特征并将数据拆分为火车,并使用train_test_split进行了测试:

Train data  : (60, 772)
Test data   : (20, 772)
Train labels: (60,)
Test labels : (20,)

我下一步要做的是将SVM分类器应用于测试数据集中的图像并查看结果。

# create the model - SVM
#clf = svm.SVC(kernel='linear', C=40)
clf = svm.SVC(kernel='rbf', C=10000.0, gamma=0.0001)

# fit the training data to the model
clf.fit(trainDataGlobal, trainLabelsGlobal)

# path to test data
test_path = "dataset/test"

# loop through the test images
for index,file in enumerate(glob.glob(test_path + "/*.jpg")):
    # read the image
    image = cv2.imread(file)

    # resize the image
    image = cv2.resize(image, fixed_size)

    # predict label of test image
    prediction = clf.predict(testDataGlobal)
    prediction = prediction[index]
    #print("Accuracy: {}%".format(clf.score(testDataGlobal, testLabelsGlobal) * 100 ))

    # show predicted label on image
    cv2.putText(image, train_labels[prediction], (20,30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0,255,255), 2)

    # display the output image
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    plt.show()

即使我看到它说60%的准确性,我的准确性也没有很高。但是,大多数图像都未正确标记。我在prediction中传递了错误的论点吗?

我该怎么做才能改善这一点?

编辑:我已经尝试使用以下代码对您所说的内容进行操作,但是出现错误,提示我应该重塑feature_vector。所以我这样做了,然后出现以下错误。

(作为参考:feature_extraction_method(image).shape(772,)。)

for filename in test_images:

    # read the image and resize it to a fixed-size
    img = cv2.imread(filename)
    img = cv2.resize(img, fixed_size)

    feature_vector = feature_extraction_method(img)
    prediction = clf.predict(feature_vector.reshape(-1, 1))
    cv2.putText(img, prediction, (20, 30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0, 255, 255), 2)
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.show()   

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-2b8ff4146d8e> in <module>()
     19 
     20     feature_vector = feature_extraction_method(img)
---> 21     prediction = clf.predict(feature_vector.reshape(-1, 1))
     22     cv2.putText(img, prediction, (20, 30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0, 255, 255), 2)
     23     plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in predict(self, X)
    546             Class labels for samples in X.
    547         """
--> 548         y = super(BaseSVC, self).predict(X)
    549         return self.classes_.take(np.asarray(y, dtype=np.intp))
    550 

/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in predict(self, X)
    306         y_pred : array, shape (n_samples,)
    307         """
--> 308         X = self._validate_for_predict(X)
    309         predict = self._sparse_predict if self._sparse else self._dense_predict
    310         return predict(X)

/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in _validate_for_predict(self, X)
    457             raise ValueError("X.shape[1] = %d should be equal to %d, "
    458                              "the number of features at training time" %
--> 459                              (n_features, self.shape_fit_[1]))
    460         return X
    461 

ValueError: X.shape[1] = 1 should be equal to 772, the number of features at training time 

1 个答案:

答案 0 :(得分:1)

您的代码有两个主要问题。

首先,您不需要在for循环的每个交互中对整个测试集进行分类。一次预测一张图像的类别标签就足够了:

    prediction = svm.clf.predict([testDataGlobal[index, :]])

请注意,testDataGlobal[index, :]方法必须使用类似二维数组的变量,因此[ ]必须括在方括号predict()中。

第二个也是最重要的一点是,让我们假设函数glob产生了三个图像文件的列表,分别是imgA.jpgimgB.jpgimgC.jpg并让我们表示它们对应的特征向量为featsAfeatsBfeatsC。为了使您的代码正常工作,至关重要的是testDataGlobal的安排如下:

[featsA, 
 featsB, 
 featsC]

如果特征向量的排列顺序不同,则可能会得到错误的结果。

您可以通过以下代码段正确标记图像(未经测试):

test_images = glob.glob("dataset/test/*.jpg")

for filename in test_images:
    img = cv2.imread(filename)
    img = cv2.resize(img, fixed_size)
    feature_vector = your_feature_extraction_method(img)
    prediction = svm.clf.predict([feature_vector])
    cv2.putText(img, prediction[0], (20, 30), 
                cv2.FONT_HERSHEY_TRIPLEX, .7 , (0, 255, 255), 2)
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.show()    

其中your_feature_extraction_method()代表消耗图像并返回其特征向量(类似于一维数组)的函数。

注意:请不要忘记将feature_vector括在方括号[ ]中。您还可以使用以下任何一种方法来将feature_vector的维度增加一个维度:

    prediction = svm.clf.predict(feature_vector[None, :])
    prediction = svm.clf.predict(feature_vector[np.newaxis, :])
    prediction = svm.clf.predict(np.atleast_2d(feature_vector))