vision_face · 얼굴 인식

얼굴을 찾고 나이·성별·감정을 분석하며, 얼굴을 학습해 누구인지 알아봅니다.

Class: putTextPIL() Face

얼굴 찾기·나이·성별·감정·얼굴 구분은 OpenVINO(OMZ 모델), 얼굴 점·방향·거리는 MediaPipe 로 합니다. dlib 은 쓰지 않습니다(261104).

openpibo.vision_face.MASK_ONNX = '/home/pi/.model/mask/mask.onnx'

마스크 판별 — edge-lab 과 같은 파일(임베더 + 분류기 한 개, 입력 RGB 0~255 1x224x224x3). 처음 부를 때 올린다

openpibo.vision_face.DB_FORMAT = 'openpibo-facedb'

얼굴 정보 파일(save_db) 안에 적는 이름. 다른 모델로 만든 파일은 열지 않는다

openpibo.vision_face.THRESHOLD = 0.4

같은 사람으로 보는 최대 오차도. 예전(dlib)과 같은 값 0.4 — 학생 코드·블록이 쓰던 기준이 그대로 통하게 오차도 = 코사인 거리(0~2) x SCORE_SCALE 로 예전 크기에 맞춘다. 코사인 거리 0.6 이 오차도 0.4. 성인 공개 사진 LFW 1000쌍(261104)에서 코사인 0.6 은 다른 사람 오인 0%, 같은 사람 놓침 2.2% — 교실 아이 얼굴로 다시 볼 것

openpibo.vision_face.MP_TO_DLIB68 = (127, 234, 93, 132, 58, 136, 150, 176, 152, 400, 379, 365, 288, 361, 323, 454, 356, 70, 63, 105, 66, 107, 336, 296, 334, 293, 300, 168, 197, 5, 4, 75, 97, 2, 326, 305, 33, 160, 158, 133, 153, 144, 362, 385, 387, 263, 373, 380, 61, 39, 37, 0, 267, 269, 291, 405, 314, 17, 84, 181, 78, 82, 13, 312, 308, 317, 14, 87)

dlib 68점 번호 → MediaPipe 얼굴 점 번호. landmark_face 가 예전(dlib) 번호 그대로 돌려주게 한다 (턱 0~16 · 눈썹 17~26 · 코 27~35 · 눈 36~47 · 입 48~67)

openpibo.vision_face.REID_REF5 = array([[0.31556875, 0.46157411],        [0.68262292, 0.45983393],        [0.5002625 , 0.64050536],        [0.34947188, 0.82469196],        [0.65343646, 0.82325089]])

face-reidentification-retail-0095 의 정렬 기준점(128x128 기준 비율, OMZ face_recognition_demo 와 같은 값). 그림 왼쪽 눈 · 오른쪽 눈 · 코끝 · 입 왼쪽 끝 · 입 오른쪽 끝

openpibo.vision_face.MEAN68 = array([[0.009, 0.428],        [0.017, 0.503],        [0.026, 0.58 ],        [0.045, 0.662],        [0.079, 0.751],        [0.178, 0.872],        [0.243, 0.916],        [0.36 , 0.973],        [0.522, 0.996],        [0.685, 0.966],        [0.803, 0.903],        [0.868, 0.856],        [0.962, 0.729],        [0.989, 0.64 ],        [1.   , 0.556],        [1.001, 0.477],        [0.999, 0.402],        [0.096, 0.341],        [0.136, 0.314],        [0.198, 0.299],        [0.284, 0.301],        [0.384, 0.31 ],        [0.587, 0.304],        [0.687, 0.29 ],        [0.774, 0.284],        [0.841, 0.296],        [0.887, 0.321],        [0.491, 0.392],        [0.493, 0.468],        [0.495, 0.535],        [0.497, 0.576],        [0.413, 0.621],        [0.446, 0.637],        [0.502, 0.639],        [0.559, 0.634],        [0.591, 0.616],        [0.192, 0.412],        [0.235, 0.393],        [0.302, 0.389],        [0.375, 0.415],        [0.315, 0.423],        [0.248, 0.427],        [0.614, 0.409],        [0.683, 0.379],        [0.75 , 0.38 ],        [0.797, 0.396],        [0.741, 0.414],        [0.673, 0.414],        [0.323, 0.748],        [0.4  , 0.716],        [0.451, 0.708],        [0.507, 0.713],        [0.564, 0.705],        [0.618, 0.711],        [0.701, 0.739],        [0.623, 0.805],        [0.572, 0.821],        [0.512, 0.827],        [0.454, 0.824],        [0.404, 0.811],        [0.341, 0.748],        [0.462, 0.737],        [0.509, 0.738],        [0.557, 0.736],        [0.685, 0.74 ],        [0.559, 0.776],        [0.511, 0.78 ],        [0.463, 0.777]])

