새소식

💫 AI (인공지능)/LSTM

[수어쉬워] 수어 모션 데이터 수집

  • -

해당 포스팅은 수어 모션 인식 모델을 위한 데이터 수집 포스팅입니다.

[수어쉬워] 수어 교육 및 번역 플랫폼

 

30초 동안 랜드마크된 손동작 모션을 학습을 위한 데이터로 저장해줍니다.


🌳 1. 데이터

전체코드보기

더보기
import cv2
import mediapipe as mp
import numpy as np
import time, os

actions = ['여러분', '안녕하세요' ,'발표', '시작', '어때_의문문', '오늘', '하루', '보내다']
seq_length = 30
secs_for_action = 30

# MediaPipe hands model
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands(
    max_num_hands=2,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5)

cap = cv2.VideoCapture(0)

created_time = int(time.time())
os.makedirs('dataset', exist_ok=True)

while cap.isOpened():
    for idx, action in enumerate(actions):
        data = []

        ret, img = cap.read()

        img = cv2.flip(img, 1)

        cv2.putText(img, f'Waiting for collecting {action.upper()} action...', org=(10, 30), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=(255, 255, 255), thickness=2)
        cv2.imshow('img', img)
        cv2.waitKey(3000)

        start_time = time.time()

        while time.time() - start_time < secs_for_action:
            ret, img = cap.read()

            img = cv2.flip(img, 1)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            result = hands.process(img)
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

            if result.multi_hand_landmarks is not None:
                for res in result.multi_hand_landmarks:
                    joint = np.zeros((21, 4))
                    for j, lm in enumerate(res.landmark):
                        joint[j] = [lm.x, lm.y, lm.z, lm.visibility]

                    # Compute angles between joints
                    v1 = joint[[0,1,2,3,0,5,6,7,0,9,10,11,0,13,14,15,0,17,18,19], :3] # Parent joint
                    v2 = joint[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], :3] # Child joint
                    v = v2 - v1 # [20, 3]
                    # Normalize v
                    v = v / np.linalg.norm(v, axis=1)[:, np.newaxis]

                    # Get angle using arcos of dot product
                    angle = np.arccos(np.einsum('nt,nt->n',
                        v[[0,1,2,4,5,6,8,9,10,12,13,14,16,17,18],:], 
                        v[[1,2,3,5,6,7,9,10,11,13,14,15,17,18,19],:])) # [15,]

                    angle = np.degrees(angle) # Convert radian to degree

                    angle_label = np.array([angle], dtype=np.float32)
                    angle_label = np.append(angle_label, idx)

                    d = np.concatenate([joint.flatten(), angle_label])

                    data.append(d)

                    mp_drawing.draw_landmarks(img, res, mp_hands.HAND_CONNECTIONS)

            cv2.imshow('img', img)
            if cv2.waitKey(1) == ord('q'):
                break

        data = np.array(data)
        print(action, data.shape)
        np.save(os.path.join('dataset', f'raw_{action}_{created_time}'), data)

        # Create sequence data
        full_seq_data = []
        for seq in range(len(data) - seq_length):
            full_seq_data.append(data[seq:seq + seq_length])

        full_seq_data = np.array(full_seq_data)
        print(action, full_seq_data.shape)
        np.save(os.path.join('dataset', f'seq_{action}_{created_time}'), full_seq_data)
    break

 

- 저장한 모션

actions = ['여러분', '안녕하세요' ,'발표', '시작', '어때_의문문', '오늘', '하루', '보내다']
seq_length = 30
secs_for_action = 30

저는 총 8가지의 모션을 30초동안 데이터로 저장하였습니다.

 

- 설정

# MediaPipe hands model
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands(
    max_num_hands=2,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5)

cap = cv2.VideoCapture(0)

저는 양손을 위하여 max_num_hands=2 를 하였고,

 

외부 캠이 아닌, 노트북 내장 캠이기에

cv2.VideoCapture(0) 을 두었습니다.

 

 

- 빠져나가기

if cv2.waitKey(1) == ord('q'):
    break

q key를 눌러 다음 모션으로 나가거나, 30초 후에 자동으로 다음 모션에 대한 데이터 저장이 이루어집니다.


🌳 2. 데이터 저장 후

dataset이라는 폴더 안에 raw데이터와, seq 데이터가 각각 저장됩니다.


해당 포스팅은 유튜버 빵형의 개발도상국 채널을 보고 적용하고 쓴 글입니다.

https://www.youtube.com/watch?v=eHxDWhtbRCk&t=287s 

 

'💫 AI (인공지능) > LSTM' 카테고리의 다른 글

[수어쉬워] LSTM 학습  (0) 2022.07.27
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.