Dennis Núñez

PhD (c) in AI and Neuroimaging. CEA / Inria / Université Paris-Saclay

Basic hand detector in C++ using Haar cascades on OpenCV 2.4

Implemented in OpenCV 2.4.x and 3.x. In the next link you can find the pre trained .xml file (created after training the Haar cascades classifier) that will be used to implement the hand detector: [link].


Create a the hand_detectop.cpp and fill in with the next content:

#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <iostream> #include <stdio.h> using namespace cv; using namespace std; Mat img; vector<Rect> hands; CascadeClassifier Hand; int main() { VideoCapture cap(0); char ch; namedWindow("Hand detection",CV_WINDOW_NORMAL); Hand.load("hand.xml"); while(true) { cap>>img; Hand.detectMultiScale(img,hands,1.1,3,0|CV_HAAR_FIND_BIGGEST_OBJECT,Size(30,30)); for(size_t i=0; i < hands.size() ; i++) { int point1x = hands[i].x; int point1y = hands[i].y; int lengthxy = hands[i].width; rectangle(img, Point(point1x,point1y), Point(point1x+lengthxy,point1y+lengthxy), Scalar(0,0,255), 1, 8, 0 ); imshow("Hand detection", img ); } imshow("Hand detection",img); ch=waitKey(1); if(ch==27) { break; } } return 0; }

Compilation and execution

Create the Makefile and fill in with the next content:

CC = g++ CFLAGS = -g -Wall SRCS = hand_detector.cpp PROG = hand_detector OPENCV_LIBS = /usr/local OPENCV = -I$(OPENCV_LIBS)/include/opencv -I$(OPENCV_LIBS)/include \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ $(OPENCV_LIBS)/lib/ \ $(OPENCV_LIBS)/lib/ LIBS = $(OPENCV) $(PROG):$(SRCS) $(CC) $(CFLAGS) -o $(PROG) $(SRCS) $(LIBS)

Then, compile with:

$ make

FInally, execute the created file with:

$ ./hand_detectop