"""
사물·QR코드·포즈·손동작·마커를 인식합니다.
Class:
:meth:`~openpibo.vision_detect.putTextPIL`
:obj:`~openpibo.vision_detect.Detect`
"""
import cv2
import os,math
import numpy as np
from pyzbar import pyzbar
from .modules.ed_onnx import EdOnnx
from .modules.pose.movenet import Movenet
from .modules.pose.utils import visualize_pose
from .modules.card.decode_card import get_card
from PIL import Image,ImageDraw,ImageFont
import openpibo_models
import logging
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # MediaPipe(손동작) 안의 TFLite C++ 로그 줄이기 — TensorFlow 는 쓰지 않는다
os.environ['LIBCAMERA_LOG_LEVELS'] = '3'
logging.getLogger("tensorflow").setLevel(logging.ERROR) # 같은 이름의 파이썬 로거가 있으면 조용히(없으면 하는 일 없음)
# 기본 사물 인식 모델 (easydetect ed-s 320, COCO 80종 — 이름·conf 가 파일 안에 있다). 261026, easydetect-lab 지시서.
# 다른 기본 모델을 쓰려면 이 한 줄만 바꾼다. lab 에서 받은 모델(job<번호>.onnx)은 load_object_model(파일) 로 고른다
OBJECT_MODEL = '/home/pi/.model/object/ed-s-320.onnx'
[docs]
def putTextPIL(img, text, points, size=30, colors=(255,255,255)):
"""
이미지에 문자를 입력합니다. (한/영 가능 - pillow 이용)- COPY
:param numpy.ndarray img: 이미지 객체
:param str text: 표시할 문자열
:param tuple(int, int) points: 텍스트 블록 좌측상단 좌표 (x, y)
:param int size: 표시할 글자의 크기
:param tuple(int, int, int) colors: 글자 색깔 BGR 값 (b, g, r) or 16진수 값 '#rrggbb'
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
if type(points) is not tuple:
raise Exception(f'"{points}" must be tuple type')
if len(points) != 2:
raise Exception(f'len({points}) must be 2')
if type(colors) is str:
colors = (int(colors[5:7], 16), int(colors[3:5], 16), int(colors[1:3], 16))
if type(colors) is not tuple:
raise Exception(f'"{colors}" must be tuple type')
if len(colors) != 3:
raise Exception(f'len({colors}) must be 3')
font = ImageFont.truetype(openpibo_models.filepath("KDL.ttf"), size)
pil = Image.fromarray(img) # CV to PIL
ImageDraw.Draw(pil).text(points, text, font=font, fill=colors) # putText
img[:] = np.array(pil) # PIL to CV
return img
[docs]
class Detect:
"""
Functions:
:meth:`~openpibo.vision_detect.Detect.load_object_model`
:meth:`~openpibo.vision_detect.Detect.detect_object`
:meth:`~openpibo.vision_detect.Detect.detect_object_vis`
:meth:`~openpibo.vision_detect.Detect.detect_qr`
:meth:`~openpibo.vision_detect.Detect.detect_qr_vis`
:meth:`~openpibo.vision_detect.Detect.detect_pose`
:meth:`~openpibo.vision_detect.Detect.detect_pose_vis`
:meth:`~openpibo.vision_detect.Detect.analyze_pose`
:meth:`~openpibo.vision_detect.Detect.load_hand_gesture_model`
:meth:`~openpibo.vision_detect.Detect.recognize_hand_gesture`
:meth:`~openpibo.vision_detect.Detect.recognize_hand_gesture_vis`
:meth:`~openpibo.vision_detect.Detect.detect_marker`
:meth:`~openpibo.vision_detect.Detect.detect_marker_vis`
인식과 관련된 다양한 기능을 사용할 수 있는 클래스입니다.
* 사물 인식 (easydetect ed, 기본 COCO 80개 class · lab 에서 학습한 모델, onnxruntime)
* QR/바코드 인식 (pyzbar)
* Pose 인식 (MoveNet)
* 손동작 인식 (MediaPipe)
* 마커 인식 (ArUco)
example::
from openpibo.vision_detect import Detect
detect = Detect()
# 아래의 모든 예제 이전에 위 코드를 먼저 사용합니다.
"""
def __init__(self, object_model=None):
# 사물 인식 모델은 처음 detect_object 를 부를 때 올린다 (QR·마커만 쓰면 메모리를 안 쓴다)
self.object_detector = None
self.object_model_path = object_model or OBJECT_MODEL
self.pose_detector = Movenet() # openpibo/modules/pose/movenet_lightning.onnx (onnxruntime, 261104)
# marker
self.camera_matrix = np.array([
[1.42068235e+03,0.00000000e+00,9.49208512e+02],
[0.00000000e+00,1.37416685e+03,5.39622051e+02],
[0.00000000e+00,0.00000000e+00,1.00000000e+00]])
self.distortion_coeff = np.array([1.69926613e-01,-7.40003491e-01,-7.45655262e-03,-1.79442353e-03, 2.46650225e+00])
#self.dictionary = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50)
self.dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
self.parameters = cv2.aruco.DetectorParameters()
self.hand_gesture_recognizer = None
[docs]
def load_hand_gesture_model(self, modelpath='/home/pi/.model/hand/gesture_recognizer.task'):
"""
손동작 인식 모델을 불러옵니다.
:param str modelpath: 손동작 인식 모델 경로
"""
#'/home/pi/.model/hand/gesture_recognizer.task', /home/pi/.model/hand/rps_recognizer.task'
# mediapipe 는 여기서 처음 불러온다. 파일 맨 위에서 불러오면 QR·포즈·사물 인식만 써도
# import 비용(약 50MB)이 늘 붙는다
from mediapipe.tasks import python as mp_python
from mediapipe.tasks.python import vision as mp_vision
self.hand_gesture_recognizer = mp_vision.GestureRecognizer.create_from_options(
mp_vision.GestureRecognizerOptions(
base_options=mp_python.BaseOptions(model_asset_path=modelpath),
running_mode=mp_vision.RunningMode.IMAGE,
num_hands= 2,
min_hand_detection_confidence= 0.5,
min_hand_presence_confidence= 0.5,
min_tracking_confidence= 0.5,
)
)
[docs]
def recognize_hand_gesture(self, image):
"""
손동작을 인식합니다.
:param numpy.ndarray image: 이미지 객체
:returns: 모델에 따른 손동작 인식 결과
"""
if self.hand_gesture_recognizer == None:
raise Exception('"load_hand_gesture_model" must be called')
import mediapipe as mp # load_hand_gesture_model 에서 이미 올라와 있다
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_image)
recognition_result = self.hand_gesture_recognizer.recognize(mp_image)
hands_data = [] # 손 정보를 담을 리스트
if recognition_result and recognition_result.hand_landmarks:
height, width, _ = image.shape
for hand_index, hand_landmarks in enumerate(recognition_result.hand_landmarks):
# 21개 랜드마크 픽셀 좌표 추출
hpoints = []
for landmark in hand_landmarks:
px = int(landmark.x * width)
py = int(landmark.y * height)
hpoints.append((px, py))
name = ""
score = 0
if recognition_result.gestures:
gesture = recognition_result.gestures[hand_index]
name = gesture[0].category_name
score = round(gesture[0].score, 2)
hands_data.append({"point": hpoints, "name": name, "score": score})
return hands_data
[docs]
def recognize_hand_gesture_vis(self, img, items):
"""
손동작 인식 결과를 표시합니다.
:param numpy.ndarray img: 이미지 객체
:param array items: 손동작 인식 결과
"""
for item in items:
# hands 시각화
hpoints = item["point"]
name = item["name"]
score = item["score"]
# 21개 포인트 빨간색 원으로 그리기
for px, py in hpoints:
cv2.circle(img, (px, py), 3, (255, 255, 255), -1)
# 첫 번째 랜드마크 근처에 손 라벨(Right or Left / Gesture) 표시
putTextPIL(img, f'{name}/{score}', (hpoints[0][0], hpoints[0][1] - 50), 30, (255, 0, 0))
[docs]
def load_object_model(self, modelpath=None):
"""
사물 인식 모델을 불러옵니다.
easydetect 모델 파일(``.onnx``)을 고릅니다. easydetect lab 에서 받은
``job<번호>.onnx`` 가 그대로 쓰입니다. 클래스 이름과 확신 기준은 파일 안에 들어 있고, 이름은 한글일 수 있습니다.
모델을 못 쓰면(파일이 없음, onnxruntime 1.13 미만, 읽기 실패) 이유가 담긴 오류가 납니다.
example::
detect.load_object_model('/home/pi/code/job3.onnx') # lab 에서 받은 모델
detect.load_object_model() # 기본 모델(COCO)로 돌아가기
:param str modelpath: 사물 인식 모델 파일(``.onnx``). 없으면 기본 모델
"""
# 이전 모델의 ONNX Runtime 세션을 먼저 놓는다(파이보 램 2GB — 바꿀 때마다 쌓이지 않게)
if self.object_detector is not None:
self.object_detector.close()
self.object_detector = None
# 경로를 먼저 바꾼다 — 못 열면 오류가 나고, 다음 detect_object 도 예전 모델로 몰래 돌지 않고 같은 오류를 낸다
self.object_model_path = modelpath or OBJECT_MODEL
self.object_detector = EdOnnx(self.object_model_path)
[docs]
def detect_object(self, img):
"""
이미지에서 사물을 찾습니다(모델은 ``load_object_model`` 로 바꿀 수 있습니다).
:param numpy.ndarray img: 이미지 객체
:returns: ``[{"name": 이름, "score": 점수(%), "box": (x1, y1, x2, y2)}, ...]``
"""
if not isinstance(img, np.ndarray):
raise ValueError('"img" must be a valid OpenCV image (np.ndarray).')
if self.object_detector is None:
self.object_detector = EdOnnx(self.object_model_path)
# conf 는 파일 안의 easydetect.conf(없으면 0.5), iou 는 0.7 로 EdOnnx 가 정한다 — 여기서 넘기는 값은 쓰이지 않는다
boxes, scores, classes = self.object_detector(img, conf=0.5, iou=0.4)
data = []
for (x1, y1, x2, y2), score, cls_id in zip(boxes, scores, classes):
# 점수(%)는 반올림한다 — easydetect-lab·detect.py 가 보여 주는 소수 둘째 자리(:.2f)와 같게(261026, 전엔 버림)
data.append({ "name": self.object_detector.name_of(cls_id), "score": int(round(round(float(score), 2) * 100)),
"box": (int(x1), int(y1), int(x2), int(y2)) })
return data
[docs]
def detect_object_vis(self, img, items):
"""
사물 인식 결과를 표시합니다.
:param numpy.ndarray img: 이미지 객체
:param array items: 사물 인식 결과
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
color = (0,255,0)
for item in items:
x1,y1,x2,y2 = item['box']
cv2.rectangle(img, (x1,y1), (x2,y2), color, 2)
if not items:
return
# 이름표는 상자 색 바탕 + 검은 글자(밝은 배경에서도 보이게, 261027). 상자 위에 자리가 없으면 상자 안쪽 위에 그린다.
# 글자 크기는 그림 크기를 따른다(640x480 → 24). PIL 변환은 한 번만 한다(한글은 PIL 로만 그려진다)
h, w = img.shape[:2]
font = ImageFont.truetype(openpibo_models.filepath("KDL.ttf"), max(14, round(min(h, w) / 20)))
pil = Image.fromarray(img)
draw = ImageDraw.Draw(pil)
for item in items:
x1,y1,x2,y2 = item['box']
text = f"{item['name']} {item['score']}" if 'score' in item else str(item['name'])
l, t, r, b = draw.textbbox((0, 0), text, font=font)
tw, th = r - l + 8, b - t + 6
top = y1 - th if y1 - th >= 0 else y1
left = min(max(x1, 0), max(w - tw, 0))
draw.rectangle((left, top, left + tw, top + th), fill=color)
draw.text((left + 4 - l, top + 3 - t), text, font=font, fill=(0,0,0))
img[:] = np.array(pil)
[docs]
def detect_qr(self, img):
"""
이미지 안의 QR코드 및 바코드를 인식합니다.
example::
img = camera.read()
detect.detect_qr(img)
:param numpy.ndarray img: 이미지 객체
:returns: ``{"data": 내용, "type": 바코드 / QR코드, "position":(startX,startY,endX,endY)}``
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
results = []
barcodes = pyzbar.decode(img)
for barcode in barcodes:
x,y,w,h = barcode.rect
_type = barcode.type
_data = barcode.data.decode("utf-8", errors="replace") # UTF-8 이 아닌 QR 도 멈추지 않게
res = get_card(_data)
if res != None:
_type, _data = "CARD", res
results.append({"data":_data, "type":_type, "box":(x,y,x+w,y+h)})
return results
[docs]
def detect_qr_vis(self, img, items):
"""
QR/바코드 결과를 표시합니다.
:param numpy.ndarray img: 이미지 객체
:param array items: QR 인식 결과
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
for item in items:
x1,y1,x2,y2 = item['box']
data = item['data']
cv2.rectangle(img, (x1,y1), (x2,y2), (255,50,255), 2)
putTextPIL(img, str(data), (x1, y1-30), 30, (255,50,255))
[docs]
def detect_pose(self, img):
"""
이미지 안의 Pose를 인식합니다.
example::
img = camera.read()
detect.detect_pose(img)
:param numpy.ndarray img: 이미지 객체
:returns: ``인식한 결과``
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
list_persons = [self.pose_detector.detect(img)]
return list_persons
[docs]
def detect_pose_vis(self, img, items):
"""
포즈를 표시 합니다.
:param numpy.ndarray img: 이미지 객체
:param array items: 포즈 데이터
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
visualize_pose(img, items)
[docs]
def analyze_pose(self, data):
"""
detect_pose 함수의 결과 값을 분석합니다.
example::
img = camera.read()
result = detect.detect_pose(img)
detect.analyze_pose(result)
:param dict data: 이미지 객체
:returns: ``인식한 포즈 리스트 ['left_hand_up', 'right_hand_up', 'clap']``
"""
def distance(p1, p2):
return math.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2)
NOSE, LEFT_EYE, RIGHT_EYE, LEFT_EAR, RIGHT_EAR = 0,1,2,3,4
LEFT_SHOULDER, RIGHT_SHOULDER, LEFT_ELBOW, RIGHT_ELBOW, LEFT_WRIST, RIGHT_WRIST = 5,6,7,8,9,10
LEFT_HIP, RIGHT_HIP, LEFT_KNEE, RIGHT_KNEE, LEFT_ANKLE, RIGHT_ANKLE = 11,12,13,14,15,16
res = []
data = data[0].keypoints
if data[LEFT_WRIST].coordinate.y < data[LEFT_ELBOW].coordinate.y:
res.append("left_hand_up")
if data[RIGHT_WRIST].coordinate.y < data[RIGHT_ELBOW].coordinate.y:
res.append("right_hand_up")
if distance(data[LEFT_WRIST].coordinate, data[RIGHT_WRIST].coordinate) < 75:
res.append("clap")
return res
[docs]
def detect_marker(self, img, marker_length=2):
"""
이미지 안의 마커를 인식합니다. # cv2.aruco.DICT_4X4_50
example::
img = camera.read()
result = detect.detect_marker(img)
:param numpy.ndarray img: 이미지 객체
:returns: ``[{"id": 마커번호, "center": }, ...]``
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
marker_length /= 250
corners, ids, _ = cv2.aruco.detectMarkers(img, self.dictionary, parameters=self.parameters)
res = []
if len(corners) > 0:
# img = cv2.aruco.drawDetectedMarkers(img, corners, ids)
ids = ids.flatten()
for (corner, markerID) in zip(corners, ids):
rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corner, marker_length, self.camera_matrix, self.distortion_coeff)
(topLeft, topRight, bottomRight, bottomLeft) = corner.reshape((4, 2))
topRight = (int(topRight[0]), int(topRight[1]))
topLeft = (int(topLeft[0]), int(topLeft[1]))
bottomRight = (int(bottomRight[0]), int(bottomRight[1]))
bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1]))
cX = int((topLeft[0] + bottomRight[0]) / 2.0)
cY = int((topLeft[1] + bottomRight[1]) / 2.0)
distance = round(tvec[0][0][2] * 100, 1) #[cm]
res.append({"id":markerID, "center": (cX, cY), "box": [topLeft, topRight, bottomRight, bottomLeft], "distance":distance})
return res
[docs]
def detect_marker_vis(self, img, items):
"""
마커 결과를 표시합니다.
:param numpy.ndarray img: 이미지 객체
:param array items: 마커 결과
"""
if not type(img) is np.ndarray:
raise Exception('"img" must be image data from opencv')
for item in items:
cX, cY = item['center']
topLeft, topRight, bottomRight, bottomLeft = item['box']
markerID = item['id']
distance = item['distance']
cv2.line(img, topLeft, topRight, (255, 0, 0), 4)
cv2.line(img, topRight, bottomRight, (255, 0, 0), 4)
cv2.line(img, bottomRight, bottomLeft, (255, 0, 0), 4)
cv2.line(img, bottomLeft, topLeft, (255, 0, 0), 4)
cv2.circle(img, (cX, cY), 4, (0, 0, 255), -1)
putTextPIL(img, f'{markerID}/{distance}cm', (topLeft[0], topLeft[1] - 15), 15, (0, 255, 0))