2017-03-21 263 views
1

我在使用Python,OpenCV 3.1和HOG進行有用的檢測時遇到了問題。雖然我的工作代碼無誤地執行,但訓練後的HOG/SVM組合無法在測試圖像上檢測到。使用OpenCV在Python中進行HOG培訓和檢測

從OpenCV示例和其他堆棧溢出討論我已經開發了以下方法。

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是在圖像中居中的單一矩形和不位於其中正位於測試圖像英寸

我已經嘗試了許多基於堆棧溢出回答和其他OpenCV示例和討論的不同參數組合。他們都沒有改變結果。

+0

詳細和組織良好的問題解釋應該獎勵。我可以問你爲什麼只使用** svm.getSupportVectors()[0] **的原因嗎? – 3yanlis1bos

回答

0

我認爲你需要所有支持向量。所以問題不在於你的訓練碼,而是你的考驗。

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

你做你的訓練,你把所有的數據,但是當涉及到的測試,你只用得到的分類器的一小部分。

svmvec = svm.getSupportVectors()[0] 

更改此行,您將有一個較少的問題。

0

在中心創建單個矩形的原因是因爲檢測器幾乎將所有區域都分類爲「人」。 默認情況下,detectMultiScale抑制矩形的重疊。所以你只能看到中心的單個矩形。 您可以使用detectMultiScale的finalThreshold選項關閉此抑制。

hogParams = { 'finalThreshold': 0} 
found, w = hog.detectMultiScale(test_img, **hogParams) 

默認情況下,這個參數設置爲2 你可以看到幾乎所有的區域由矩形的顏色填充。

我對這種「錯誤分類」的答案是簡單地改變標籤的順序。

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