블로그 이미지
devtang
Instagram : @taebr0 devtaehyeong@gmail.com

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2020. 4. 29. 18:06 Raspberry Pi

 

 

 

 

 

 

 

이번 게시물에서는 RaspberryPi 3B+에 Tensorflow 를 이용하여 사전 훈련된 Mobilenet SSDLite_V2를 이용하여 파이카메라로 Object Detection하는 과정을 작성하겠습니다.

 

우선 준비물로는 Picamera와 라즈베리파이만 있으면 됩니다.

 

라즈베리파이 터미널창을 열고 다음과같이 업데이트를 해줍니다.

sudo apt-get update
sudo apt-get upgrade

 

이후 tensorflow 모델을 다운 받을 폴더를 만들어줍니다.

cd Desktop
mkdir tensorflow
cd tensorflow

 저는 Desktop 에 tensorflow1이라고 폴더명을 만들고 터미널로 들어가줬습니다.

wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_armv7l.whl

 

이제 위와 같은 명령어를 치고 다운받아줍니다. 

 

다운이 완료되면 models라는 폴더가 생성되있습니다.

 

sudo pip3 install tensorflow-1.8.0-cp35-none-linux_armv7l.whl // python3.x버전설치
sudo pip install tensorflow-1.8.0-cp35-none-linux_armv7l.whl

저는 라즈베리파이에 세팅된 기본 파이썬버전이 3.5 라 pip3를 붙혀줄 필요가 없었습니다.

pip3버전으로 까는것을 추천드립니다.

 

텐서플로우가 설치가 완료되고나면, 텐서플로우에 필요한 패키지를 추가로 설치해줘야합니다.

이제부터 pip은 생략하고 pip3로 통일해서 올리겠습니다. 본인 환경에 맞게 설치하시길 바랍니다.

 

sudo apt-get install libatlas-base-dev

sudo pip3 install pillow lxml jupyter matplotlib cython

sudo apt-get install python-tk

추가적으로 OpenCV도 설치해줘야하는데 Jetson nano가 라즈베리와같이 우분투 환경이기에 똑같이 진행해주시면 됩니다.

 

(아래 게시물 참고바랍니다.)

https://ultrakid.tistory.com/10

 

[OpenCV] Jetson nano에 OpenCV 3.4 설치

제 나노 보드에 설치된 Jetson Nano Developer Kit image, CUDA 10.0, Jetpack 4.3 버전 기준으로 작성하였습니다. 우선 OpenCV 설치 전에 필요한 라이브러리 들을 설치해줍니다. (참고) - pkg-config나 unzip 또..

ultrakid.tistory.com

sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev

sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev

sudo apt-get install libxvidcore-dev libx264-dev

sudo apt-get install qt4-dev-tools

pip3 install opencv-python

OpenCV 설치시에 굉장히 오래걸리기도 하고, 발열이 심하니 설치후에 꼭 라즈베리파이를 쉬게 해주세요..

 

이제 구글의 프로토콜 버퍼를 이용할 준비를 해야합니다.

https://developers.google.com/protocol-buffers

 

Protocol Buffers  |  Google Developers

Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.

developers.google.com

이것을 이용하면 데이터를 한 번 구성하는 방법을 정의한 후 특수 생성 된 소스 코드를 사용하여 다양한 데이터 스트림에서 다양한 언어로 다양한 구조의 데이터를 쉽게 읽고 쓸 수 있다고 합니다. .proto파일을 생성하여  응용 프로그램 언어에 대한 프로토콜 버퍼 컴파일러를 실행하여 데이터 액세스 클래스를 생성한다고 하는데, 이것을 이용하면 더 작고 빠르게 읽을 수 있어서 라고 합니다.

 

명령어를 입력해줍니다. 

sudo apt-get install autoconf automake libtool curl

이 다운로드는 참고로 만들어준 tensorflow 폴더에서 진행해주세요.

wget https://github.com/protocolbuffers/protobuf.git // protocol buffer 받아오기

tar -zxvf protobuf-all-3.6.0.tar.gz // 압축풀어주기

cd protobuf-3.6.0 // 폴더로 진입

 

 

./configure

./configure를 해주면 대략 2분정도걸립니다.

 

make

make는 진짜 더더 오래걸립니다.. 저는 한시간정도 걸린 것 같습니다.

make check

이건 리얼 더더더 오래걸렸던거 같습니다. 참고로 하다가 라즈베리파이가 먹통됬는데, 먹통된 사람들은 전원을 끄고 

다시 켜준다음에 다시 make check 진행해주시면 위와같은 화면이 나오면 올바르게 컴파일 된겁니다.

저는 먹통이되서 다시 켜고 컴파일시켜 2시간 넘게 걸렸습니다.

