Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou takatakamanbou/00_face_mischief.md Secret
Last active Oct 1, 2015

Embed
What would you like to do?
##### face_mischief.py ver 20150930
import numpy as np
import cv2
#fnHaarCascade = '/opt/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'
fnHaarCascade = '/opt/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml'
def drawFrame( img, x, y, w, h ):
cv2.rectangle( img, ( x, y ), ( x + w, y + h ), ( 0, 255, 0 ), 3 )
def drawBlackBar( img, x, y, w, h ):
posLT = ( x, int( y + h * 0.3 ) )
posRB = ( x + w, int( y + h * 0.45 ) )
cv2.rectangle( img, posLT, posRB, color = ( 0, 0, 0 ), thickness = -1 )
def drawBeam( img, x, y, w, h, state ):
# beam color
hsv = np.uint8( [ [ [ int( state * 180 ), 255, 255 ] ] ] )
bgr = np.asarray( cv2.cvtColor( hsv, cv2.COLOR_HSV2BGR )[0, 0], dtype = int )
# beam directions are varied periodically
dxL = int( 50 * np.sin( 2 * np.pi * state ) )
dxR = int( 80 * np.sin( 2 * np.pi * ( state + 0.25 ) ) )
# left beam
eyeL = ( int( x + w * 0.3 ), int( y + h * 0.35 ) )
targetL = ( x - 100 + dxL, img.shape[0] )
cv2.line( img, eyeL, targetL, color = bgr, thickness = w / 6 )
# right beam
eyeR = ( int( x + w * 0.7 ), int( y + h * 0.35 ) )
targetR = ( img.shape[1] - 200 + dxR, img.shape[0] )
cv2.line( img, eyeR, targetR, color = bgr, thickness = w / 6 )
if __name__ == '__main__':
cascade = cv2.CascadeClassifier( fnHaarCascade )
cap = cv2.VideoCapture( 0 )
cnt = 0
state = 0
while( True ):
rv, frame = cap.read()
img = cv2.resize( frame, ( frame.shape[1] / 2, frame.shape[0] / 2 ) )
img = cv2.flip( img, 1 )
gray = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY )
gray = cv2.equalizeHist( gray )
faces = cascade.detectMultiScale( gray, scaleFactor = 1.1, minNeighbors = 5, minSize = ( 32, 32 ) )
for ( x, y, w, h ) in faces:
if state == 0:
drawFrame( img, x, y, w, h )
elif state == 1:
drawBlackBar( img, x, y, w, h )
elif state == 2:
drawBeam( img, x, y, w, h, cnt / 60.0 )
cv2.imshow( 'hoge', img )
key = cv2.waitKey( 1 )
if key == ord( 'q' ):
break
ik = key - ord( '0' )
if ik in [ 0, 1, 2 ]:
state = ik
cnt = ( cnt + 1 ) % 60
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.