In [ ]:
import sys, time
import ipywidgets as widget
from IPython.display import display
import numpy as np
import cv2
from PIL import Image as PIL_Image
from io import BytesIO
cv2.startWindowThread()
def img_to_png(ima, cvt=None):
if cvt:
ima = cv2.cvtColor(ima, cvt)
im = PIL_Image.fromarray(ima)
bio = BytesIO()
im.save(bio, format='png')
return bio.getvalue()
In [ ]:
import dlib
sd = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
fr = cv2.face.createEigenFaceRecognizer()
fd = dlib.get_frontal_face_detector()
In [ ]:
cap = cv2.VideoCapture(0)
cap.set(3,1920)
cap.set(4,1080)
while True:
ret, img0 = cap.read()
img = cv2.resize(img0, (640,360))
H, W = img.shape[:2]
keycode = cv2.waitKey(1) & 0xff
if keycode == ord('q'):
break
#imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#ret,thresh = cv2.threshold(imgray,127,255,0)
#im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#cv2.drawContours(img, contours, -1, (0,255,0), 1)
#img = edges = cv2.Canny(img,100,200)
#img[:,:,0] += edges*128
"""
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (50,50,450,290)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
"""
rl = fd(img)
for r in rl:
shape = sd(img, r)
poly = np.int32([(x.x, x.y) for x in shape.parts()])*2
img0 = cv2.polylines(img0, np.int32([poly[:17]]) , 0, (0,255,255))
img0 = cv2.polylines(img0, np.int32([poly[17:22]]) , 0, (255,0,255))
img0 = cv2.polylines(img0, np.int32([poly[22:27]]) , 0, (255,0,255))
img0 = cv2.polylines(img0, np.int32([poly[27:31]]) , 0, (0,255,0))
img0 = cv2.polylines(img0, np.int32([poly[30:36]]) , 1, (0,255,0))
img0 = cv2.polylines(img0, np.int32([poly[36:42]]) , 1, (255,255,255))
img0 = cv2.polylines(img0, np.int32([poly[42:48]]) , 1, (255,255,255))
img0 = cv2.polylines(img0, np.int32([poly[48:60]]) , 1, (255,255,0))
img0 = cv2.polylines(img0, np.int32([poly[60:68]]) , 1, (255,255,0))
#img = cv2.rectangle(img, (r.left(),r.top()), (r.right(),r.bottom()), (255,255,0))
img0 = cv2.flip(img0, 1)
cv2.imshow('frame', img0)
#time.sleep(0.3)
cv2.destroyWindow('frame')
cap.release()