Python:ValueError:类的数量必须大于1;得到1

时间:2017-05-29 09:37:07

标签: python image-processing computer-vision classification svm

根据Tonechasthis post建议,计算一组图像的红色通道直方图然后将它们分类为正确类型的代码是:

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;得到1

有人可以帮忙吗?感谢

2 个答案:

答案 0 :(得分:0)

看看你的功能:

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.

return循环for的第一次迭代结束时,您folders。你需要取消缩进这一行。

答案 1 :(得分:-1)

我只是有同样的问题 我想通了 下载您的数据时,有时标签或目标是String 尝试y = y.astype(np.uint8)