【问题标题】:How to get to work reshape() function over 2D vectors如何在 2D 向量上使用 reshape() 函数
【发布时间】:2019-12-09 11:55:11
【问题描述】:

我已经重新塑造了一个特征向量,但仍然出现此错误:

ValueError: Expected 2D array, got 1D array instead: array=[].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我在预测之前使用了reshape

features = features.reshape(1, -1)

但一点运气都没有。

这是我的代码

import cv2
import numpy as np
import os
import glob
import mahotas as mt
from sklearn.svm import LinearSVC

# function to extract haralick textures from an image
def extract_features(image):
    # calculate haralick texture features for 4 types of adjacency
    textures = mt.features.haralick(image)

    # take the mean of it and return it
    ht_mean = textures.mean(axis = 0).reshape(1, -1)
    return ht_mean

# load the training dataset
train_path  = "C:/dataset/train"
train_names = os.listdir(train_path)

# empty list to hold feature vectors and train labels
train_features = []
train_labels   = []

# loop over the training dataset
print ("[STATUS] Started extracting haralick textures..")
for train_name in train_names:
    cur_path = train_path + "/" + train_name
    cur_label = train_name
    i = 1

    for file in glob.glob(cur_path + "/*.jpg"):
        print ("Processing Image - {} in {}".format(i, cur_label))
        # read the training image
        image = cv2.imread(file)

        # convert the image to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # extract haralick texture from the image
        features = extract_features(gray)

        # append the feature vector and label
        train_features.append(features.reshape(1, -1))[0]
        train_labels.append(cur_label)

        # show loop update
        i += 1

# have a look at the size of our feature vector and labels
print ("Training features: {}".format(np.array(train_features).shape))
print ("Training labels: {}".format(np.array(train_labels).shape))

# create the classifier
print ("[STATUS] Creating the classifier..")
clf_svm = LinearSVC(random_state = 9)

# fit the training data and labels
print ("[STATUS] Fitting data/label to model..")
clf_svm.fit(train_features, train_labels)

# loop over the test images
test_path = "C:/dataset/test"
for file in glob.glob(test_path + "/*.jpg"): 
    # read the input image
    image = cv2.imread(file)

    # convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # extract haralick texture from the image
    features = extract_features(gray)

    # evaluate the model and predict label
    prediction = clf_svm.predict(features)

    # show the label
    cv2.putText(image, prediction, (20,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,255), 3)
    print ("Prediction - {}".format(prediction))

    # display the output image
    cv2.imshow("Test_Image", image)
    cv2.waitKey(0)

我不知道是我错误地使用了 reshape() 还是遗漏了一些东西。

ValueError:预期的 2D 数组,得到 1D 数组:array=[]。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)。

【问题讨论】:

    标签: python python-3.x opencv machine-learning numpy-ndarray


    【解决方案1】:

    考虑以下几点:

    • 由于train_featuresclf_svm.fit(train_features, train_labels) 行中的[ ](空列表),因此出现上述错误。它应该至少包含1 数据。这是因为train_path 指向仅包含图像文件的文件夹,但上面的代码假设train_path 指向至少具有1 子文件夹(无文件)的文件夹。

      train 
         - class1_folder[class11.jpg, class12.jpg, ...]
         - class2_folder[class21.jpg, class22.jpg, ...]
         - and so on ...
      

      在这里,您的训练数据的类名将是[class1, class2, ...]

    • train_features.append(features.reshape(1, -1))[0]改成train_features.append(features.reshape(1, -1)[0])

    • clf_svm.predict(features) 的输出是一个 numpy 数组。因此,在cv2.putText 函数中将prediction 替换为str(prediction)。您也可以将其替换为 prediction[0]

    试试下面的代码:

    import cv2
    import numpy as np
    import os
    import glob
    import mahotas as mt
    from sklearn.svm import LinearSVC
    
    # function to extract haralick textures from an image
    def extract_features(image):
        # calculate haralick texture features for 4 types of adjacency
        textures = mt.features.haralick(image)
    
        # take the mean of it and return it
        ht_mean = textures.mean(axis = 0).reshape(1, -1)
        return ht_mean
    
    # load the training dataset
    train_path  = "C:\\dataset\\train"
    train_names = os.listdir(train_path)
    
    # empty list to hold feature vectors and train labels
    train_features = []
    train_labels   = []
    
    # loop over the training dataset
    print ("[STATUS] Started extracting haralick textures..")
    for train_name in train_names:
        cur_path = train_path + "\\" + train_name
        print(cur_path)
        cur_label = train_name
        i = 1
    
        for file in glob.glob(cur_path + "\*.jpg"):
            print ("Processing Image - {} in {}".format(i, cur_label))
            # read the training image
            #print(file)
            image = cv2.imread(file)
            #print(image)
    
            # convert the image to grayscale
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
            # extract haralick texture from the image
            features = extract_features(gray)
            #print(features.reshape(1, -1))
            # append the feature vector and label
            train_features.append(features.reshape(1, -1)[0])
            train_labels.append(cur_label)
    
            # show loop update
            i += 1
    
    # have a look at the size of our feature vector and labels
    print ("Training features: {}".format(np.array(train_features).shape))
    print ("Training labels: {}".format(np.array(train_labels).shape))
    
    # create the classifier
    print ("[STATUS] Creating the classifier..")
    clf_svm = LinearSVC(random_state = 9)
    
    # fit the training data and labels
    print ("[STATUS] Fitting data/label to model..")
    print(train_features)
    clf_svm.fit(train_features, train_labels)
    
    # loop over the test images
    test_path = "C:\\dataset\\test"
    for file in glob.glob(test_path + "\*.jpg"): 
        # read the input image
        image = cv2.imread(file)
    
        # convert to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
        # extract haralick texture from the image
        features = extract_features(gray)
    
        # evaluate the model and predict label
        prediction = clf_svm.predict(features)
    
        # show the label
        cv2.putText(image, str(prediction), (20,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,255), 3)
        print ("Prediction - {}".format(prediction))
    
        # display the output image
        cv2.imshow("Test_Image", image)
        cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    【讨论】:

    • 感谢您的回答,Anubhav。我已经尝试了你的回答,但现在我收到了这个警告。 ConvergenceWarning: Liblinear failed to converge, increase the number of iterations。环顾四周,我发现我必须增加迭代次数。¿你怎么看?
    • 为了补充上面的评论,我在LinearSVC 中使用了dual = False 来避免警告,但进程仍然中止。
    • 但是,请告诉我一件事:C:\\dataset\\train。它需要包含类文件夹,其中包含 .jpg 文件。
    • LinearSVC 模型中尝试max_iter=10000。如果这不起作用,请尝试在 0-1 之间缩放数据以处理 ConvergenceWarning: Liblinear failed to converge, increase the number of iterations
    • 我修正了你告诉我的关于测试集中路径的问题。没有意识到没有必要在其中包含子文件夹。非常感谢。
    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2018-10-15
    • 1970-01-01
    • 2013-06-13
    • 2015-04-07
    • 2017-10-06
    相关资源
    最近更新 更多