Human Target in less than 90 lines of Code (Python+OpenCV)

07 Feb

Using python and the versatile OpenCV library its possible to get a human detection system in less than 90 lines of code.This assumes a basic knowledge of python and some working knowledge of the OpenCV computer vision library.


The initialization selects whether a camera is to be used or captured image file from the disk,with the inbuilt functions as many cameras as needed can be connected starting from CAM(0) and going up incrementally.

   def __init__(self , typ , fpath):
if( typ == 1 ):
self.capture = cv.CaptureFromCAM(0)
elif( typ == 2 ):
self.capture = cv.CaptureFromFile(fpath)
cv.NamedWindow(“Target”, 1)


Before the human can be detected we have to clear up the artifacts that may reduce the efficiency of our detection algorithms.This involves Gaussian smoothing to eliminate false positives.

The capture is gray-scale converted as this color space can be worked on faster than a full color space and re-sized to a smaller size also for the same added speed in processing.

           # Smooth to get rid of false positives
cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0)

# Convert the image to grayscale.
cv.CvtColor(color_image, grey_image, cv.CV_RGB2GRAY)

# scale input image for faster processing
cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)

cv.EqualizeHist(small_img, small_img)


The detection is carried out by utilizing a HaarCascade based on Viola-Jones.After training to detect a specific object of interest , the cascade file (an XML) is loaded with into the HaarDetectObjects function which stores the detected objects as a tuple which when iterated over yields our detected objects position.

cascade = cv.Load(“data/HS.xml”)

faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0),
haar_scale, min_neighbors, cv.CV_HAAR_DO_CANNY_PRUNING, min_size)

A central point is computed and a rectangle with a bulls-eye.The VideoWriter provides a easy way to capture an recording of the whole program run.

writer = cv.CreateVideoWriter(“output.avi”, cv.CV_FOURCC(‘M’,’J’,’P’,’G’), 15, frame_size)

cv.WriteFrame(writer, color_image)

humans found
Leave a comment

Posted by on February 7, 2012 in Computer Vision, Python


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: