블로그 이미지
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. 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. 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