vision

OpenCV 라이브러리를 활용한 영상처리, 인공지능 비전 기술을 사용합니다.

Class: vision_api() Camera Face Detect TeachableMachine

openpibo.vision.vision_api(mode, image, params={})[소스]

인공지능 비전 API를 호출합니다.

example:

from openpibo.vision import vision_api, Camera

camera = Camera()

res = vision_api('caption/caption', camera.read(), {})
매개 변수
  • mode (str) – 호출할 비전 API

  • image (str/numpy.ndarray) – 표시할 이미지 파일 경로 / 데이터(cv2)

반환

Json 타입 결과의 데이터

example:

{ 'type': 'caption', 'result': 'ok', 
  'data': {
    caption:  "사람에게 로봇을 과시하는 사람", 
    caption_en:  "a person showing off a robot to a person",
    raw:  [
      "a person showing off a robot to a person",
      "a robot that is sitting on top of a table",
      "a very cute white robot that is sitting in front of a table"
    ]
  }
}

class openpibo.vision.Camera(cam=0, width=None, height=None)[소스]

Bases: object

Functions: imread() read() imshow_to_ide() resize() rotate() imwrite() rectangle() circle() line() putText() stylization() detailEnhance() pencilSketch() flip()

파이보의 카메라를 제어합니다.

  • 사진 촬영, 읽기, 쓰기 등 카메라 기본 기능을 사용할 수 있습니다.

  • 이미지에 도형/글자를 추가할 수 있습니다.

  • 이미지를 변환할 수 있습니다.

example:

from openpibo.vision import Camera

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

이미지 파일을 읽습니다.

example:

camera.imread('/home/pi/openpibo-files/data/image/clear.png')
매개 변수

filename (str) – 사용할 이미지 파일

반환

numpy.ndarray 타입 이미지 객체

example:

array([[[0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0]],

      [[0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0]],

      ...,

      [[0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0]]], dtype=uint8)

read()[소스]

카메라를 통해 이미지를 촬영합니다.

해상도 변경 시 이미지가 깨질 수 있으므로, 기본 해상도를 권장합니다.

example:

camera.read()
반환

numpy.ndarray 타입 이미지 객체

imshow_to_ide(img, ratio=0.25)[소스]

이미지 파일을 Web IDE에 출력합니다.

example:

