python训练svm分类器_如何使用Python中的OpenCV 3.0中的HOG功能训练SVM分类器?

目前我有同样的问题,我看过OpenCV的以下文件:

在哪里可以找到答案的一部分:

deskewed = [map(deskew,row) for row in train_cells]

hogdata = [map(hog,row) for row in deskewed]

trainData = np.float32(hogdata).reshape(-1,64)

responses = np.float32(np.repeat(np.arange(10),250)[:,np.newaxis])

svm = cv2.ml.SVM_create()

svm.setKernel(cv2.ml.SVM_LINEAR)

svm.setType(cv2.ml.SVM_C_SVC)

svm.setC(2.67)

svm.setGamma(5.383)

svm.train(trainData, cv2.ml.ROW_SAMPLE, responses)

svm.save('svm_data.dat')

那是我正在合作的.一旦我解决了,我会更新答案.但此刻我希望它对你有所帮助.

………………………………………….. ……………………..

您可以在此opencv目录中找到名为digits.py的示例:

\opencv\sources\samples\python

根据您的opencv版本,SVM类的方法存在一些差异.这是opencv 3.1的一个例子.

svm = cv2.ml.SVM_create()

svm.setType(cv2.ml.SVM_C_SVC)

svm.setKernel(cv2.ml.SVM_RBF) # cv2.ml.SVM_LINEAR

# svm.setDegree(0.0)

svm.setGamma(5.383)

# svm.setCoef0(0.0)

svm.setC(2.67)

# svm.setNu(0.0)

# svm.setP(0.0)

# svm.setClassWeights(None)

svm.train(samples_train, cv2.ml.ROW_SAMPLE, labels_train)

resp = svm.predict(samples_test)[1].ravel()

print resp, labels_test

err = (labels_test != resp).mean()

print('error: %.2f %%' % (err*100))

confusion = np.zeros((10, 10), np.int32)

for i, j in zip(labels_test, resp):

confusion[i, j] += 1

print('confusion matrix:')

print(confusion)

print()

………………………………………….. ……………………..

最后我通过这种方式得到它:

samples = []

labels = []

# Get positive samples

for filename in glob.glob(os.path.join(positive_path, '*.jpg')):

img = cv2.imread(filename, 1)

hist = hog(img)

samples.append(hist)

labels.append(1)

# Get negative samples

for filename in glob.glob(os.path.join(negative_path, '*.jpg')):

img = cv2.imread(filename, 1)

hist = hog(img)

samples.append(hist)

labels.append(0)

# Convert objects to Numpy Objects

samples = np.float32(samples)

labels = np.array(labels)

# Shuffle Samples

rand = np.random.RandomState(321)

shuffle = rand.permutation(len(samples))

samples = samples[shuffle]

labels = labels[shuffle]

# Create SVM classifier

svm = cv2.ml.SVM_create()

svm.setType(cv2.ml.SVM_C_SVC)

svm.setKernel(cv2.ml.SVM_RBF) # cv2.ml.SVM_LINEAR

# svm.setDegree(0.0)

svm.setGamma(5.383)

# svm.setCoef0(0.0)

svm.setC(2.67)

# svm.setNu(0.0)

# svm.setP(0.0)

# svm.setClassWeights(None)

# Train

svm.train(samples, cv2.ml.ROW_SAMPLE, labels)

svm.save('svm_data.dat')

问候.

你可能感兴趣的:(python训练svm分类器)