Tensorflow의 Object Detection API를 사용하면서, 궁극적인 목표는 나만의 오브젝트들을 학습하여 영상 및 이미지 분석에 이용해 보는것 이었다.


이것을 하는데 여러 시행착오가 있었으며 지금까지 거쳐온 과정은 아래와 같다.


1. Nvidia-Docker 기반으로 tensorflow_gpu를 설치

    [설치] Installing tensorflow-gpu with Docker

2. Tensorflow Object Detection API 설치

    [설치] Object Detection API      

2. 오프라인 및 실시간 영상을 프레임 단위로 분석하기 위해서 Opencv 라이브러리를 설치

    [설치] Installing Opencv with Tensorflow    

3. Object Detection API Tutorial - 이미지 분석

    [API] Object Detection API를 이용한 오브젝트 인식하기 Part 1. - 설정 [펌]

4. Object Detection API Tutorial - 영상분석(실시간 및 녹화 영상)

    [API] Object Detection API를 이용한 오브젝트 인식하기 Part 3. - Web Cam 연동 [펌]

5. Tensorflow 학습 데이터 포맷 TFRecord

    [TFRecord] 텐서플로우 트레이닝 데이타 포맷인 *.tfrecord 파일 읽고 쓰기 [펌]

6.  Custom Object Detection - 동물 사진 학습 ( 실패 )

    [API] Tensorflow Object Detection API를 이용한 물체 인식 #2-동물 사진을 학습 시켜보자[펌]


처음으로 참조한 블로거의 동물 사진 학습하는 포스팅을 보고 시도하였으나 Google CloudML를 이용하여 학습하는 과정을 소개한것이라는 것을 알고 포기 하였다. (돈이 들어서)


국내 블로거들의 포스팅은 이제 크게 도움이 되지 못해서, 해외 블로거들의 글들로 눈을 돌린 시점이기도하다.

처음으로 검색해서 나온 블로거는 Dat Tran 이다.

https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9

아래 내용을 기반으로 진행해보려 했으나 조금 어려워서 다른 블로거를 찾았다.

블로거: sentdex

블로그:

https://plus.google.com/+sentdex

https://www.youtube.com/watch?v=K_mFnvzyLvc&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=3

https://pythonprogramming.net/custom-objects-tracking-tensorflow-object-detection-api-tutorial/


이 사람은 파이썬으로 상당히 다양한 프로젝트를 해본것 같다. 처음으로 찾은 Dat Tran이 포스팅한 내용을 인용하여 Custom Object Detection 하는 방법을 가이드 한다.


Tensorflow 에서 Custom Object Detection을 하기위한 과정은 다음과 같다.


1.학습시킬 이미지 준비

  학습 시킬 이미지는 일반적으로는 적어도 100장 또는 500장 이상의 이미지가 필요하다고 한다.

  하지만 내가 실무자로부터(R업체 솔루션을 개발한 대표)들은 바로는 적어도 2000장 보통은 20000~30000장의 이미지를 확보해야 정확도가 괜찮게 나온다고 들었다.

  ※ TODO 내가 학습 시키고 싶은 이미지를 쉽게 확보 할 수 있는 도구를 찾아보기.(또는 개발해보기)


2. Annotate/label

  Object Detection을 하려면 이미지와 해당 이미지에 대한 정보를 가지고 있는 XML 파일들이 있어야 한다.(이를 레이블링이라함)

  이미지 정보를 들고 있는 XML파일에는 이미지 이름, 이미지 종류, 이미지 내 detection 대상 이름, 좌표(xmin, xmax, ymin, ymax) 등이 포함되어야 한다.

  이렇게 이미지 레이블링을 도와주는 도구가 몇몇 있는것 같다.

   - labelImg: https://github.com/tzutalin/labelImg

   - FastAnnotationTool: https://github.com/christopher5106/FastAnnotationTool

   - ImageMagic: http://imagemagick.org/script/index.php


3. 보유하고 있는 데이터를 train/test sample로 나누기

  보유하고 있는 데이터를 train/test를 나누는 여러 가지가 있지만, 그 중 가장 대표적인 이유는 Overfitting 때문에 그렇다.

  내가 가지고 있는 데이터셋에만 적합한 학습데이터를 가지지 않으려는 노력인것이다.

4. 학습을 위한 TF Records 변환

  [TFRecord] 텐서플로우 트레이닝 데이타 포맷인 *.tfrecord 파일 읽고 쓰기 [펌] 을 참조

5. 학습에 사용할 모델 고르기

   config 파일 설정하기

   https://github.com/tensorflow/models/tree/master/research/object_detection/samples/configs

6. 학습 시키기(Train)

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

   Tensorflow에서 가이드해주는 Config를 보면 학습시키는 단계가 무려 20만이다.. 어떤이가 CPU에서 100step을 돌리는데 1시간이나 걸렸다고한다. 나는 GPU를 사용하여 3만스텝 정도하는데 3시간쯤 걸린거 같다. 이래서 꼭 GPU를 써야 하는거 같다.

7. Export graph from new trained model

8. Detect custom objects in real time


이 블로거의 도움으로 나만의 오브젝트를 학습하여 탐지할 수 있는 방법을 알게 되었고 이제 포스팅을 시작한다.

 

 

 

 

 

 

 

 

 

Posted by 이성윤