img = camera.read()
camera.imshow_to_ide(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • ratio (float) – 이미지 사이즈 변환 비율 (다수 동시 사용시, 네트워크 부하)

resize(img, w, h)[소스]

Opencv 이미지의 크기를 변환합니다.

example:

img = camera.read()
camera.resize(img, 128, 64)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • w (int) – 변환될 이미지의 가로 크기입니다. (픽셀 단위)

  • h (int) – 변환될 이미지의 세로 크기입니다. (픽셀 단위)

반환

크기 변환 후의 이미지 객체

rotate(img, degree=10, ratio=0.9)[소스]

이미지를 회전시킵니다.

example:

img = camera.read()
camera.rotate(img, 10, 0.9)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • degree (int) – 회전할 각도

  • ratio (float) – 축소 또는 확대할 비율

반환

회전한 numpy.ndarray 이미지 객체

imwrite(filename, img)[소스]

이미지를 파일로 저장합니다.

example:

img = camera.read()
camera.imwrite('/home/pi/image.jpg', img)
매개 변수
  • filename (str) –

    저장할 파일 경로

    확장자는 jpg 또는 png를 사용할 수 있습니다.

  • img (numpy.ndarray) – 저장할 이미지 객체

rectangle(img, p1, p2, colors=(255, 255, 255), tickness=1)[소스]

이미지에 직사각형을 그립니다.

example:

img = camera.read()
camera.rectangle(img, (10, 10), (300, 200), (255, 255, 255), 1)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • p1 (tuple(int, int)) – 좌측상단 좌표 (x, y)

  • p2 (tuple(int, int)) – 우측하단 좌표 (x, y)

  • colors (tuple(int, int, int)) – RGB 값 (r, g, b) or 16진수 값 ‘#ffffff’

  • tickness (int) – 사각형 모서리의 두께 (픽셀 단위)

circle(img, p, r, colors=(255, 255, 255), tickness=1)[소스]

이미지에 직사각형을 그립니다.

example:

img = camera.read()
camera.circle(img, (10, 10), (255, 255, 255), 1)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • p (tuple(int, int)) – 좌측상단 좌표 (x, y)

  • r (int) – 반지름

  • colors (tuple(int, int, int)) – RGB 값 (r, g, b) or 16진수 값 ‘#ffffff’

  • tickness (int) – 사각형 모서리의 두께 (픽셀 단위)

line(img, p1, p2, colors=(255, 255, 255), tickness=1)[소스]

이미지에 직선을 그립니다.

example:

img = camera.read()
camera.line(img, (10, 10), (300, 200), (255, 255, 255), 1)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • p1 (tuple(int, int)) – 시작 좌표 (x, y)

  • p2 (tuple(int, int)) – 끝 좌표 (x, y)

  • colors (tuple(int, int, int)) – RGB 값 (r, g, b) or 16진수 값 ‘#ffffff’

  • tickness (int) – 선의 두께 (픽셀 단위)

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

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

example:

img = camera.read()
new_img = camera.putTextPIL(img, '안녕하세요.', (15, 10), 30, (255, 255, 255))
매개 변수
  • img (numpy.ndarray) – 이미지 객체

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

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

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

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

putText(img, text, points, size=1, colors=(255, 255, 255), tickness=1)[소스]

이미지에 문자를 입력합니다. (영어만 가능)

example:

img = camera.read()
new_img = camera.putText(img, 'hello', (15, 10), 10, (255, 255, 255), 1)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

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

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

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

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

  • tickness (int) – 글자 두께

stylization(img, sigma_s=100, sigma_r=0.5)[소스]

만화 이미지로 변환합니다. (opencv api) low speed

example:

img = camera.read()
camera.stylization(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • sigma_s (float) – 이미지의 blur 보존 정도 (1-200)

  • sigma_r (float) – 이미지의 Edge 적용 정도 (0-1)

반환

변환 후의 이미지 객체

detailEnhance(img, sigma_s=100, sigma_r=0.05)[소스]

만화 이미지로 변환합니다. (opencv api)

example:

img = camera.read()
camera.stylization(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • sigma_s (float) – 이미지의 blur 보존 정도 (1-200)

  • sigma_r (float) – 이미지의 Edge 적용 정도 (0-1)

반환

변환 후의 이미지 객체

pencilSketch(img, sigma_s=100, sigma_r=0.2, shade_factor=0.018)[소스]

스케치 이미지로 변환합니다.

example:

img = camera.read()
camera.sketchize(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • sigma_s (float) – 이미지의 blur 보존 정도 (1-200)

  • sigma_r (float) – 이미지의 Edge 적용 정도 (0-1)

  • shade_factor (float) – 이미지의 밝기 정도 (0-0.1)

반환

변환 후의 이미지 객체(grayscale), 변환 후의 이미지 객체(bgr)

edgePreservingFilter(img, flags=1, sigma_s=60, sigma_r=0.4)[소스]

흐림 이미지로 변환합니다.

example:

img = camera.read()
camera.edgePreservingFilter(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • flags (int) – 필터 종류 1 (RECURS_FILTER) or 2 (NORMCONV_FILTER)

  • sigma_s (float) – 이미지의 blur 보존 정도 (1-200)

  • sigma_r (float) – 이미지의 Edge 적용 정도 (0-1)

반환

변환 후의 이미지 객체(grayscale), 변환 후의 이미지 객체(bgr)

flip(img, flags=1)[소스]

상하/좌우 대칭 이미지로 변환합니다

example:

img = camera.read()
camera.flip(img, 1)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • flags (int) – 0: 상하 대칭, 1: 좌우 대칭, -1: 상하/좌우 대칭

반환

변환 후, 이미지 객체

class openpibo.vision.Face[소스]

Bases: object

Functions: detect() get_ageGender() get_age() get_gender() init_db() train_face() delete_face() recognize() get_db() save_db() load_db()

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

  • 얼굴을 탐색합니다.

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

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

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

얼굴 데이터베이스

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

얼굴 데이터베이스의 포맷은 이중 list [[], []] 이며, 첫 번째 list에는 얼굴의 이름이, 두 번째 list에는 학습된 얼굴 데이터가 인코딩되어 들어갑니다.

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

example:

from openpibo.vision import Face

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

얼굴을 탐색합니다.

example:

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

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

반환

인식된 얼굴들의 (x, y, w, h) 배열 입니다.

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

example:

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

landmark_face(img)[소스]

얼굴의 랜드마크를 탐색합니다.

example:

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

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

반환

{"data": 인식한 결과, "img": landmark를 반영한 이미지 }

get_ageGender(img, item)[소스]

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

example:

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

  • item (numpy.ndarray) – 얼굴의 좌표 (x, y, w, h)

반환

{"age": 나이, "gender": 성별}

  • age: 나이의 범위를 tuple() 형태로 출력한다.

    ex) (15, 20) # 15살에서 20살 정도

  • gender: male / female

참고: https://github.com/kairess/age_gender_estimation

get_age(img, item)[소스]

얼굴의 나이를 추정합니다.

example:

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

  • item (numpy.ndarray) – 얼굴의 좌표 (x, y, w, h)

반환

나이 범위 Raw데이터

  • age: 나이의 범위를 tuple() 형태로 출력한다.

    ex) (15, 20) # 15살에서 20살 정도

참고: https://github.com/kairess/age_gender_estimation

get_gender(img, item)[소스]

얼굴의 성별을 추정합니다.

example:

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

  • item (numpy.ndarray) – 얼굴의 좌표 (x, y, w, h)

반환

성별 Raw데이터

  • gender: male / female

참고: https://github.com/kairess/age_gender_estimation

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) – 얼굴의 좌표 (x, y, w, h)

반환

{"name": 이름, "score": 오차도}

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

오차도가 0.4 이하일 때 동일인으로 판정합니다.

get_db()[소스]

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

example:

face.get_db()
반환

facedb (list(list, list) 타입)

example:

[
  ['honggildong'],
  [array([-0.06423206,  0.12474005,  0.0511112 , -0.05676335, -0.07211345,
          -0.03123881, -0.04119622, -0.12800875,  0.11717855, -0.11079554,
           0.22952782, -0.02007426, -0.17457265, -0.13562854, -0.04972655,
           0.15810637, -0.12785575, -0.16479518, -0.07002968, -0.00208595,
           0.169218  ,  0.03144928, -0.01074579,  0.04103286, -0.09245337,
          ...
          -0.00706697,  0.06025593, -0.0049719 ])]
]

save_db(filename)[소스]

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

example:

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

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

load_db(filename)[소스]

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

example:

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

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

class openpibo.vision.Detect[소스]

Bases: object

Functions: detect_object() detect_qr() detect_pose() analyze_pose() classify_image() object_tracker_init() track_object() detect_marker()

인식과 관련된 다양한 기능을 사용할 수 있는 클래스입니다.

  • 90개 class 안에서의 객체 인식 (MobileNet V2)

  • QR/바코드 인식 (pyzbar)

  • Pose 인식

  • 이미지 분류

example:

from openpibo.vision import Detect

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

이미지 안의 객체를 인식합니다. (아래 class의 사물 인식 가능)

인식 가능한 사물은 다음과 같습니다:

'background', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 
'None', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'None',
'backpack', 'umbrella', 'None', 'None', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',
'skateboard', 'surfboard', 'tennis racket', 'bottle', 'None', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 
'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 
'potted plant', 'bed', 'None', 'dining table', 'None', 'None', 'toilet', 'None', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
'toaster', 'sink', 'refrigerator', 'None', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier' 

example:

img = camera.read()
detect.detect_object(img)
매개 변수

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

반환

{"name":이름, "score":정확도, "position":사물좌표(startX, startY, endX, endY)}

  • score는 0~100 사이의 float 값 입니다.

detect_qr(img)[소스]

이미지 안의 QR코드 및 바코드를 인식합니다.

example:

img = camera.read()
detect.detect_qr(img)
매개 변수

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

반환

{"data": 내용, "type": 바코드 / QR코드, "position":(startX,startY,endX,endY)}

detect_pose(img)[소스]

이미지 안의 Pose를 인식합니다.

example:

img = camera.read()
detect.detect_pose(img)
매개 변수

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

반환

{"data": 인식한 결과, "img": Pose를 반영한 이미지 }

analyze_pose(data)[소스]

detect_pose 함수의 결과 값을 분석합니다.

example:

img = camera.read()
result = detect.detect_pose(img)
detect.analyze_pose(result)
매개 변수

data (dict) – 이미지 객체

반환

인식한 포즈 리스트 ['left_hand_up', 'right_hand_up', 'clap']

classify_image(img, k=5)[소스]

이미지를 분류합니다.

example:

img = camera.read()
detect.classify_image(img)
매개 변수
  • img (numpy.ndarray) – 이미지 객체

  • k (int) – 가져올 결과 항목 개수

반환

top_k 리스트 [{"score":정확도, "name":이름}, ...]

object_tracker_init(img, p)[소스]

이미지 안의 사물 트래커를 설정합니다.

example:

img = camera.read()
detect.object_tracker_init(img)
매개 변수

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

track_object(tracker, img)[소스]

이미지 안의 사물 트래커를 설정합니다.

example:

img = camera.read()
tracker = detect.object_tracker_init(img, (10,10,100,100))
tracker, position = detect.track_object(tracker, img)
매개 변수

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

반환

{"tracker": 업데이트된 tracker, "position": 업데이트된 사물 위치 }

detect_marker(img, marker_length=2)[소스]

이미지 안의 마커를 인식합니다. # cv2.aruco.DICT_4X4_50

example:

img = camera.read()
result = detect.detect_marker(img)
매개 변수

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

반환

[{"id": 마커번호, "center":  }, ...]

class openpibo.vision.TeachableMachine[소스]

Bases: object

Functions: load() predict()

파이보의 카메라 Teachable Machine 기능을 사용합니다.

  • 이미지 프로젝트표준 이미지 모델 을 사용합니다.

  • Teachable Machine 에서 학습한 모델을 적용하여 추론할 수 있습니다.

  • 학습한 모델은 Tensorflow Lite 형태로 다운로드 해주세요.

example:

from openpibo.vision import TeachableMachine

tm = TeachableMachine()
# 아래의 모든 예제 이전에 위 코드를 먼저 사용합니다.
load(model_path, label_path)[소스]

(내부 함수) Tflite 모델로 불러옵니다. (부동소수점/양자화) 모두 가능

example:

tm.load_tflite('model_unquant.tflite', 'labels.txt')
매개 변수
  • model_path (str) – Teachable Machine의 모델파일

  • label_path (str) – Teachable Machine의 라벨파일

predict(img)[소스]

(내부 함수) Tflite 모델로 추론합니다.

example:

cm = Camera()
img = cm.read()
tm.predict(img)
매개 변수

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

반환

가장 높은 확률을 가진 클래스 명, 결과(raw 데이터)