Skip to content

Instantly share code, notes, and snippets.

@CrociDB
Created June 21, 2010 00:35
Show Gist options
  • Save CrociDB/446249 to your computer and use it in GitHub Desktop.
Save CrociDB/446249 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
import cv
def detect(image):
image_size = cv.GetSize(image)
# create grayscale version
grayscale = cv.CreateImage(image_size, 8, 1)
cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
# create storage
storage = cv.CreateMemStorage(0)
# equalize histogram
#cv.EqualizeHist(grayscale, grayscale)
# detect objects
cascade = cv.Load('haar/haarcascade_frontalface_alt.xml')
#cascade = cv.Load('haar/haarcascade_frontalface_default.xml')
faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (50, 50))
if faces:
print 'face detected!'
for i in faces:
_x = int(i[0][0])
_y = int(i[0][1])
_w = int(i[0][2])
_h = int(i[0][3])
cv.Rectangle(image, (_x, _y), (_x + _w, _y + _h), cv.CV_RGB(0, 255, 0), 3, 8, 0)
if __name__ == "__main__":
# create windows
cv.NamedWindow('Camera')
# create capture device
device = 0 # assume we want first device
capture = cv.CreateCameraCapture(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
# check if capture device is OK
if not capture:
print "Error opening capture device"
sys.exit(1)
while 1:
# do forever
# capture the current frame
frame = cv.QueryFrame(capture)
if frame is None:
break
# mirror
cv.Flip(frame, None, 1)
# face detection
detect(frame)
# display webcam image
cv.ShowImage('Camera', frame)
# handle events
k = cv.WaitKey(10)
if k == 0x1b: # ESC
print 'ESC pressed. Exiting ...'
break
@CrociDB
Copy link
Author

CrociDB commented Jun 21, 2010

Esse código foi adaptado desse aqui: http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/ - que está usando a OpenCV 1.0 com um wrapper pra python. No meu caso, como eu to usando a OpenCV 2.1, que já vem com suporte a Python nativo, precisei fazer umas alterações. =D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment