我在使用 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/