Python 如何在二维向量上使用整形()函数
我重新塑造了一个特征向量,但仍然出现以下错误:Python 如何在二维向量上使用整形()函数,python,python-3.x,opencv,machine-learning,numpy-ndarray,Python,Python 3.x,Opencv,Machine Learning,Numpy Ndarray,我重新塑造了一个特征向量,但仍然出现以下错误: 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. 我在预测之前使用过重塑,比如 featu
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.
我在预测之前使用过重塑,比如
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)
我不知道我是否错误地使用了整形()或缺少了什么
ValueError:应为2D数组,而应为1D数组:数组=[]。
使用数组重塑数据。如果数据具有单个特征或数组,则重塑(-1,1)。如果数据包含单个样本,则重塑(1,-1)。请考虑以下几点:
- 出现上述错误是因为
在train\u features
行中为[](空列表)。它应至少包含clf\u svm.fit(train\u features,train\u label)
数据。这是因为1
指向一个仅包含图像文件的文件夹,但上述代码假设train\u path
指向一个至少包含train\u path
子文件夹(无文件)的文件夹 在这里,培训数据的类名将是1
[class1,class2,…]
- 正确的行
到train\u features.append(features.reformate(1,-1))[0]
train\u features.append(features.reformate(1,-1)[0])
的输出是一个numpy数组。因此,在clf\u svm.predict(features)
函数中将cv2.putText
替换为prediction
。您还可以将其替换为str(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()
谢谢你的回答,阿努巴夫。我试过你的回答,但现在我得到了这个警告<代码>收敛警告:Liblinear无法收敛,请增加迭代次数。环顾四周,我发现我必须增加迭代次数。你认为呢?为了补充上面的评论,我在
LinearSVC
中使用了dual=False
,以避免警告,但该过程仍然中止。但是,请告诉我一件事,你的路径是什么:C:\\dataset\\train
。它需要包含包含.jpg文件的类文件夹。请在LinearSVC
model中尝试max\u iter=10000
。如果这不起作用,请尝试在0-1之间缩放数据以处理收敛警告:Liblinear无法收敛,请增加迭代次数
。我修复了您告诉我的测试集中的路径。没有意识到没有必要在其中包含子文件夹。非常感谢你。
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()