tensorflow 에서 제공하는 Install 가이드를(https://www.tensorflow.org/install/install_linux) 통해서 설치해 보았다.


Determine how to install TensorFlow


Docker completely isolates the TensorFlow installation from pre-existing packages on your machine. The Docker container contains TensorFlow and all its dependencies. Note that the Docker image can be quite large (hundreds of MBs). You might choose the Docker installation if you are incorporating TensorFlow into a larger application architecture that already uses Docker.


Installing with Docker

Take the following steps to install TensorFlow through Docker:

  1. Install Docker on your machine as described in the Docker documentation.
  2. Optionally, create a Linux group called docker to allow launching containers without sudo as described in the Docker documentation. (If you don't do this step, you'll have to use sudo each time you invoke Docker.)
  3. To install a version of TensorFlow that supports GPUs, you must first install nvidia-docker, which is stored in github.
  4. Launch a Docker container that contains one of the TensorFlow binary images.

The remainder of this section explains how to launch a Docker container.


Docker를 통한 GPU 버전을 설치하기전에 nvidia-docker를 설치해줘야 한다.

현재 설치 할 시스템의 OS가 CentOs7이라서  https://github.com/NVIDIA/nvidia-docker 에서  "CentOS/RHEL 7 x86_64"  가이드 된 대로 진행을 해보면 뭔가 적절하게 되지 않는다.


그래서 구글링을 하게 되었다. http://blog.exxactcorp.com/installing-using-docker-nv-docker-centos-7/ 이 블로거가 가이드한대로 설치하면 잘 설치가 된다.

Installing and getting DOCKER and NV-DOCKER running in CentOS 7 is a straight forward process:

# Assumes CentOS 7
# Assumes NVIDIA Driver is installed as per requirements ( < 340.29 )
# Install DOCKER
sudo curl -fsSL https://get.docker.com/ | sh
# Start DOCKER
sudo systemctl start docker
# Add dockeruser, usermod change
sudo adduser dockeruser
usermod -aG docker dockeruser
# Install NV-DOCKER
# GET NVIDIA-DOCKER
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker-1.0.1-1.x86_64.rpm
# INSTALL
sudo rpm -i /tmp/nvidia-docker*.rpm
# Start NV-DOCKER Service
systemctl start nvidia-docker


그럼 이제 nvidia-docker 가 잘 설치가 되었다.


GPU support

Prior to installing TensorFlow with GPU support, ensure that your system meets all NVIDIA software requirements. To launch a Docker container with NVidia GPU support, enter a command of the following format:


$ nvidia-docker run -it -p hostPort:containerPort TensorFlowGPUImage

where:

  • -p hostPort:containerPort is optional. If you plan to run TensorFlow programs from the shell, omit this option. If you plan to run TensorFlow programs as Jupyter notebooks, set both hostPort and containerPort to 8888.
  • TensorFlowGPUImage specifies the Docker container. You must specify one of the following values:
    • gcr.io/tensorflow/tensorflow:latest-gpu, which is the latest TensorFlow GPU binary image.
    • gcr.io/tensorflow/tensorflow:latest-devel-gpu, which is the latest TensorFlow GPU Binary image plus source code.
    • gcr.io/tensorflow/tensorflow:version-gpu, which is the specified version (for example, 0.12.1) of the TensorFlow GPU binary image.
    • gcr.io/tensorflow/tensorflow:version-devel-gpu, which is the specified version (for example, 0.12.1) of the TensorFlow GPU binary image plus source code.

We recommend installing one of the latest versions. For example, the following command launches the latest TensorFlow GPU binary image in a Docker container from which you can run TensorFlow programs in a shell:

$ nvidia-docker run -it gcr.io/tensorflow/tensorflow:latest-gpu bash

The following command also launches the latest TensorFlow GPU binary image in a Docker container. In this Docker container, you can run TensorFlow programs in a Jupyter notebook:

$ nvidia-docker run -it -p 8888:8888 gcr.io/tensorflow/tensorflow:latest-gpu

The following command installs an older TensorFlow version (0.12.1):

$ nvidia-docker run -it -p 8888:8888 gcr.io/tensorflow/tensorflow:0.12.1-gpu

Docker will download the TensorFlow binary image the first time you launch it. For more details see the TensorFlow docker readme.


위에 내용을 참조하여 내가 실제로 수행한 명령어들은 와래와 같다.


$ sudo nvidia-docker run -d -p 8888:8888 -p 8889:8889 -p 6901:6901 --name tensorflow_gpu gcr.io/tensorflow/tensorflow:latest-gpu

위의 명령어를 수행하면 tensorflow + cuda + notebook 이 설치된 빈 깡통 Ubuntu16.04 OS가 설치된다.

※ 여기에서 중요한점은 -p 는 포트포워딩할 포트인데 내가 사용할 서버의 포트를 어떻게 사용할 것인지를 충분히 고려하여야 한다는점이다. 현재까지는 docker는 런타임중에 포트를 추가할 수 없게 되어 있다. 포트를 추가 하려면 다양한 방법이 있겠지만

나와 같은 경우에는 현재 이미지를 commit 하여 저장한 상태에서 다시 포트를 추가하여 container를 만들었다.


$ sudo nvidia-docker exec -it tensorflow_gpu bash

이 명령을 수행하게 되면 내가 생성한 tensorflow_gpu bash 컨테이너에 접속할 수 있게 된다.


Validate your installation

Run a short TensorFlow program

Invoke python from your shell as follows:

$ python

Enter the following short program inside the python interactive shell:

Python
import tensorflow as tf
hello
= tf.constant('Hello, TensorFlow!')

sess
= tf.Session()
print(sess.run(hello))

If the system outputs the following, then you are ready to begin writing TensorFlow programs:

Hello, TensorFlow!

위에도 언급했지만, nvidia-docker를 이용하여 컨테이너를 생성하면 빈깡통 ubuntu가 설치된다.

그러므로 기본 유틸리티들을 설치해주어야 한다.


Ubuntu 설치 후 기본 도구 설치

http://cafe.naver.com/telcosn/562 글 이외의 설치 목록은 아래에 있다.

apt-getinstall net-tools

apt-get install tcpdump

apt-get install apt-utils

apt install-y  vim htop  iftop tree  openssh-server  lrzsz openvswitch-switch

sudo apt-get install git


Ubuntu 설치 후 데스크탑 설치

apt-get update
apt-get upgrade
apt-get install tasksel


 

 

 

 

2


참고: https://imitator.kr/Linux/1305


Ubuntu 설치 후 tightvncserver 설치

참고: http://cafe.naver.com/telcosn/437

명령어: vncserver :100 -rfbport 6901 -geometry 1920x1080


Ubuntu 설치 후 시간 동기화

sudo dpkg-reconfigure tzdata -> asia, seoul 선택

Posted by 이성윤