dlib 라이브러리 : 기계 학습 알고리즘, 이미지 처리 등의 기능을 가지는 툴킷으로, 기존에 C++로 작성된 툴킷이지만, python 패키지로도 설치해 사용할 수 있습니다.
conda install -c conda-forge dlib
저는 아나콘다를 사용하기 때문에 위의 코드를 설치합니다.
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
if ret == False:
break
dets = detector(img)
print("number of faces detected:", len(dets))
print(dets)
for det in dets:
x1 = det.left()
y1 = det.top()
x2 = det.right()
y2 = det.bottom()
cv2.rectangle(img, pt1=(x1, y1), pt2=(x2, y2),
color=(0, 255, 0), thickness=2)
cv2.imshow('result', img)
if cv2.waitKey(1) == ord('q'):
break
detector = dlib.get_frontal_face_detector()
dlib.get_frontal_face_detector()로 생성된 기본 face_detecor 객체는 dlib.fhog_object_detector 객체입니다.
print("number of faces detected:", len(dets))
print(dets)
위의 출력은 아래와 같습니다.
number of faces detected: 1
rectangles[[(512, 35) (691, 214)]]
len(dets)를 통하여 화면 안에 검출된 얼굴의 총개수를 추출합니다.
dets는 탐지된 얼굴 영역의 왼쪽 상단 꼭짓점 좌표와 우측 하단 꼭짓점 좌표가 리스트 안에 튜플 형식으로 나타납니다.
for det in dets:
x1 = det.left()
y1 = det.top()
x2 = det.right()
y2 = det.bottom()
cv2.rectangle(img, pt1=(x1, y1), pt2=(x2, y2), color=(0, 255, 0), thickness=2)
탐지한 얼굴 영역에 대하여 사각형을 그립니다.
출력 결과
number of faces detected: 6
rectangles[[(821, 261) (893, 333)], [(997, 245) (1069, 317)], [(333, 237) (405, 309)], [(149, 269) (221, 341)], [(629, 285) (701, 357)], [(501, 293) (573, 365)]]
얼굴 일정 부분에 대해 랜드마크를 얻고 싶으신 분은 자신이 필요한 모델을 위의 링크에서 다운로드하여 사용하시면 됩니다.
'OpenCV-Python' 카테고리의 다른 글
OpenCV Python 원하는 이미지 영역 잘라내기(붙이기) (0) | 2021.11.27 |
---|---|
dlib 눈 인식(Ear 알고리즘을 이용한 졸음인식) (0) | 2021.11.25 |
OpenCV Python 히스토그램 역투영 (0) | 2021.09.01 |
OpenCV Python 색상 영역 검출 (0) | 2021.08.31 |
OpenCV Python 히스토그램 평활화 (0) | 2021.08.30 |