얼굴 점을 못 찾았을 때 돌려주는 평균 68점(상자 기준 비율). 예전 dlib 처럼 늘 68점을 돌려주게 한다 (LFW 300장에서 MediaPipe 점을 상자 비율로 평균, 261104)

openpibo.vision_face.putTextPIL(img, text, points, size=30, colors=(255, 255, 255))[소스]

이미지에 문자를 입력합니다. (한/영 가능 - pillow 이용)- COPY

매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • text (str) – 표시할 문자열

  • points (tuple(int, int)) – 텍스트 블록 좌측상단 좌표 (x, y)

  • size (int) – 표시할 글자의 크기

  • colors (tuple(int, int, int)) – 글자 색깔 BGR 값 (b, g, r) or 16진수 값 ‘#rrggbb’

class openpibo.vision_face.Face[소스]

기반 클래스: object

Functions: detect_face() landmark_face() analyze_face() mask_face() init_db() train_face() delete_face() recognize() get_db() save_db() load_db() detect_mesh()

얼굴과 관련된 다양한 기능을 수행하는 클래스입니다. 다음 기능을 수행할 수 있습니다.

  • 얼굴을 탐색합니다.

  • 얼굴을 학습/저장/삭제합니다.

  • 학습된 얼굴을 인식합니다.

  • 얼굴로 나이/성별/감정을 추정합니다.

얼굴 데이터베이스:

인스턴스 변수 facedb 를 의미하며, 여기에서 얼굴 데이터를 등록하고 불러오고 삭제합니다.

얼굴 데이터베이스의 포맷은 이중 list [[], []] 이며, 첫 번째 list에는 얼굴의 이름이, 두 번째 list에는 학습된 얼굴 데이터(숫자 256개)가 들어갑니다.

또한 파일로 저장하여 인스턴스가 삭제된 후에도 얼굴 정보를 남겨둘 수 있습니다.

example:

from openpibo.vision_face import Face

face = Face()
# 아래의 모든 예제 이전에 위 코드를 먼저 사용합니다.
preload()[소스]

얼굴 모델을 모두 미리 올립니다(처음 쓸 때 기다리지 않게). 보통은 부를 필요가 없습니다 — 각 기능을 처음 쓸 때 그 기능에 필요한 모델만 올립니다.

example:

face.preload()
detect_face(img)[소스]

얼굴을 탐색합니다.

example:

img = camera.read()
face.detect_face(img)
매개변수:

img (numpy.ndarray) – 이미지 객체

반환:

인식된 얼굴들의 (x1, y1, x2, y2) 배열 입니다.

list 타입으로, 이미지 하나에 얼굴이 여러 개 인식된 경우 인식된 얼굴의 좌표가 모두 입력됩니다.

example:

[[10, 10, 40, 50], [120, 30, 160, 70], [130, 140, 200, 260]]

detect_face_vis(img, items)[소스]

얼굴 box 표시합니다.

매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • items (array) – 얼굴 좌표 (x1,y1,x2,y2) 리스트

landmark_face(img, item)[소스]

얼굴의 랜드마크(68점)를 탐색합니다. 점 번호는 예전(dlib 68점)과 같습니다.

example:

img = camera.read()
items = face.detect_face(img)
face.landmark_face(img, items[0])
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (array) – 얼굴 좌표 (x1,y1,x2,y2)

반환:

좌표 리스트 (68x2)

landmark_face_vis(img, coords)[소스]

얼굴의 랜드마크를 표시합니다.

example:

img = camera.read()
items = face.detect_face(img)
coords = face.landmark_face(img, items[0])
face.landmark_face_vis(img, coords)
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • coords (array) – landmark_face 가 돌려준 좌표 리스트

