import cv2
import os
import numpy as np
import hog_discriptor
def get_path():
print('loading data...')
PosImgPath = "D:\\A\\python\\opencv\\tests\\hog_pedestran_detect_python\\Positive"
NegImgPath = "D:\\A\\python\\opencv\\tests\\hog_pedestran_detect_python\\Negative"
PosImgList = os.listdir(PosImgPath)
NegImgList = os.listdir(NegImgPath)
print('Number of positive samples:', len(PosImgList))
print('Number of negative samples:', len(NegImgList))
samplePath = []
labels = []
for f in PosImgList:
samplePath.append('Positive\\' + f)
labels.append(1)
for f in NegImgList:
samplePath.append('Negative\\' + f)
labels.append(-1)
labels = np.array(labels)
return samplePath, labels
def extract_hog(samplePath):
print('extracting hog...')
winSize = (64, 128)
blockSize = (16, 16)
blockStride = (8, 8)
cellSize = (8, 8)
Bin = 9
hogDescriptor = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, Bin)
hogFeature = []
for f in samplePath:
img = cv2.imread(f, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (64, 128))
discriptor = hogDescriptor.compute(img)
hogFeature.append(discriptor)
hogFeature = np.array(hogFeature)
return hogFeature
def train_svm(hogFeature, labels):
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setP(0.01)
svm.setC(0.01)
svm.setType(cv2.ml.SVM_EPS_SVR)
print('training...')
svm.train(hogFeature, cv2.ml.ROW_SAMPLE, labels)
print('done.')
return svm
def get_svm_detecter(svm):
SupportVector = svm.getSupportVectors()
SupportVector = np.transpose(SupportVector)
rho, alpha, _ = svm.getDecisionFunction(0)
return np.append(alpha * SupportVector, [[-rho]], 0)
def detect(MyDecter):
imageSrc = cv2.imread('TestData\\000001.jpg', cv2.IMREAD_COLOR)
myHog = cv2.HOGDescriptor()
myHog.setSVMDetector(MyDecter)
objects, _ = myHog.detectMultiScale(imageSrc, winStride=(8, 8), padding=(16, 16), scale=1.04)
for (x, y, w, h) in objects:
cv2.rectangle(imageSrc, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('img', imageSrc)
cv2.waitKey(0)
if __name__ == '__main__':
samplePath, labels = get_path()
hogFeature = extract_hog(samplePath)
svm = train_svm(hogFeature, labels)
MyDecter = get_svm_detecter(svm)
detect(MyDecter)