python - 使用 OpenCV 在 Python 中进行 HOG 训练和检测

标签 python opencv

我在使用 Python、OpenCV 3.1 和 HOG 进行有用检测时遇到问题。虽然我有可以无误执行的工作代码,但经过训练的 HOG/SVM 组合无法在测试图像上进行检测。

根据 OpenCV 示例和其他 Stack Overflow 讨论,我开发了以下方法。

win_size = (64, 64)
block_size = (16, 16)
block_stride = (8, 8)
cell_size = (8, 8)
nbins = 9
deriv_aperture = 1
win_sigma = 4.
histogram_norm_type = 0
l2_hys_threshold = 2.0000000000000001e-01
gamma_correction = 0
nlevels = 64

hog = cv2.HOGDescriptor(win_size,
                        block_size,
                        block_stride,
                        cell_size,
                        nbins,
                        deriv_aperture,
                        win_sigma,
                        histogram_norm_type,
                        l2_hys_threshold,
                        gamma_correction,
                        nlevels)

window_stride = (8, 8)
padding = (8, 8)
locations = ((0, 0),)

histograms = []
# not showing the loop here but
# create histograms for 600 positive and 600 negative images
# all images are of size 64x64
histograms.append(np.transpose(hog.compute(roi, window_stride, padding, locations)))

training_data = np.concatenate(histograms)
classifications = np.array([1] * 600 + [0] * 600)

svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setC(0.01)
svm.setTermCriteria((cv2.TermCriteria_MAX_ITER, 100, 1e-6))

svm.train(training_data, cv2.ml.ROW_SAMPLE, classifications)

# testing
test_img = cv2.imread('test_image.jpg')
svmvec = svm.getSupportVectors()[0]
rho = -svm.getDecisionFunction(0)[0]
svmvec = np.append(svmvec, rho)
hog.setSVMDetector(svmvec)
found, w = hog.detectMultiScale(test_img)

在每个测试中,found 都是以图像为中心的单个矩形,并且不在测试图像中正例所在的位置。

我已经根据 Stack Overflow 答案和其他 OpenCV 示例和讨论尝试了许多不同的参数组合。它们都不会改变结果。

最佳答案

我认为您需要所有支持向量。所以问题不在于你的训练代码,而是你的测试。

svm.train(training_data, cv2.ml.ROW_SAMPLE, classifications)

您使用所有数据进行训练,但在进行测试时,您只使用生成的分类器的一小部分。

svmvec = svm.getSupportVectors()[0]

改变这一行,你就会少一个问题。

关于python - 使用 OpenCV 在 Python 中进行 HOG 训练和检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42937421/

相关文章:

python - Django 使用 Widget 覆盖 ModelForm 属性

python - 如何在 python 中递增数字字符串 '0000000001'?

Android OpenCV : update camera frames while executing AsyncTask

python - 在python中应用轮廓后如何从图像中提取文本?

opencv - haar分类器中cascade.xml的解释

python - TypeError:在python 2.7.6中无法调用 'int'对象

python - 拼接 NumPy 数组

python - Django : select_related with ManyToManyField

python - 如何关闭 tkinter 上的上一个窗口?

c++ - 如何从带有蒙版的轮廓图像中获取像素值?