Close

Summary of python code for Object Detector using Histogram of Oriented Gradients (HOG) and Linear Support Vector Machines (SVM)

A project log for Elephant AI

a system to prevent human-elephant conflict by detecting elephants using machine vision, and warning humans and/or repelling elephants

neil-k-sheridanNeil K. Sheridan 04/28/2017 at 18:290 Comments

Dependencies:

from __future__ import print_function
from sklearn.feature_extraction.image import extract_patches_2d
from imutils import paths
from scipy import io
import numpy as np
import random
import cv2
import cPickle
from sklearn.svm import SVC

1. Extracting features

#init HOG detector

hog = HOG(orientations=conf["orientations"], pixelsPerCell=tuple(conf["pixels_per_cell"]),
	cellsPerBlock=tuple(conf["cells_per_block"]), normalize=conf["normalize"])
data = []
labels = []

# TRAINING IMAGES
# collect the paths to the training (positive elephant) images

pos_paths = list(paths.list_images(conf["positive_images"]))
print("1/3: Processing training images")

for (i, pos_path) in enumerate(pos_paths):
	# load training image
	image = cv2.imread(pos_path)
	# convert to grayscale
	train_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	# resize
	train_image = cv2.resize(train_image, (122, 96), interpolation=cv2.INTER_AREA)
	# put the train_image into a list called train_image_list
	train_image_list = (train_image, cv2.flip(train_image, 1)) if conf["use_flip"] else (train_image,)

	# loop for train_image in train_image_list
	for train_image in train_image_list:
		# extract features from train_image and add to list of features
		features = hog.describe(train_image)
		data.append(features)
		labels.append(1)

#NEGATIVE IMAGES

neg_paths = list(paths.list_images(conf["negative_images"]))
print("2/3: Processing negative images")

or i in np.arange(0, conf["num_negative_images"]):
	# randomly select a negative image
	# extract patches
	image = cv2.imread(random.choice(neg_paths))
	if image is not None:
	    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            #note here 3737: error: (-215) scn == 3 || scn ==4 in function cvtColor if u pass
            #a bad input image
	    patches = extract_patches_2d(image, tuple(conf["window_dim"]),
		max_patches=conf["num_distractions_per_image"])

	
	for patch in patches:
		# extract features from patch 
		features = hog.describe(patch)
		# update list
		data.append(features)
		labels.append(-1)


#SAVING DATA FILE
print("3/3 Saving file")
dataset.dump_dataset(data, labels, conf["features_path"], "features")

2. Training classifier

print("1/2: training classifier...")
model = SVC(kernel="linear", C=conf["C"], probability=True, random_state=22)
model.fit(data, labels)

# save classifier to cpickle file
print("2/2: saving classifier to cpickle file")
f = open(conf["classifier_path"], "w")
f.write(cPickle.dumps(model))
f.close

See http://scikit-learn.org/stable/tutorial/basic/tutorial.html for information on using scikitlearn

Discussions