本文介绍了Python:ValueError:类的数量必须大于1;得到1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从建议之后>这篇文章,计算一组图像的红色通道直方图然后将它们分类为正确类型的代码是:
Following Tonechas suggestion from this post, the code to compute the red channel histogram of a set of images and then classify them to the correct type, is this:
import cv2
import os
import glob
import numpy as np
from skimage import io
root = "C:/Users/joasa/data/train"
folders = ["Type_1", "Type_2", "Type_3"]
extension = "*.jpg"
# skip errors caused by corrupted files
def file_is_valid(filename):
try:
io.imread(filename)
return True
except:
return False
def compute_red_histogram(root, folders, extension):
X = []
y = []
for n, imtype in enumerate(folders):
filenames = glob.glob(os.path.join(root, imtype, extension))
for fn in filter(file_is_valid, filenames):
print(fn)
image = io.imread(fn)
img = cv2.resize(image, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_AREA)
red = img[:, :, 0]
h, _ = np.histogram(red, bins=np.arange(257), normed=True)
X.append(h)
y.append(n)
return np.vstack(X), np.array(y)
X, y = compute_red_histogram(root, folders, extension)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state = 0)
from sklearn.svm import SVC
clf = SVC()
clf.fit(X_train, y_train)
y_test
clf.predict(X_test)
y_test == clf.predict(X_test)
score = clf.score(X_test, y_test)
prediction = pd.DataFrame(y_test, score, columns=['prediction', 'score']).to_csv('prediction.csv')
我收到此错误:
ValueError:类的数量必须大于一;得到1
有人可以帮忙吗?谢谢
推荐答案
看看你的功能:
def compute_red_histogram(root, folders, extension):
X = []
y = []
for n, imtype in enumerate(folders):
filenames = glob.glob(os.path.join(root, imtype, extension))
for fn in filter(file_is_valid, filenames):
print(fn)
image = io.imread(fn)
img = cv2.resize(image, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_AREA)
red = img[:, :, 0]
h, _ = np.histogram(red, bins=np.arange(257), normed=True)
X.append(h)
y.append(n)
return np.vstack(X), np.array(y) ## <--- this line is not properly indented.
你在第一个结束时返回
的迭代
循环文件夹
。你需要取消缩进这一行。
You return
at the end of the first iteration of the for
loop over folders
. you need to un-indent this line.
这篇关于Python:ValueError:类的数量必须大于1;得到1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!