视频人脸检测

  1. import numpy as np
  2. import cv2
  3. face_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml')
  4. eye_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_eye.xml')
  5. # 创建一个 VideoCapture 对象,参数是设备的索引即摄像机的编号或者 Video 的文件名
  6. # 这里的 0 是指第一台摄像机,以此类推
  7. cap = cv2.VideoCapture(0)
  8. ret, frame = cap.read()
  9. while (ret):
  10. # while cap.isOpened():
  11. # 一帧一帧的捕获
  12. ret, frame = cap.read()
  13. #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  14. faces = face_cascade.detectMultiScale(frame, 1.3, 5)
  15. for (x, y, w, h) in faces:
  16. img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
  17. #roi_gray = gray[y:y+h, x:x+w]
  18. roi_color = img[y:y+h, x:x+w]
  19. eyes = eye_cascade.detectMultiScale(roi_color)
  20. for (ex, ey, ew, eh) in eyes:
  21. cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
  22. cv2.imshow("frame", frame)
  23. if cv2.waitKey(1) & 0xFF == 27: # ord('q'):
  24. break
  25. # cap.release()
  26. cv2.destroyAllWindows()
  1. import cv2 as cv
  2. capture = cv.VideoCapture(0)
  3. face_detector = cv.CascadeClassifier("C:/Anaconda3/Library/etc/haarcascades/haarcascade_frontalface_default.xml")
  4. smile_detector = cv.CascadeClassifier("C:/Anaconda3/Library/etc/haarcascades/haarcascade_smile.xml")
  5. while True:
  6. ret, image = capture.read()
  7. if ret is True:
  8. cv.imshow("frame", image)
  9. faces = face_detector.detectMultiScale(image, scaleFactor=1.05, minNeighbors=3,
  10. minSize=(30, 30), maxSize=(300, 300))
  11. for x, y, width, height in faces:
  12. cv.rectangle(image, (x, y), (x+width, y+height), (0, 0, 255), 2, cv.LINE_8, 0)
  13. roi = image[y:y+height,x:x+width]
  14. smiles = smile_detector.detectMultiScale(roi, scaleFactor=1.7, minNeighbors=3,
  15. minSize=(15, 15), maxSize=(100, 100))
  16. for sx, sy, sw, sh in smiles:
  17. cv.rectangle(roi, (sx, sy), (sx + sw, sy + sh), (0, 255, 0), 1)
  18. cv.imshow("faces", image)
  19. c = cv.waitKey(50)
  20. if c == 27:
  21. break
  22. else:
  23. break
  24. cv.destroyAllWindows()

图片人脸检测

  1. import numpy as np
  2. import cv2
  3. face_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_frontalface_default.xml')
  4. eye_cascade = cv2.CascadeClassifier('./data/haarcascades/haarcascade_eye.xml')
  5. img = cv2.imread("F:/jupyter/OpenCV-Python-Tutorial/Tutorial/sample_img/lena.jpg")
  6. faces = face_cascade.detectMultiScale(img, 1.3, 5)
  7. for (x,y,w,h) in faces:
  8. img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
  9. roi_gray = img[y:y+h, x:x+w]
  10. roi_color = img[y:y+h, x:x+w]
  11. eyes = eye_cascade.detectMultiScale(roi_gray)
  12. for (ex,ey,ew,eh) in eyes:
  13. cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
  14. cv2.imshow('img',img)
  15. cv2.waitKey(0)
  16. cv2.destroyAllWindows()

