University projects
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

180 lines
5.5 KiB

  1. #!/usr/bin/python
  2. """
  3. This program is demonstration for face and object detection using haar-like features.
  4. The program finds faces in a camera image or video stream and displays a red box around them.
  5. Original C implementation by: ?
  6. Python implementation by: Roman Stanchak
  7. """
  8. import sys
  9. import os
  10. from opencv.cv import *
  11. from opencv.highgui import *
  12. from PIL import Image
  13. # Global Variables
  14. cascade = None
  15. storage = cvCreateMemStorage(0)
  16. cascade_name = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml"
  17. input_name = "../c/lena.jpg"
  18. # Parameters for haar detection
  19. # From the API:
  20. # The default parameters (scale_factor=1.1, min_neighbors=3, flags=0) are tuned
  21. # for accurate yet slow object detection. For a faster operation on real video
  22. # images the settings are:
  23. # scale_factor=1.2, min_neighbors=2, flags=CV_HAAR_DO_CANNY_PRUNING,
  24. # min_size=<minimum possible face size
  25. min_size = cvSize(20,20)
  26. image_scale = 1.2
  27. haar_scale = 1.2
  28. min_neighbors = 2
  29. haar_flags = CV_HAAR_DO_CANNY_PRUNING
  30. def crop_count(facecropped):
  31. #get image dimensions
  32. iheight = int(facecropped.height / 2);
  33. iwidth = int(facecropped.width);
  34. iy = int(facecropped.width / 2);
  35. #create a crop rect
  36. crop1 = cvRect(60,iy,iwidth/2,iheight);
  37. #select crop rect area from original image
  38. halff = cvGetSubRect(facecropped,crop1);
  39. #get new image dimensions
  40. mheight = int(halff.height /2);
  41. mwidth = int(halff.width);
  42. my = int(halff.height / 2);
  43. #create a crop box for mouth
  44. crop2 = cvRect(0,my,mwidth,mheight);
  45. #select crop rect area from image
  46. mouth = cvGetSubRect(halff,crop2);
  47. #create temp images
  48. source = mouth;
  49. grey = cvCreateImage (cvSize (mouth.width, mouth.height), 8, 1)
  50. output = cvCreateImage (cvSize (mouth.width, mouth.height), 8, 1)
  51. # Convert to greyscale
  52. cvCvtColor (source, grey, CV_BGR2GRAY)
  53. # Convert to black and white based on threshold of 50
  54. cvThreshold(grey, output, 50, 255, CV_THRESH_BINARY);
  55. count = 0
  56. # Count number of dark pixels
  57. for i in output:
  58. for j in i:
  59. if j == 255:
  60. count += 1
  61. print "Number of dark pixels: " + str(count)
  62. #left for testing
  63. #cvSaveImage("face.jpg", output);
  64. def detect_and_draw( img ):
  65. # allocate temporary images
  66. gray = cvCreateImage( cvSize(img.width,img.height), 8, 1 );
  67. small_img = cvCreateImage( cvSize( cvRound (img.width/image_scale),
  68. cvRound (img.height/image_scale)), 8, 1 );
  69. # convert color input image to grayscale
  70. cvCvtColor( img, gray, CV_BGR2GRAY );
  71. # scale input image for faster processing
  72. cvResize( gray, small_img, CV_INTER_LINEAR );
  73. cvEqualizeHist( small_img, small_img );
  74. cvClearMemStorage( storage );
  75. if( cascade ):
  76. t = cvGetTickCount();
  77. faces = cvHaarDetectObjects( small_img, cascade, storage,
  78. haar_scale, min_neighbors, haar_flags, min_size );
  79. t = cvGetTickCount() - t;
  80. print "detection time = %gms" % (t/(cvGetTickFrequency()*1000.));
  81. if faces:
  82. for face_rect in faces:
  83. # the input to cvHaarDetectObjects was resized, so scale the
  84. # bounding box of each face and convert it to two CvPo
  85. # pt1 = cvPoint( int(face_rect.x*image_scale), int(face_rect.y*image_scale))
  86. # pt2 = cvPoint( int((face_rect.x+face_rect.width)*image_scale),
  87. # int((face_rect.y+face_rect.height)*image_scale) )
  88. x = int(face_rect.x*image_scale);
  89. y = int(face_rect.y*image_scale);
  90. h = int(face_rect.height*image_scale);
  91. w = int(face_rect.width*image_scale);
  92. print x,y,w,h
  93. face = cvRect(x,y,w,h);
  94. crop = cvGetSubRect(img,face);
  95. #cvSaveImage("face.jpg", crop);
  96. crop_count(crop);
  97. if __name__ == '__main__':
  98. if len(sys.argv) > 1:
  99. if sys.argv[1].startswith("--cascade="):
  100. cascade_name = sys.argv[1][ len("--cascade="): ]
  101. if len(sys.argv) > 2:
  102. input_name = sys.argv[2]
  103. elif sys.argv[1] == "--help" or sys.argv[1] == "-h":
  104. print "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" ;
  105. sys.exit(-1)
  106. else:
  107. input_name = sys.argv[1]
  108. # the OpenCV API says this function is obsolete, but we can't
  109. # cast the output of cvLoad to a HaarClassifierCascade, so use this anyways
  110. # the size parameter is ignored
  111. cascade = cvLoadHaarClassifierCascade( cascade_name, cvSize(1,1) );
  112. if not cascade:
  113. print "ERROR: Could not load classifier cascade"
  114. sys.exit(-1)
  115. if input_name.isdigit():
  116. capture = cvCreateCameraCapture( int(input_name) )
  117. else:
  118. capture = cvCreateFileCapture( input_name );
  119. if( capture ):
  120. frame_copy = None
  121. i = 0;
  122. while True:
  123. frame = cvQueryFrame( capture );
  124. print i;
  125. if( not frame ):
  126. break;
  127. if( not frame_copy ):
  128. frame_copy = cvCreateImage( cvSize(frame.width,frame.height),
  129. IPL_DEPTH_8U, frame.nChannels );
  130. if( frame.origin == IPL_ORIGIN_TL ):
  131. cvCopy( frame, frame_copy );
  132. else:
  133. cvFlip( frame, frame_copy, 0 );
  134. detect_and_draw( frame_copy );
  135. i = i+1;
  136. if( cvWaitKey( 10 ) >= 0 ):
  137. break;
  138. else:
  139. image = cvLoadImage( input_name, 1 );
  140. if( image ):
  141. detect_and_draw( image );
  142. cvWaitKey(0);
  143. cvDestroyWindow("result");