analyze_face(img, item)[소스]

얼굴의 나이, 성별, 감정을 추정합니다.

example:

img = camera.read()
items = face.detect_face(img)
item = items[0] # item은 items 중 하나
face.analyze_face(img, item)
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (numpy.ndarray) – 얼굴의 좌표 (x1, y1, x2, y2)

반환:

{age: 0~100, gender: Male 또는 Female, emotions: neutral, happy, sad, surprise, anger, box:좌표}

analyze_face_vis(img, item)[소스]

얼굴의 나이, 성별, 감정을 표시합니다.

매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (numpy.ndarray) – 얼굴 분석 결과

mask_face(img, item)[소스]

마스크를 썼는지 판별합니다. edge-lab(PC)과 같은 모델·같은 계산입니다.

example:

img = camera.read()
items = face.detect_face(img)
face.mask_face(img, items[0])
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (numpy.ndarray) – 얼굴의 좌표 (x1, y1, x2, y2)

반환:

{"mask": True/False, "score": 0~100 (고른 쪽 확률 %), "box": 좌표}

init_db()[소스]

얼굴 데이터베이스를 초기화합니다.

초기화된 데이터베이스는 빈 이중 list [[], []] 입니다.

example:

face.init_db()
train_face(img, item, name)[소스]

얼굴을 학습하여 얼굴 데이터베이스에 저장합니다.

example:

img = camera.read()
items = face.detect_face(img)
item = items[0] # item는 items중 하나
face.train_face(img, item, 'honggildong')
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (numpy.ndarray) – 디텍팅한 얼굴의 사각형 좌측상단, 우측하단 포인트 (x1, y1, x2, y2)

  • name (str) – 디텍팅한 얼굴에 붙일 이름

delete_face(name)[소스]

등록된 얼굴을 삭제합니다.

example:

face.delete_face('honggildong')
매개변수:

name (str) – 삭제할 얼굴의 이름

반환:

True / False

recognize(img, item)[소스]

등록된 얼굴을 인식합니다.

example:

img = camera.read()
items = face.detect_face(img)
item = items[0] # item는 items중 하나
face.recognize(img, item)
매개변수:
  • img (numpy.ndarray) – 이미지 객체

  • item (numpy.ndarray) – 얼굴의 좌표 (x1, y1, x2, y2)

반환:

{"name": 이름, "score": 오차도, "max": 가장 가까운 이름}

얼굴이 비슷할수록 오차도가 낮게 측정됩니다.

오차도가 face.threshold (기본 0.4) 보다 낮을 때 동일인으로 판정합니다.

get_db()[소스]

사용 중인 얼굴 데이터베이스를 확인합니다.

example:

face.get_db()
반환:

facedb (list(list, list) 타입)

example:

[
  ['honggildong'],
  [array([ 0.0412, -0.0731,  0.1093, ..., -0.0158], dtype=float32)]   # 숫자 256개
]

save_db(filename)[소스]

얼굴 데이터베이스를 파일로 저장합니다(JSON).

example:

face.save_db('/home/pi/facedb')
매개변수:

filename (str) – 저장할 얼굴 데이터베이스 파일의 경로입니다.

load_db(filename)[소스]

얼굴 데이터베이스 파일을 불러옵니다.

예전(dlib) 방식으로 저장한 파일은 열지 않습니다 — 얼굴을 다시 등록해서 저장해 주세요.

example:

face.load_db('/home/pi/facedb')
매개변수:

filename (str) – 불러 올 facedb 파일의 경로입니다.

calculate_head_orientation(keypoints)[소스]

(내부 함수) 얼굴 랜드마크 데이터를 통해 얼굴 방향 계산

get_angle_between_lines(start, point1, point2)[소스]

Calculate angle between two lines defined by three points.

detect_mesh_vis(image, items)[소스]

Draw connections between landmarks based on Mediapipe’s face mesh.

detect_mesh(image)[소스]

얼굴의 랜드마크를 인식하고, 거리, 방향을 추정합니다

매개변수:

image (numpy.ndarray) – 이미지 객체

반환:

{얼굴의 거리, 방향, 랜드마크}의 리스트 (얼굴 2개까지 인식)