视频人脸表情检测

  1. #!usr/bin/env python
  2. # -*- coding:utf-8 _*-
  3. """
  4. @author:asus_pc
  5. @file: face_detector.py
  6. @time: 2019/08/17
  7. """
  8. # 开发环境
  9. # Python3.6
  10. # Python 2/3 compatibility
  11. import cv2 # 4.0.0
  12. import dlib # 19.8.1 到 https://pypi.org/simple/dlib/ 下载 whl 文件 pip install *.whl 安装
  13. import numpy as np # 1.16.2
  14. from pathlib import Path
  15. import sys
  16. # 配置 Dlib 关键点检测路径
  17. # 文件可以从 http://dlib.net/files/ 下载
  18. PREDICTOR_PATH = "C:/BLOG/Computer_Vision_Project/Computer_Vision_Project/Facial_Expression_Recognition/6_server_demo/static/face_detector_trained/shape_predictor_68_face_landmarks.dat"
  19. predictor = dlib.shape_predictor(PREDICTOR_PATH) # 关键点检测
  20. # 配置人脸检测器路径
  21. cascade_path = "C:/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml" # 在 opencv github 可以找到
  22. # 初始化分类器
  23. cascade = cv2.CascadeClassifier(cascade_path)
  24. # 调用 cascade.detectMultiScale 人脸检测器和 Dlib 的关键点检测算法 predictor 获得关键点结果
  25. def get_landmarks(im):
  26. try:
  27. rects = cascade.detectMultiScale(im, 1.3, 5) # 进行多尺度检测
  28. if len(rects) == 1:
  29. x, y, w, h = rects[0]
  30. rect = dlib.rectangle(int(x), int(
  31. y), int(x + w), int(y + h)) # 获得检测框
  32. # 调用 dlib 关键点检测
  33. return np.matrix([[p.x, p.y] for p in predictor(im, rect).parts()])
  34. except:
  35. return None
  36. # 打印关键点信息方便调试
  37. def annotat_landmarks(im, landmarks):
  38. im = im.copy()
  39. for idx, point in enumerate(landmarks):
  40. pos = (point[0, 0], point[0, 1])
  41. cv2.putText(im, str(idx),
  42. pos,
  43. fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
  44. fontScale=0.4,
  45. color=(0, 0, 255))
  46. cv2.circle(im, pos, 5, color=(0, 255, 255))
  47. return im
  48. def get_mouth(im):
  49. # 得到 68 个关键点
  50. landmarks = get_landmarks(im)
  51. if landmarks is not None:
  52. # print(landmarks)
  53. xmin = 10000
  54. xmax = 0
  55. ymin = 10000
  56. ymax = 0
  57. # 根据最外围的关键点获取包围嘴唇的最小矩形框
  58. # 68 个关键点是从
  59. # 左耳朵0 -下巴-右耳朵16-左眉毛(17-21)-右眉毛(22-26)-左眼睛(36-41)
  60. # 右眼睛(42-47)-鼻子从上到下(27-30)-鼻孔(31-35)
  61. # 嘴巴外轮廓(48-59)嘴巴内轮廓(60-67)
  62. for i in range(48, 67):
  63. x = landmarks[i, 0]
  64. y = landmarks[i, 1]
  65. if x < xmin:
  66. xmin = x
  67. if x > xmax:
  68. xmax = x
  69. if y < ymin:
  70. ymin = y
  71. if y > ymax:
  72. ymax = y
  73. # print("xmin", xmin)
  74. # print("xmax", xmax)
  75. # print("ymin", ymin)
  76. # print("ymax", ymax)
  77. roiwidth = xmax - xmin # 矩形框的宽和高
  78. roiheight = ymax - ymin
  79. roi = im[ymin:ymax, xmin:xmax, :]
  80. # cv2.imshow("roi_0", roi)
  81. # 将最小矩形扩大 1.5 倍,获得最终矩形框
  82. if roiwidth > roiheight: # 宽和高哪个大哪个就 ×1.5 倍
  83. dstlen = 1.5 * roiwidth
  84. else:
  85. dstlen = 1.5 * roiheight
  86. diff_xlen = dstlen - roiwidth
  87. diff_ylen = dstlen - roiheight
  88. newx = xmin
  89. newy = ymin
  90. imagerows, imagecols, ch = im.shape
  91. # print("imagerows, imagecols", imagerows, imagecols)
  92. if newx >= diff_xlen / 2 and newx + roiwidth + diff_xlen / 2 < imagecols:
  93. newx = newx - diff_xlen / 2
  94. elif newx < diff_xlen / 2:
  95. newx = 0
  96. else:
  97. newx = imagecols - dstlen
  98. if newy >= diff_ylen / 2 and newy + roiheight + diff_ylen / 2 < imagerows:
  99. newy = newy - diff_ylen / 2
  100. elif newy < diff_ylen / 2:
  101. newy = 0
  102. else:
  103. newy = imagecols - dstlen
  104. roi = im[int(newy):int(newy + dstlen), int(newx):int(newx + dstlen), :]
  105. return roi # 得到人脸关键点就返回嘴巴区域
  106. return None # 否则返回空
  107. # cv2.imshow("roi", roi)
  108. # cv2.imwrite(dst+im_path.name, roi)
  109. if __name__ == '__main__':
  110. # 创建一个 VideoCapture 对象,参数是设备的索引即摄像机的编号或者 Video 的文件名
  111. # 这里的 0 是指第一台摄像机,以此类推
  112. cap = cv2.VideoCapture(0)
  113. ret, frame = cap.read()
  114. while (ret):
  115. # while cap.isOpened():
  116. # 一帧一帧的捕获
  117. ret, frame = cap.read()
  118. landmarks = get_landmarks(frame)
  119. if landmarks is not None:
  120. frame = annotat_landmarks(frame, landmarks)
  121. cv2.imshow("frame", frame)
  122. if cv2.waitKey(1) & 0xFF == 27: # ord('q'):
  123. break
  124. cv2.waitKey(0)
  125. cv2.destroyAllWindows()