sudo make install

위와같은 명령어를 쳐서 설치합니다.

cd python  // @@@@ python 폴더로 꼭 들어가주세요 @@@@

export LD_LIBRARY_PATH=../src/.libs

python3 setup.py build --cpp_implementation

python3 setup.py test --cpp_implementation

python3 setup.py build --cpp_implementation

 

python3 setup.py test --cpp_implementation

sudo python3 setup.py install --cpp_implementation

계속계속 진행해 줘요.

 

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION=3

sudo ldconfig

sudo ldconfig 치면 위와 같이 나옵니다.

이제 설치가 거의 완료됬습니다. 재부팅 전에 실행하면 텐서플로우 오류가 뜨니 반드시 재부팅을 해줍니다.

sudo reboot now

 

재부팅이 완료가 되면 Desktop에다 tensorflow1 이라고 폴더를 만들어주어 그안에 들어가줍니다.

cd Desktop

mkdir tensorflow1

cd tensorflow1

아래 명령어를 입력해주면 위와 같은 이미지처럼 다운로드가 진행됩니다~!!

git clone --recurse-submodules https://github.com/tensorflow/models.git 

설치가 완료되면 

이다음부터 조금 중요한데,

sudo nano ~/.bashrc

위의 명령어를 입력해주면

아래와 같은 GNU 창이 뜹니다. 커서를 맨아래로옮겨 아래 코드를 적고 Ctrl + X -> Y 를 눌러 저장하고 나옵니다.

export PYTHONPATH=$PYTHONPATH:/home/pi/tensorflow1/models/research:/home/pi/tensorflow1/models/research/slim

echo $PYTHONPATH 를치면

위와같이 우리가 입력한 주소가 나옵니다. 위와 같이 나오면 성공적으로 진행된것입니다.

 

https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

 

tensorflow/models

Models and examples built with TensorFlow. Contribute to tensorflow/models development by creating an account on GitHub.

github.com

이제 실행을위해 pre-trained 된 모델을 다운 받아옵니다. 저는 Mobilenet ssdlite V2 버전을 이용하겠습니다.

wget http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz

 

다운로드가 완료되면 아래 명령어를 입력하여 압축을 풀어줍니다.

tar -xzvf ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz

다시 models파일안에 research 폴더안으로 들어와서 명령어를 입력해줘야 합니다.

protoc object_detection/protos/*.proto --python_out=.

이명령어를 입력한후 폴더안에 파일을보시면 파이썬 파일들이 proto파일들로 변환되서 저장되어있습니다. 구글 프로토콜 버퍼를 사용할 준비가 완벽하게 됬습니다!

 

 

이제 object_detection 폴더 안으로 들어와서 테스트할 파이썬 파일을 받아옵니다.

라즈베리카메라를 이용한 객체인식 예제 코드 파일입니다.

wget https://raw.githubusercontent.com/EdjeElectronics/TensorFlow-Object-Detection-on-the-Raspberry-Pi/master/Object_detection_picamera.py

python3 Object_detection_picamera.py

받아와서 python으로 실행을 시키면 tensorflow가 꽤 많이 메모리를 잡아먹기 때문에 시간이 조금 걸립니다.

 

아래는 구현 동영상입니다.

https://youtu.be/rLK-y8ePueQ

 

 

참고사이트

https://youtu.be/npZ-8Nj1YwY

 

=======================================================================

posted by devtang
2020. 3. 10. 14:41 개인 프로젝트

개인 프로젝트를 위해 저에게 필요한 단방향 소켓 통신방식을 만들어 봤습니다.

 

 

기본적인 세팅 구조

 

우선 라즈베리파이에 data.txt라는 텍스트 파일에 Random한 시간과 내용을 실시간으로 적게 되면,

윈도우에서 실시간으로 받은 문장을 server.txt라고 만든 텍스트 파일에 실시간으로 적어주는 방식입니다.

저번 출입알림시스템 때 이용해봤지만 리눅스-리눅스 환경의 소켓 통신이라 이번에는 서버코드를 약간 수정했습니다.

 

data.txt 파일에 ABCD를 적어서 저장하는 순간 윈도우내 지정된 server.txt 파일에 문자가 저장됩니다.

소켓으로 실시간 메모장을 열고 확인해야 하기 때문에 조금 비효율적이지만 

제가 배운 선에서 최대한 저한테 이용하기 편리하게 만들어놨습니다.

 

Windows 10 에서 구동한 소스 코드입니다. (Server)

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma comment(lib,"ws2_32.lib")
#include <WinSock2.h>
#include <windows.h>


#define  BUF_SIZE   1024
void ErrorHandling(char *message);
int main(int argc, char *argv[])

{
   FILE *fp;
   WSADATA wsaData;
   SOCKET hServSock, hClntSock;
   SOCKADDR_IN servAddr, clntAddr;
   char message[BUF_SIZE];
   char write_memo[BUF_SIZE] = { 0, };
   int str_len, j;
   int szClntAddr;

   if (argc != 2)
   {
      printf("Usage:%s <port>\n", argv[0]);
      exit(1);
   }



   if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) //소켓 라이브러리 초기화
      ErrorHandling("WSAStartup() error!");

   hServSock = socket(PF_INET, SOCK_STREAM, 0); //소켓생성

   if (hServSock == INVALID_SOCKET)
      ErrorHandling("socket() error");

   memset(&servAddr, 0, sizeof(servAddr));
   servAddr.sin_family = AF_INET;
   servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   servAddr.sin_port = htons(atoi(argv[1]));

   if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) //IP주소와 PORT 번호 할당
      ErrorHandling("bind() error");

   if (listen(hServSock, 5) == SOCKET_ERROR) //listen 소켓을 서버 소켓으로 완성
      ErrorHandling("listen() error");


   szClntAddr = sizeof(clntAddr);
   hClntSock = accept(hServSock, (SOCKADDR*)&clntAddr, &szClntAddr); // accept함수 호출
   if (hClntSock == INVALID_SOCKET)
      ErrorHandling("accept() error");

   while (1)
   {
      str_len=recv(hClntSock, message, sizeof(message)-1, 0); //클라이언트 메세지를 받음
      if (strcmp(write_memo, message) == 0) // *참고
         continue;
      else {
         fp = fopen("C:\\**TXT파일의위치**", "w"); //fopen함수 이용하여 메모장 쓰기모드로 열기
         fwrite(message, strlen(message), 1, fp); // 받은 메세지를 메모장에 쓰기
         fclose(fp); // 메모장을 닫는다.
         strcpy(write_memo, message); // *받은 메세지를 write_memo 변수에 복사해놓음(계속 쓰는것을 방지)
         printf("Message from Client : %s", message); //받은 메세지를 표시
      }
      for (j = 0; j < 100; j++) {
         message[j] = 0; //100글자까지 초기화
      }
         
   }
   closesocket(hClntSock);
   closesocket(hServSock);
   WSACleanup();
   return 0;
}

void ErrorHandling(char *message)
{
   fputs(message, stderr);
   fputc('\n', stderr);
   exit(1);
}

받은 message를 write_memo 라는 변수를 만들어서 복사해준 이유는 

라즈베리파이에서 예를들어 'ABCD'를 입력하면 한번만 보내는것이 아니라 무한적으로 ABCD를 계속 보내게 됩니다.

따라서 write_memo에 전에받았던 'ABCD'를 저장해놓으면 다음 while 루프때 문자가 바뀌지않으면

다음 문장을 입력받기 전까지 대기하게 할 수 있어서 만들어놨습니다.

 

아래는 RaspberryPi에서 구동한 소스 코드입니다.(Client)

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#define  BUF_SIZE   1024
void error_handling(char *message);

int main( int argc, char *argv[])
{
   char send_socket[BUF_SIZE]= {0,};
   int sock;
   char message[BUF_SIZE];
   struct sockaddr_in serv_adr;
   FILE *fp;
   if(argc != 3) {
      printf("Usage : %s <IP> <PORT>\n", argv[0]);
      exit(1);
   }
   
   sock= socket( PF_INET, SOCK_STREAM, 0);
   if( -1 ==sock)
      error_handling("socket() error");

   memset( &serv_adr, 0, sizeof( serv_adr));
   serv_adr.sin_family     = AF_INET;
   serv_adr.sin_addr.s_addr= inet_addr(argv[1]);
   serv_adr.sin_port       = htons(atoi(argv[2]));
  

   if( -1 == connect(sock, (struct sockaddr*)&serv_adr, sizeof( serv_adr) ) )
   {
      printf( "접속 실패\n");
      exit( 1);
   }
   
   
   while(1){
   
      fp = fopen("**TXT파일 위치**","r"); // 읽기 모드로 TXT파일을 열기
      fscanf(fp, "%s",message); // TXT파일내 문장을 읽기
      //printf("MES : %s",message);
      fclose(fp);
      if(strcmp(message,send_socket)==0)
      {
    	continue;
      }
      else{
    strcpy(send_socket,message);
    printf("SEND : %s\n", send_socket);
    write(sock,message,sizeof(message)-1); // 서버로 message 전송
    }
      
      
   }
   close(sock);
   return 0;
}

void error_handling(char *message)
{
   fputs(message,stderr);
   fputc('\n',stderr);
   exit(1);
}

 

여기도 마찬가지로 제가 쓰던 코드라 조금 난잡할수도 있습니다. 위와 같은 방식으로 send_socket이라는 변수에 message를 저장시켜 문장이 변하지 않으면 계속 while 루프를 돌도록 구현했습니다.

 

아래는 프로그램 구현 동영상입니다.

 

 

 

참고도서 : 윤성우의 열혈 TCP/IP 소켓 프로그래밍

 

====== 오렌지 미디어 ======

             목록 서버1   서버2 강의시간 강의교안  PART 01 네트워크 프로그래밍의 시작    Chapter 01 네트워크 프로그래밍과 소켓의 이해        01-1. 네트워크 프로그래밍과 소켓의 이해① 27:43        01-1. 네트워크 프로그래밍과 소켓의 이해② 07:58        01-1. 네트워크 프로그래밍과 소켓의 이해③ 12:52        01-2. 리눅스 기반 파일 조작하기 27:27        01-3.

www.orentec.co.kr

 

posted by devtang
2020. 3. 2. 17:25 Raspberry Pi

 

EAR(Eye Aspect ratio)알고리즘을 이용한 운전자 졸음운전 방지 시스템 입니다.

 

구현 영상

 

EAR 알고리즘

Soukupová와 Čech의 2016 년 논문인 Facial Landmarks를 사용한 Real-Time Eye Blink Detection 의 작업을 기반으로  EAR ( eye aspect ratio) 관계를 반영하는 방정식을 도출 할 수 있습니다.

 

 

 

눈을 감게 되면 눈의 세로 비율이 작아지고, EAR 비율역시 작아집니다. 사람이 깜박이면 눈의 종횡비가 급격히 감소하여 0에 가까워집니다. 사람이 졸리면 눈을 감거나 눈을 조그마하게 뜨는 행동을 하게 되므로 EAR값을 이용하여 주기적으로 낮아지면 알람을 울리게 하는 졸음감지 시스템을 구현할 수 있습니다.

 

def eye_aspect_ratio(eye):
#눈에 랜드마크 좌표를 찍어서 EAR값을 예측합니다.
	A = dist.euclidean(eye[1],eye[5]) 
	B = dist.euclidean(eye[2],eye[4])
	C = dist.euclidean(eye[0],eye[3])
	
	ear = (A+B) / (2.0 * C)
	return ear

 

또한 평소 눈의 THRESH값을 0.3정도로 설정해놓고 눈을 감게되면 EAR비율이 작아지므로 ALARM이 울리게 됩니다. 

# 눈의 EAR의 THRESH 기본값을 0.3으로 설정합니다.
EYE_AR_THRESH = 0.3
EYE_AR_CONSEC_FRAMES = 48
# 프레임 카운터와 부울을 초기화하는 데 사용
# 알람이 울리면 표시
counter = 0
ALARM_ON = false

 

 

OpenCV의 drawContours 함수를 이용하여 눈 주변에 선을 실시간으로 그려줍니다.

   #외곽선으로 인식된 눈을 그려줍니다(drawContours함수이용)
		leftEyeHull = cv2.convexHull(leftEye)
		rightEyeHull = cv2.convexHull(rightEye)
		cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
		cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

 

눈을 인식해야 하므로 68_face_landmark.dat 파일을 이용하여 예제를 실행합니다.

 

정상적으로 구동이 되는것을 확인했습니다. 라즈베리파이에서 실시간으로 돌려봤지만

위에 동영상을 보시면 프레임이 상당히 낮습니다.

 

읽어주셔서 감사합니다.

 

posted by devtang
2020. 2. 25. 20:54 AI/TensorFlow Lite

*참고한 사이트는 게시글 하단에 남겨놓겠습니다.

 

 

Tensor Processing Unit

구글에서 Coral Edge TPU 라는 제품을 냈습니다.

 

Google Coral USB Accelerator

구글 코랄 USB 액셀레이터 / 컴퓨터에 꽂아 Google Edge TPU 보조프로세서로 기능하는 제품 / USB 3.0 C타입 / Google 클라우드와 호환 / 로컬 인공지능

www.devicemart.co.kr

 

USB 형식으로 컴퓨터에 꽂아 뉴럴 네트워크의 연산속도를 가속화 해주는 제품입니다.

컴퓨터 제품에 간단하게 꽂아서 쓸수 있어서 좋은점도 있지만, USB형식이라 라즈베리파이와 같은

싱글보드 컴퓨터에 호환이되는것이 흥미롭습니다.

 

되게 아담합니다. ( 소프트 점보 지우개 수준 )

Tensorflow Lite 버전밖에 지원이 되지 않지만 그래도 라즈베리파이에서 실시간 사물 인식을

꽤 높은 프레임으로 실행할 수 있어서 괜찮은 제품인 것 같습니다.

라즈베리파이에 USB를 꽂으면 기계에서 LED가 켜집니다.

 

라즈베리파이에 이용하려면 아래 3가지가 설치 되어있어야합니다.

(라즈베리파이가 지원되지만 Coral 공식 홈페이지에서는 3B+ 모델과 4 모델에만 테스트 했다고 합니다.)

 

1. Python 3.5 이상 설치

2. Edge TPU Runtime 설치

3. TensorFlow Lite 설치

 

1. Python 3.5 이상 설치

라즈베리파이 스트레치 버전(제 기준)에는 파이썬이 2.7.x 버전대로 설치되어 있으므로 아래와 같은 명령어로 파이썬을 설치해줍니다. 

sudo apt-get update
sudo apt-get install python3

 

2. Edge TPU Runtime 설치

coral에서 제공하는 클라우드 패키지를 라즈베리에 저장합니다.

echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

sudo apt-get update

이제 TPU runtime을 설치합니다. 

표준 클럭으로 설치하려면 아래의 명령어를 입력하세요.

sudo apt-get install libedgetpu1-std

클럭을 최대로 높이고 설치하려면 아래의 명령어를 입력하세요. (라즈베리파이에 쿨러가 없다면 왠만하면 비추입니다.)

sudo apt-get install libedgetpu1-max

설치가  완료되면 Coral USB Accelerator를 라즈베리파이에 꼽고 Tensorflow Lite 설치를 합니다.

 

3. TensorFlow Lite 설치

 

라즈베리파이3 파이썬3.7.x 버전 이므로 아래와 같은 명령어를 입력하여 다운로드 합니다.

wget https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl

다운로드 받은다음 pip 명령어로 설치합니다.

pip3 install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl

 

다른 버전의 TensorFlow Lite를 원하시면 아래 사이트를 참조하세요.

https://www.tensorflow.org/lite/guide/python

 

Python quickstart  |  TensorFlow Lite

Using TensorFlow Lite with Python is great for embedded devices based on Linux, such as Raspberry Pi and Coral devices with Edge TPU, among many others. This page shows how you can start running TensorFlow Lite models with Python in just a few minutes. All

www.tensorflow.org

 

이제 모든 설치가 완료되었으면, 정상적으로 구동이 되는지 확인해봅시다!

 

coral이라는 폴더를 생성하고 github에서 예제 코드를 받아옵니다.

mkdir coral &&  cd coral git clone https://github.com/google-coral/tflite.git

새(bird)를 분류하는 텐서플로우 기본 예제를 다운 받아옵니다.

cd tflite / python / examples / classification bash install_requirements.sh

parrot.jpg

파이썬으로 예제 그림을 추론할 수 있는지 돌려봅니다.

python3 classify_image.py \ 
--model models / mobilenet_v2_1.0_224_inat_bird_quant_edgetpu.tflite \ 
--labels models / inat_bird_labels.txt \ 
--input images / parrot.jpg

아래와 같이 나오면 TensorFlow Lite 가 정상적으로 설치됬습니다.

INFO: Initialized TensorFlow Lite runtime.
----INFERENCE TIME----
Note: The first inference on Edge TPU is slow because it includes loading the model into Edge TPU memory.
15.3ms
3.0ms
2.8ms
2.9ms
2.9ms
-------RESULTS--------
Ara macao (Scarlet Macaw): 0.76562

Ara macao가 무엇인고 찾아봤더니

금강앵무새라고 하네요. 사진보니 위의 예제 사진과 동일한 새입니다.

 

올바르게 설치된 것 같으니 이제는 사물인식 코드를 이용해서 실시간 웹캠으로 사물인식을 해보겠습니다.

 

https://github.com/google-coral/edgetpu/blob/master/examples/object_detection.py

 

google-coral/edgetpu

Source code for the Edge TPU API library. Contribute to google-coral/edgetpu development by creating an account on GitHub.

github.com

 

Lite버전임에도 불구하고 은근 정확도가 높습니다.

 

0  person
1  bicycle
2  car
3  motorcycle
4  airplane
5  bus
6  train
7  truck
8  boat
9  traffic light
10  fire hydrant
12  stop sign
13  parking meter
14  bench
15  bird
16  cat
17  dog
18  horse
19  sheep
20  cow
21  elephant
22  bear
23  zebra
24  giraffe
26  backpack
27  umbrella
30  handbag
31  tie
32  suitcase
33  frisbee
34  skis
35  snowboard
36  sports ball
37  kite
38  baseball bat
39  baseball glove
40  skateboard
41  surfboard
42  tennis racket
43  bottle
45  wine glass
46  cup
47  fork
48  knife
49  spoon
50  bowl
51  banana
52  apple
53  sandwich
54  orange
55  broccoli
56  carrot
57  hot dog
58  pizza
59  donut
60  cake
61  chair
62  couch
63  potted plant
64  bed
66  dining table
69  toilet
71  tv
72  laptop
73  mouse
74  remote
75  keyboard
76  cell phone
77  microwave
78  oven
79  toaster
80  sink
81  refrigerator
83  book
84  clock
85  vase
86  scissors
87  teddy bear
88  hair drier
89  toothbrush

89개의 객체가 학습되어있습니다. 가지고 놀다보면 꽤 재밌어요 ㅎㅎ

아래는 실시간 웹캠 영상입니다.

TensorFlow Lite를 이용한 사물 인식 영상으로 마무리 짓겠습니다.

 

서투른 글 읽어주셔서 감사합니다.

 

참고사이트

https://coral.ai/docs/edgetpu/multiple-edgetpu/

https://coral.ai/docs/accelerator/get-started#2-install-the-tensorflow-lite-library

https://www.tensorflow.org/lite/guide/python

 

Python quickstart  |  TensorFlow Lite

Using TensorFlow Lite with Python is great for embedded devices based on Linux, such as Raspberry Pi and Coral devices with Edge TPU, among many others. This page shows how you can start running TensorFlow Lite models with Python in just a few minutes. All

www.tensorflow.org

 

Get started with the USB Accelerator | Coral

Learn how to set up the Coral USB Accelerator and run some demo code.

coral.ai

 

Run multiple models with multiple Edge TPUs | Coral

 

coral.ai

 

posted by devtang
2020. 2. 25. 16:24 개인 프로젝트

 

연구실에서 개인적으로 진행해본 프로젝트 데모영상입니다.

 

출입알림시스템 데모 영상

 

 

계획하게된 계기

우선 저는 대학교 학부생으로 정보통신공학전공 연구실에 들어왔습니다.

라즈베리파이와 우분투 환경에대해 공부하던중에 ㅎㅎㅎ

교수님이 출입하시면 게임하다 걸리면 혼날거같아서 ㅎㅎㅎ

YOLO를 이용하여 연구실 인원 얼굴을 학습하여 출입시 누군지 인식하고 음성으로 알림 해주는 프로그램을 만들 계획을 짜게 되었습니다.

 

출입알림 시스템을 만들기 위해서 제가 간단히라도 공부했던 내용을 정리해보면

 

● YOLO 학습 ( 머신러닝의 원리, 데이터 학습원리 및 방법 )

● 라즈베리파이 

● OpenCV를 이용한 영상처리 기법

● TCP/IP 소켓 프로그래밍

● 카카오API, 구글 API를 활용한 TTS(Text to Speech), STT(Speech to Text)

 

2학년이 막 끝난 시점에 연구실에 처음 들어오게된 저로써는 , 처음에 그냥 공부하려니

되게 낯설었지만, 작은 프로젝트 하나라도 제대로 구현해보자 하는 마음으로 프로젝트에 

쓰일만한 내용을 학습했습니다.  특히~ 소켓 잡을때는 진짜 하기 싫었네요 ㅎㅎ

 

아무튼 어느정도 공부하면서 확실한 계획을 세웠습니다.

 

1단계 : 연구실 내의 모든 사람들의 얼굴을 학습한 후 실시간 감지 확인

 

 

첫번째로, 우리의 얼굴을 학습시킨후, 정상적으로 인식이 되는지 확인하였습니다.

 

YOLO는 Ubuntu환경에서 구동하였고, 1인당 1300~1400장의 얼굴 데이터를 학습시켰습니다.

 

 

얼굴 학습후 테스트 영상

YOLO 학습했던 내용은 추후에 추가 업로드 예정입니다.

 

2단계 : 양방향 소켓 통신 확인 (문자열 송수신)

 

소켓 프로그래밍은 도서관에서 책을빌려 병행하면서 공부했었네요

윤성우의 열혈 TCP/IP 프로그래밍

 

====== 오렌지 미디어 ======

             목록 서버1   서버2 강의시간 강의교안  PART 01 네트워크 프로그래밍의 시작    Chapter 01 네트워크 프로그래밍과 소켓의 이해        01-1. 네트워크 프로그래밍과 소켓의 이해① 27:43        01-1. 네트워크 프로그래밍과 소켓의 이해② 07:58        01-1. 네트워크 프로그래밍과 소켓의 이해③ 12:52        01-2. 리눅스 기반 파일 조작하기 27:27        01-3.

www.orentec.co.kr

 

라즈베리파이 <-> 우분투 간의 소켓 통신 확인후

YOLO에서 감지했을때 txt파일에 인식한 사람의 이름을 써주고

실시간으로 소켓으로 txt파일을 읽어서 라즈베리파이에 전송해주는 식으로 구상했습니다.

 

라즈베리파이로 출력하는 음성은 카카오 API 를 이용하여, 각 사람들의 음성파일을 만들었습니다.

 

MobaXterm을 이용한 음성파일 추출

소프트웨어적인 구현은 거의 완벽하게 진행되어있으나

하드웨어적 효율적 구현은 추후에 할예정입니다. 

 

YOLO가 인식하기에 카메라가 상당히 먼곳에 있어 인식이안되서 USB연장선으로 카메라를 땡겨왔습니다.

상당히 불편합니다..

USB 연장선을 더 추가하여 아예 벽쪽으로 몰아버리거나..

아니면 무선 영상 통신을 이용하여 영상을 받아 인식해주거나

생각좀 해봐야 할것 같네요.

posted by devtang
2020. 2. 25. 14:00 Raspberry Pi

*참고한 사이트는 게시글 하단에 남겨놓겠습니다.

 

저번 게시물에서 얼굴의 68개의 특징점을 잡아낸 알고리즘을 이용한 예제를 실행해봤습니다.

이번에는 5개의 랜드마크를 추출하는 알고리즘을 사용했습니다.

 

 

68개의 랜드마크를 추출하는 방식과 달리 ,이번 알고리즘은 

왼쪽 눈 2점, 오른쪽 눈 2점, 코 1점을 검출하여, 라즈베리파이에서 보다 더 나은 속도를 보여줍니다.

속도는 68개 추출에 비해 8-10% 향상되었으며, 잠재적으로 정확성은 조금 떨어질 수 있다고 합니다.

인식률이 상당히 좋습니다. 라즈베리파이에서 이정도 속도만 나와도 감사할 따름입니다...

실시간으로 웹캠을 통해 얼굴의 특징점이 인식됩니다.

또한

68 포인트 랜드마크 데이터 파일은 99.7MB정도였지만

5 포인트 랜드마크 데이터 파일은 9.2MB로 기존 파일에 비해 약 10배 정도 작아졌습니다.

 

구성환경으로는 전 게시물과 동일합니다.

Raspberry Pi 3B+

Picamera

OS : Raspbian Stretch 9.11

OpenCV, imutils, dlib,라이브러리 설치

 

소스코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# USAGE
 
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import cv2
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p""--shape-predictor", required=True,
    help="/home/pi/Desktop/faster_facial_landmarks/shape_predictor_5_face_landmarks.dat")
args = vars(ap.parse_args())
 
# initialize dlib's face detector (HOG-based) and then create the
# facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
 
# initialize the video stream and sleep for a bit, allowing the
# camera sensor to warm up
print("[INFO] camera sensor warming up...")
#vs = VideoStream(src=0).start()
vs = VideoStream(usePiCamera=True).start() # Raspberry Pi
 
# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream, resize it to
    # have a maximum width of 400 pixels, and convert it to
    # grayscale
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
    # detect faces in the grayscale frame
    rects = detector(gray, 0)
 
    # check to see if a face was detected, and if so, draw the total
    # number of faces on the frame
    if len(rects) > 0:
        text = "{} face(s) found".format(len(rects))
        cv2.putText(frame, text, (1020), cv2.FONT_HERSHEY_SIMPLEX,
            0.5, (00255), 2)
 
    # loop over the face detections
    for rect in rects:
        # compute the bounding box of the face and draw it on the
        # frame
        (bX, bY, bW, bH) = face_utils.rect_to_bb(rect)
        cv2.rectangle(frame, (bX, bY), (bX + bW, bY + bH),
            (02550), 1)
 
        # determine the facial landmarks for the face region, then
        # convert the facial landmark (x, y)-coordinates to a NumPy
        # array
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)
 
        # loop over the (x, y)-coordinates for the facial landmarks
        # and draw each of them
        for (i, (x, y)) in enumerate(shape):
            cv2.circle(frame, (x, y), 1, (00255), -1)
            cv2.putText(frame, str(i + 1), (x - 10, y - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.35, (00255), 1)
 
    # show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1& 0xFF
 
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
 
# do a bit of cleanup
cv2.destroyAllWindows()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

자세한 소스 코드 내용은, 이곳을 참조하세요.

 

코드 복사후, 동일한 폴더 내에 데이터 파일과 파이썬파일을 넣어줍니다.

(5 포인트 얼굴 랜드마크 추출 데이터 파일은 하단의 참조사이트에서 받을 수 있습니다.)

 

저는 Desktop 에 faster_facial_landmarks 라는 폴더를 생성하여 넣어주었습니다.

터미널에 명령어를 입력해줍니다.

1
2
pi@raspberrypi:~/Desktop/faster_facial_landmarks $ python faster_facial_landmarks.py -shape_predictor_5_face_landmarks.dat
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

이번 게시물은 5개의 특징점을 잡아내는 예제를 실행해봤습니다.

다음엔 졸음운전을 감지하는 시스템(?) 을 포스팅 하도록 하겠습니다.

 

서투른 글 읽어주셔서 감사합니다.

 

참고사이트

(Faster) Facial landmark detector with dlib

 

(Faster) Facial landmark detector with dlib - PyImageSearch

In this tutorial you'll learn how to use dlib's 5-point facial landmark model, over 10x smaller and 8-10% faster than the original 68-point facial landmark detector.

www.pyimagesearch.com

 

posted by devtang
2020. 2. 25. 12:54 Raspberry Pi

*참고한 사이트는 게시글 하단에 남겨놓겠습니다.

 

이번에 게시할 내용은 바로 dlib 와 OpenCV을 이용한 얼굴의 특징점을 찾아내는 예제입니다.

 

위와같이 얼굴의 특징점을 실시간으로 잡아주는 예제를 실행해봤습니다.

 

Facial Landmarks?

 

 

68개의 특징점을 추출한 포인트

사람의 얼굴에 특징점을 찍어낸 방법입니다.

Face Landmark estimation 알고리즘의 원리는 2014년도에 발명된 접근 방식입니다.

이것을 이용하여 카메라를 이용한 다양한 어플리케이션을 만들수도 있습니다.

 

저는 이것을 라즈베리파이로 실시간 캠영상을 받아, 얼굴에 랜드마크를 표시하는 예제를 실행해봤습니다.

실행한 환경으로는

 

Raspberry Pi 3B+

Picamera

OS : Raspbian Stretch 9.11

OpenCV, imutils, dlib,라이브러리 설치

(라즈베리파이 세팅, 라이브러리 설치 방법 등은 추후에 포스트할 예정입니다.)

 

shape_predictor_68_face_landmarks.dat 파일은 게시물 하단의 참고사이트나 메일로 연락주세요.

 

제가 실행해본 소스 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# USAGE
 
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import datetime
import argparse
import imutils
import time
import dlib
import cv2
 
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p""--shape-predictor", required=True,
    help="path to facial landmark predictor")
ap.add_argument("-r""--picamera", type=int, default=-1,
    help="whether or not the Raspberry Pi camera should be used")
args = vars(ap.parse_args())
 
# initialize dlib's face detector (HOG-based) and then create
# the facial landmark predictor
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
 
# initialize the video stream and allow the cammera sensor to warmup
print("[INFO] camera sensor warming up...")
vs = VideoStream(usePiCamera=args["picamera"> 0).start()
 
# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream, resize it to
    # have a maximum width of 400 pixels, and convert it to
    # grayscale
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
    # detect faces in the grayscale frame
    rects = detector(gray, 0)
 
    # loop over the face detections
    for rect in rects:
        # determine the facial landmarks for the face region, then
        # convert the facial landmark (x, y)-coordinates to a NumPy
        # array
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)
 
        # loop over the (x, y)-coordinates for the facial landmarks
        # and draw them on the image
        for (x, y) in shape:
            cv2.circle(frame, (x, y), 1, (00255), -1)
      
    # show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1& 0xFF
 
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
 
# do a bit of cleanup
cv2.destroyAllWindows()
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

소스코드의 자세한 내용은 , 이곳을 참조하세요.

 

소스코드를 저장한후 꼭 소스파일과 landmark 데이터 파일이 한 폴더 내에 있어야합니다.

 

터미널 창을 열어 명령어를 입력해줍니다.

1
pi@raspberrypi:~/Desktop $ python real_landmarks.py -shape_predictor_68_face_landmarks.dat
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

성공적으로 감지가 됩니다!!

 

라즈베리파이에서 구현시 프레임이 저하되긴 하지만 활용할만한 알고리즘인것 같습니다. 

다음 게시물엔 라즈베리파이에서 조금더 효율적으로 인식이되는 방법에대해 포스팅 할 예정입니다.

서투른 글 읽어주셔서 감사합니다.

참고사이트

기계 학습(Machine Learning, 머신러닝)은 즐겁다! Part 4

 

기계 학습(Machine Learning, 머신 러닝)은 즐겁다! Part 4

딥러닝(Deep Learning)을 사용한 최신 얼굴 인식(Face Recognition)

medium.com

Real-time facial landmark detection with OpenCV, Python, and dlib

 

Real-time facial landmark detection with OpenCV, Python, and dlib - PyImageSearch

In this tutorial, I demonstrate how to detect facial landmarks in video streams in real-time using OpenCV, Python, and dlib.

www.pyimagesearch.com

 

posted by devtang
prev 1 next