728x90

출처

pip3 설치

$ sudo apt update
$ sudo apt install gfortran libopenblas-dev liblapack-dev libhdf5-dev
$ pip3 --version
pip 20.0.2 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

파이썬 라이브러리 설치

$ sudo pip3 install setuptools wheel
$ sudo pip3 install h5py

swap 사이즈 설정

현재 swap 사이즈 확인

$ free -h                      
              total        used        free      shared  buff/cache   available
Mem:           998M        182M        483M         13M        332M        772M
Swap:          499M         63M        435M
$ sudo swapon -s
Filename                                Type            Size    Used    Priority
/dev/zram1                              partition       511416  65024   5
$ sudo swapoff /dev/zram1
$ sudo zramctl --reset /dev/zram1
$ sudo zramctl --find --size 2048M
/dev/zram1
$ sudo mkswap /dev/zram1
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=ce87d072-ac8e-4bd1-ba05-d362b51b6fa1
$ sudo swapon /dev/zram1
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           998M        221M        432M         16M        345M        730M
Swap:          2.0G          0B        2.0G

TensorFlow 2.1.0 패키지 설치

TensorFlow 2.1.0 패키지 다운로드

$ wget http://1.229.109.140:3562/tensorflow/tensorflow-2.1.0/tensorflow-2.1.0-cp37-none-linux_armv7l.whl

tensorflow 2.1.0 파이썬 페키지 설치

$ export TMPDIR=/var/tmp
$ pip3 install tensorflow-2.1.0-cp37-none-linux_armv7l.whl
 
 ... 생략 ...
 
Installing collected packages: keras-preprocessing, gast, pyasn1, rsa, cachetools, pyasn1-modules, google-auth, markdown, oauthlib, certifi, chardet, idna, urllib3, requests, requests-oauthlib, google-auth-oauthlib, protobuf, absl-py, werkzeug, grpcio, tensorboard, keras-applications, tensorflow-estimator, google-pasta, wrapt, astor, scipy, opt-einsum, termcolor, tensorflow
Successfully installed absl-py-0.9.0 astor-0.8.1 cachetools-4.0.0 certifi-2019.11.28 chardet-3.0.4 gast-0.2.2 google-auth-1.13.1 google-auth-oauthlib-0.4.1 google-pasta-0.2.0 grpcio-1.28.1 idna-2.9 keras-applications-1.0.8 keras-preprocessing-1.1.0 markdown-3.2.1 oauthlib-3.1.0 opt-einsum-3.2.0 protobuf-3.11.3 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-2.23.0 requests-oauthlib-1.3.0 rsa-4.0 scipy-1.4.1 tensorboard-2.1.1 tensorflow-2.1.0 tensorflow-estimator-2.1.0 termcolor-1.1.0 urllib3-1.25.8 werkzeug-1.0.1 wrapt-1.12.1

버전 확인

$ python3
Python 3.7.7 (default, Apr  4 2020, 15:46:29) 
[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
'2.1.0'
728x90
728x90

출처

리눅스 정보 확인

CPU 정보 확인

$ cat /proc/cpuinfo
processor       : 0
model name      : ARMv7 Processor rev 5 (v7l)
BogoMIPS        : 48.00
Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x0
CPU part        : 0xc07
CPU revision    : 5
 
 ... 생략 ...
 
Hardware        : Allwinner sun8i Family
Revision        : 0000
Serial          : 1655415394228889

커널에 대한 정보

$ uname -a
Linux bananapim2ultra 5.1.12-sunxi #5.90 SMP Fri Jun 28 19:16:14 CEST 2019 armv7l armv7l armv7l GNU/Linux

OS버전에 대한 정보

$ cat /etc/issue
Ubuntu Bionic with Armbian Linux \l

논리 코어 수 확인

$ grep -c processor /proc/cpuinfo
4

TensorFlow C, C++ 라이브러리 설치

TensorFlow 라이브러리 다운로드

$ wget http://1.229.109.140:3562/tensorflow/tensorflow-2.1.0/libtensorflow.tar.gz

TensorFlow 라이브러리 설치

$ sudo tar -C /usr/local -xzf libtensorflow.tar.gz

Linker 설정

$ sudo ldconfig

예제 hello.c

#include <stdio.h>
#include <tensorflow/c/c_api.h>

int main() {
  printf("TensorFlow C library version %s\n", TF_Version());
  return 0;
}

예제 컴파일

$ gcc hello.c -ltensorflow -o hello

예제 실행

$ ./hello
TensorFlow C library version 2.1.0
728x90
728x90

출처

pip3 설치

$ sudo apt-get install gfortran libopenblas-dev liblapack-dev libhdf5-dev
$ sudo apt install python3-pip python3-dev python3-h5py
$ pip3 --version
pip 18.1 from /usr/lib/python3/dist-packages/pip (python 3.7)

파이썬 라이브러리 설치

$ sudo pip3 install setuptools wheel

swap 사이즈 설정

현재 swap 사이즈 확인

$ free -h
              total        used        free      shared  buff/cache   available
Mem:          966Mi       254Mi       542Mi       4.0Mi       169Mi       685Mi
Swap:         483Mi          0B       483Mi
$ sudo swapon -s
Filename                                Type            Size    Used    Priority
/dev/zram1                              partition       494972  0       5
$ sudo swapoff /dev/zram1
$ sudo zramctl --reset /dev/zram1
$ sudo zramctl --find --size 2048M
/dev/zram1
$ sudo mkswap /dev/zram1
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=7ad9947e-9b3a-48d7-94b3-e9a51107d18b
$ sudo swapon /dev/zram1
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           966M         86M        795M        4.2M         84M        854M
Swap:          2.0G          0B        2.0G

TensorFlow 2.1.0 패키지 설치

TensorFlow 2.1.0 패키지 다운로드

$ wget http://1.229.109.140:3562/tensorflow/tensorflow-2.1.0/tensorflow-2.1.0-cp37-none-linux_armv7l.whl

tensorflow 2.1.0 파이썬 페키지 설치

$ export TMPDIR=/var/tmp
$ pip3 install tensorflow-2.1.0-cp37-none-linux_armv7l.whl

버전 확인

$ python3
Python 3.7.3 (default, Dec 20 2019, 18:57:59) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
'2.1.0'
728x90
728x90

출처

이미지 복원

이미지 복원이 완료되면 SD 메모리를 제거하고 재부팅

$ sudo dd if=Armbian_20.02.1_Bananapim2plus_buster_current_5.4.20_desktop.img of=/dev/mmcblk1 bs=10MB
269+1 records in
269+1 records out
2692743168 bytes (2.7 GB, 2.5 GiB) copied, 340.323 s, 7.9 MB/s

리눅스 정보 확인

CPU 정보 확인

$ cat /proc/cpuinfo
processor       : 0
model name      : ARMv7 Processor rev 5 (v7l)
BogoMIPS        : 22.85
Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x0
CPU part        : 0xc07
CPU revision    : 5
 
 ... 샹략 ... 
 
Hardware        : Allwinner sun8i Family
Revision        : 0000
Serial          : 02c00042f5daa42d

커널에 대한 정보

$ uname -a
Linux bananapim2plus 5.4.20-sunxi #20.02.1 SMP Mon Feb 17 02:09:41 CET 2020 armv7l GNU/Linux

OS버전에 대한 정보

$ cat /etc/issue
Armbian 20.02.1 Buster \l 

논리 코어 수 확인

$ grep -c processor /proc/cpuinfo
4

TensorFlow C, C++ 라이브러리 설치

TensorFlow 라이브러리 다운로드

$ wget http://1.229.109.140:3562/tensorflow/tensorflow-2.1.0/libtensorflow.tar.gz

TensorFlow 라이브러리 설치

$ sudo tar -C /usr/local -xzf libtensorflow.tar.gz

Linker 설정

$ sudo ldconfig

예제 hello.c

#include <stdio.h>
#include <tensorflow/c/c_api.h>

int main() {
  printf("TensorFlow C library version %s\n", TF_Version());
  return 0;
}

예제 컴파일

$ gcc hello.c -ltensorflow -o hello

예제 실행

$ ./hello
TensorFlow C library version 2.1.0
728x90
728x90

출처

Python 3.7 설치

Python을 설치하기 전에 Python을 빌드하는 데 필요한 필수 패키지를 설치

$ sudo apt update
$ sudo apt install -y --no-install-recommends libbluetooth-dev tk-dev uuid-dev wget ca-certificates gnupg2 dirmngr python python3 gcc build-essential wget zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev

Python 소스 다운로드

$ PYTHON_VERSION=3.7.7
$ wget "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz"

Python 빌드

$ tar -xvf Python-3.7.7.tar.xz 
$ cd Python-3.7.7/
$ sudo ./configure --enable-loadable-sqlite-extensions \
  --enable-optimizations \
  --enable-option-checking=fatal \
  --enable-shared \
  --with-system-expat \
  --with-system-ffi \
  --without-ensurepip
$ sudo make -j 2 PROFILE_TASK='-m test.regrtest --pgo \
  test_array test_base64 test_binascii test_binhex test_binop test_bytes test_c_locale_coercion \
  test_class test_cmath test_codecs test_compile test_complex test_csv test_decimal test_dict \
  test_float test_fstring test_hashlib test_io test_iter test_json test_long test_math test_memoryview \
  test_pickle test_re test_set test_slice test_struct test_threading test_time test_traceback test_unicode'
 
 ... 생략 ...
 
Python build finished successfully!
The necessary bits to build these optional modules were not found:
_bz2                  _dbm                  _lzma              
_sqlite3                                                       
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
 
 
The following modules found by detect_modules() in setup.py, have been
built by the Makefile instead, as configured by the Setup files:
_abc                  atexit                pwd                
time                                                           
 
running build_scripts
copying and adjusting /home/pi/Python-3.7.7/Tools/scripts/pydoc3 -> build/scripts-3.7
copying and adjusting /home/pi/Python-3.7.7/Tools/scripts/idle3 -> build/scripts-3.7
copying and adjusting /home/pi/Python-3.7.7/Tools/scripts/2to3 -> build/scripts-3.7
copying and adjusting /home/pi/Python-3.7.7/Tools/scripts/pyvenv -> build/scripts-3.7
changing mode of build/scripts-3.7/pydoc3 from 644 to 755
changing mode of build/scripts-3.7/idle3 from 644 to 755
changing mode of build/scripts-3.7/2to3 from 644 to 755
changing mode of build/scripts-3.7/pyvenv from 644 to 755
renaming build/scripts-3.7/pydoc3 to build/scripts-3.7/pydoc3.7
renaming build/scripts-3.7/idle3 to build/scripts-3.7/idle3.7
renaming build/scripts-3.7/2to3 to build/scripts-3.7/2to3-3.7
renaming build/scripts-3.7/pyvenv to build/scripts-3.7/pyvenv-3.7
make[1]: Leaving directory '/home/pi/Python-3.7.7'

Python 3.7 설치

$ sudo make install
$ sudo ldconfig
$ sudo find /usr/local -depth \
  \( \( -type d -a \( -name test -o -name tests -o -name idle_test \) \) \
  -o \( -type f -a \( -name '*.pyc' -o -name '*.pyo' \) \) \) -exec rm -rf '{}' +
$ python3 --version
$ cd /usr/local/bin \
  && sudo ln -s idle3 idle \
  && sudo ln -s pydoc3 pydoc \
  && sudo ln -s python3 python \
  && sudo ln -s python3-config python-config

pip 설치

$ cd ~  
$ wget -O get-pip.py "https://github.com/pypa/get-pip/raw/d59197a3c169cef378a22428a3fa99d33e080a5d/get-pip.py";
$ sudo python3 get-pip.py --disable-pip-version-check --no-cache-dir "pip==20.0.2"

설치 확인

$ python3 --version
Python 3.7.7
$ pip3 --version
pip 20.0.2 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
728x90
728x90

출처

고정 IP 설정

$ sudo vi /etc/network/interfaces

auto eth0
#       iface eth0 inet dhcp
iface eth0 inet static
address 192.168.0.200
netmask 255.255.255.0
gateway 192.168.0.1
dns-nameservers 219.250.36.130

서비스 다시 시작

$ sudo systemctl restart networking.service
$ sudo systemctl status networking.service
[0m networking.service - Raise network interfaces
   Loaded: loaded (/lib/systemd/system/networking.service; enabled; vendor preset: enabled)
   Active: active (exited) since Sun 2017-08-27 13:26:01 CST; 30min ago
     Docs: man:interfaces(5)
  Process: 14900 ExecStop=/sbin/ifdown -a --read-environment --exclude=lo (code=exited, status=0/SUCCESS)
  Process: 14956 ExecStart=/sbin/ifup -a --read-environment (code=exited, status=0/SUCCESS)
  Process: 14952 ExecStartPre=/bin/sh -c [ "$CONFIGURE_INTERFACES" != "no" ] && [ -n "$(ifquery --read-envi
 Main PID: 14956 (code=exited, status=0/SUCCESS)
 
Aug 27 13:26:00 bpi-iot-ros-ai systemd[1]: Starting Raise network interfaces...
Aug 27 13:26:01 bpi-iot-ros-ai systemd[1]: Started Raise network interfaces.

DNS 설정

$ sudo vi /etc/resolv.conf 

nameserver 219.250.36.130

glmark2 설치

$ sudo apt-get install git g++ build-essential pkg-config
$ sudo apt-get install libx11-dev libgl1-mesa-dev
$ sudo apt-get install libjpeg-dev libpng-dev
$ cd ~/
$ git clone https://github.com/glmark2/glmark2.git
$ cd glmark2/
$ ./waf configure --with-flavors=x11-gl
$ ./waf build -j 4
$ sudo ./waf install

lsmod

$ lsmod
Module                  Size  Used by
hci_uart               18784  1
bcmdhd                565499  0
ft5x_ts                58051  0
ov5640                 41452  0
vfe_v4l2              175612  0
option                 29049  0
usb_wwan                5308  1 option
vfe_io                 28241  2 vfe_v4l2,ov5640
videobuf2_dma_contig     8494  1 vfe_v4l2
videobuf2_memops        1276  1 videobuf2_dma_contig
ss                     30684  0
videobuf2_core         22619  1 vfe_v4l2
ip_tables               9635  0
x_tables               12243  1 ip_tables

sunxi-mali 빌드 (실패)

$ git clone --recursive https://github.com/linux-sunxi/sunxi-mali.git
$ cd sunxi-mali
$ make config
rm -f config.mk
make config.mk
make[1]: Entering directory '/home/pi/sunxi-mali'
make -f Makefile.config
make[2]: Entering directory '/home/pi/sunxi-mali'
ABI="armhf" (Detected)
Error: Failed to open /dev/mali: No such file or directory
VERSION="" (Detected)
Error: Failed to open /dev/mali: No such file or directory
Error: Failed to open /dev/mali: No such file or directory
Error: Failed to open /dev/mali: No such file or directory
Error: Failed to open /dev/mali: No such file or directory
Error: Failed to open /dev/mali: No such file or directory
Makefile.config:57: Unknown/unhandled Mali Version ""
Makefile.config:58: Use VERSION=(r2p4,r3p0,r3p1,r3p2-01rel1) instead
Error: Failed to open /dev/mali: No such file or directory
Makefile.config:59: *** Unknown/unhandled Mali Version "".  Stop.
make[2]: Leaving directory '/home/pi/sunxi-mali'
Makefile:12: recipe for target 'config.mk' failed
make[1]: *** [config.mk] Error 2
make[1]: Leaving directory '/home/pi/sunxi-mali'
Makefile:8: recipe for target 'config' failed
make: *** [config] Error 2
pi@bpi-iot-ros-ai:~/sunxi-mali$ dpkg -l | grep libump
pi@bpi-iot-ros-ai:~/sunxi-mali$ ls
include  lib  Makefile  Makefile.config  Makefile.setup  README  test  version

libump 빌드

출처 : GitHub - linux-sunxi/libump: Unified Memory Provider userspace API source code needed for xf86-video-mali compilation

$ git clone https://github.com/linux-sunxi/libump.git
$ cd libump
$ autoreconf -i
$ ./configuremake
$ make
$ sudo make install

dpkg-buildpackage

$ sudo apt-get install debhelper dh-virtualenv
$ sudo dpkg-buildpackage -b
dpkg-buildpackage: info: source package libump
dpkg-buildpackage: info: source version 3.0-0sunxi1
dpkg-buildpackage: info: source distribution any
dpkg-buildpackage: info: source changed by Luc Verhaegen 
dpkg-buildpackage: info: host architecture armhf
 dpkg-source --before-build libump
dpkg-checkbuilddeps: error: Unmet build dependencies: debhelper (>= 9) dh-autoreconf
dpkg-buildpackage: warning: build dependencies/conflicts unsatisfied; aborting
dpkg-buildpackage: warning: (Use -d flag to override.)

libdri2 빌드

출처 : Mali binary driver - linux-sunxi.org

$ sudo apt-get install xutils-dev
git clone https://github.com/robclark/libdri2
cd libdri2
./autogen.sh
./configure --prefix=/usr
make
make install
ldconfig

sunxi-mali 빌드(성공)

버전 찾기

$ sudo find / -name libUMP.so -print
/home/pi/sunxi-mali/lib/mali/r3p0/armel/android/libUMP.so

make config

$ cd sunxi-mali
$ make config VERSION=r3p0 ABI=armhf
rm -f config.mk
make config.mk
make[1]: Entering directory '/home/pi/sunxi-mali'
make -f Makefile.config
make[2]: Entering directory '/home/pi/sunxi-mali'
ABI="armhf" (Provided)
VERSION="r3p0" (Provided)
EGL_TYPE="x11" (Detected)
echo "MALI_VERSION ?= r3p0" > config.mk
echo "MALI_LIBS_ABI ?= armhf" >> config.mk
echo "MALI_EGL_TYPE ?= x11" >> config.mk
make[2]: Leaving directory '/home/pi/sunxi-mali'
make[1]: Leaving directory '/home/pi/sunxi-mali'

sunxi-mali 설치

$ sudo make install
make -C lib install
make[1]: Entering directory '/home/pi/sunxi-mali/lib'
make -C mali install
make[2]: Entering directory '/home/pi/sunxi-mali/lib/mali'
make -C r3p0/armhf/x11/
make[3]: Entering directory '/home/pi/sunxi-mali/lib/mali/r3p0/armhf/x11'
install -m 644 libMali.so //usr/lib/
rm -f //usr/lib/libEGL.so.1.4 //usr/lib/libEGL.so.1 //usr/lib/libEGL.so
ln -sf libMali.so //usr/lib/libEGL.so.1.4
ln -sf libEGL.so.1.4 //usr/lib/libEGL.so.1
ln -sf libEGL.so.1 //usr/lib/libEGL.so
rm -f //usr/lib/libGLESv1_CM.so.1.1 //usr/lib/libGLESv1_CM.so.1 //usr/lib/libGLESv1_CM.so
ln -sf libMali.so //usr/lib/libGLESv1_CM.so.1.1
ln -sf libGLESv1_CM.so.1.1 //usr/lib/libGLESv1_CM.so.1
ln -sf libGLESv1_CM.so.1 //usr/lib/libGLESv1_CM.so
rm -f //usr/lib/libGLESv2.so.2.0 //usr/lib/libGLESv2.so.2 //usr/lib/libGLESv2.so
ln -sf libMali.so //usr/lib/libGLESv2.so.2.0
ln -sf libGLESv2.so.2.0 //usr/lib/libGLESv2.so.2
ln -sf libGLESv2.so.2 //usr/lib/libGLESv2.so
make[3]: Leaving directory '/home/pi/sunxi-mali/lib/mali/r3p0/armhf/x11'
make[2]: Leaving directory '/home/pi/sunxi-mali/lib/mali'
make[1]: Leaving directory '/home/pi/sunxi-mali/lib'
make -C include install
make[1]: Entering directory '/home/pi/sunxi-mali/include'
mkdir -p //usr//include/EGL
install -m 644 EGL/egl.h EGL/eglext.h //usr//include/EGL
mkdir -p //usr//include/EGL
install -m 644 EGL/eglplatform.h //usr//include/EGL/eglplatform.h
mkdir -p //usr//include/GLES
install -m 644 GLES/gl.h GLES/glext.h GLES/glplatform.h //usr//include/GLES
mkdir -p //usr//include/GLES2
install -m 644 GLES2/gl2.h GLES2/gl2ext.h GLES2/gl2platform.h //usr//include/GLES2
mkdir -p //usr//include/KHR
install -m 644 KHR/khrplatform.h //usr//include/KHR
make[1]: Leaving directory '/home/pi/sunxi-mali/include'

test

$ make test
cc -Wall -o test test.c -lEGL -lGLESv2

xf86-video-fbturbo 설치

$ sudo apt-get install xorg-dev
$ git clone https://github.com/ssvb/xf86-video-fbturbo.git
$ cd xf86-video-fbturbo
$ autoreconf -vi
$ ./configure --prefix=/usr
$ make
$ sudo make install

xorg.conf 복사

$ sudo cp xorg.conf /etc/X11/xorg.conf

BLE

$ sudo hcitool lescan
LE Scan ...
57:12:AD:C3:6C:D6 (unknown)
40:D8:1D:AC:2E:42 (unknown)
57:12:AD:C3:6C:D6 [LG] webOS UHD Box AN-US800K
62:83:F6:7E:66:EF (unknown)
62:83:F6:7E:66:EF (unknown)
728x90
728x90

출처

소스

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(void)
{

	VideoCapture cap("Zootopia.mp4");

	if (!cap.isOpened()) {
		cerr << "Camera open failed" << endl;
		return -1;
	}

	Mat frame, gray, blurred, edge;
	while (true) {
		//cap >> frame;
		cap.read(frame);

		if (frame.empty()) {
			break;
		}

		TickMeter tm;
		tm.start();

		cvtColor(frame, gray, COLOR_BGR2GRAY);
		bilateralFilter(gray, blurred, -1, 10, 5);
		Canny(blurred, edge, 50, 150);

		tm.stop();

		cout << tm.getTimeMilli() << "[ms]" << endl;
		
		imshow("frame", frame);
		imshow("blurred", blurred);
		imshow("edge", edge);
		
		if (waitKey(1) == 27) {
			break;
		}
	}

	return 0;
}

컴파일

$ g++ main.cpp -o main -std=c++11 `pkg-config --cflags --libs opencv4`

실행 (라즈베리파이3와 BPI-M2 ZERO의 실행 시간 비교)

pi@raspberrypi:~$ ./main          pi@bananapim2zero:~$ ./main
585.437[ms]                       1293.62[ms]                
514.686[ms]                       1309.49[ms]                
538.228[ms]                       1381.6[ms]                 
585.28[ms]                        1309.11[ms]                
525.669[ms]                       1298.43[ms]                
558.1[ms]                         1293.33[ms]                
501.31[ms]                        1291.57[ms]                
536.957[ms]                       1279.03[ms]                
546.125[ms]                       1279.27[ms]                
526.227[ms]                       1281.57[ms]                
592.775[ms]                       1319.66[ms]                
516.922[ms]                       1319.21[ms]                        
558.278[ms]                       1282.12[ms]                        
506.094[ms]                       1297.3[ms]                         
563.045[ms]                       1355.33[ms]                        
511.093[ms]                       1304.24[ms]                        
514.54[ms]                        1372.44[ms]                        
575.578[ms]                       1288.68[ms]                        
510.783[ms]                       1428.6[ms]                         
593.594[ms]                       1310.98[ms]                        
508.261[ms]                       1432.22[ms]                        
547.456[ms]                       1339.41[ms]                        
521.765[ms]                       1382.8[ms]                         
521.937[ms]                       1312.22[ms]                        
539.471[ms]                       1348.32[ms]                        
511.757[ms]                       1387.43[ms]                        
585.117[ms]                       1357.19[ms]  

실행 영상

728x90
728x90

출처

업데이트와 업그레이드

$ sudo apt-get update && sudo apt-get upgrade

OpenCV 4.1.1 관련 패키지 설치

OpenCV 빌드 관련 도구 설치

$ sudo apt-get install build-essential cmake unzip pkg-config

OpenCV 관련 라이브러리 설치

$ sudo apt-get install libjpeg-dev libpng-dev libtiff-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 zlib1g-dev

GTK 관련 라이브러리 설치

$ sudo apt-get install libgtk-3-dev

OpenCV 수치 최적화가 된 패키지 설치

$ sudo apt-get install libatlas-base-dev gfortran

Python3 설치

$ sudo apt-get install python3-dev

OpenCV 4.1.1 용 Python 3 가상 환경 구성

pip 설치

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python3 get-pip.py
Collecting pip
  Downloading https://files.pythonhosted.org/packages/30/db/9e38760b32e3e7f40cce46dd5fb107b8c73840df38f0046d8e6514e675a1/pip-19.2.3-py2.py3-none-any.whl (1.4MB)
     |████████████████████████████████| 1.4MB 768kB/s 
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Uninstalling pip-8.1.1:
      Successfully uninstalled pip-8.1.1
Successfully installed pip-19.2.3

virtualenv, virtualenvwrapper 설치

$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/get-pip.py ~/.cache/pip

python3, virtualenv 환경설정

$ echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.profile
$ echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.profile
$ echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.profile
$ echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.profile
$ source ~/.profile

가상환경을 만들고, OpenCV 4.1.1 관련 패키지 추가

$ mkvirtualenv cv -p python3
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/pi/.virtualenvs/cv/bin/python3
Also creating executable in /home/pi/.virtualenvs/cv/bin/python
Installing setuptools, pip, wheel...
done.
virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/cv/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/cv/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/cv/bin/preactivate
virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/cv/bin/postactivate
virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/cv/bin/get_env_details

workon 명령을 사용하여 cv 환경에 있는지 확인

pi@raspberrypi:~$ workon cv
(cv) pi@raspberrypi:~$ 

SWAP 사이즈 늘리기

현재 사용중인 SWAP 사이즈 확인

$ free -h
              total        used        free      shared  buff/cache   available
Mem:           495M        126M        263M        396K        104M        346M
Swap:          247M        152M         94M
$  sudo swapon --show
NAME       TYPE       SIZE  USED PRIO
/dev/zram0 partition 61.9M 38.1M    5
/dev/zram1 partition 61.9M 38.2M    5
/dev/zram2 partition 61.9M 38.1M    5
/dev/zram3 partition 61.9M 38.2M    5

Swap File 파일 만들기 (2가지 방법)

방법1

$ sudo fallocate -l 2G /swapfile

방법2

$ sudo dd if=/dev/zero of=/swapfile bs=128M count=16
16+0 records in
16+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 138.741 s, 15.5 MB/s

Swap File 파일 읽고 쓰기 권한 병경

$ sudo chmod 600 /swapfile

mkswap 도구를 사용하여 Linux 스왑 파일로 설정

$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=2cb87e99-2b39-4f99-9c05-46e5012baef5

스왑 파일을 활성화

$ sudo swapon /swapfile

Linux 부팅시 스왑파일 자동으로 사용하도록 적용

/etc/fstab 파일 열어서 내용 추가

$ sudo vi /etc/fstab

추가될 내용

/swapfile swap swap defaults 0 0

확인

$ sudo swapon --show
NAME       TYPE       SIZE  USED PRIO
/dev/zram0 partition 61.9M   38M    5
/dev/zram1 partition 61.9M   38M    5
/dev/zram2 partition 61.9M   38M    5
/dev/zram3 partition 61.9M 38.1M    5
/swapfile  file         2G    0B   -1
$ free -h
              total        used        free      shared  buff/cache   available
Mem:           495M        132M        122M        556K        239M        340M
Swap:          2.2G        151M        2.1G

numpy 파이썬 패키지 설치(OpenCV관련 수학 함수 모음)

pi@raspberrypi:~$ workon cv
(cv) pi@raspberrypi:~$ pip install numpy
Collecting numpy
  Created wheel for numpy: filename=numpy-1.17.1-cp35-cp35m-linux_armv7l.whl size=8686923 sha256=2628ac3cf647d10ebd10bc9c1eab6defd408d23f7d997728dc1f8b231f8a53df
  Stored in directory: /home/pi/.cache/pip/wheels/ba/05/2b/885479a25e17d366187c96094978de4807cac569ab52564de2
Successfully built numpy
Installing collected packages: numpy
Successfully installed numpy-1.17.1
(cv) pi@raspberrypi:~$ python
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> quit()

OpenCV 4.1.1 다운로드

OpenCV 4.1.1 소스 다운로드

$ cd ~
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.1.1.zip
$ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.1.1.zip

압축풀기

$ unzip opencv.zip
$ unzip opencv_contrib.zip

디렉토리명 변경

$ mv opencv-4.1.1 opencv
$ mv opencv_contrib-4.1.1 opencv_contrib

OpenCV 컴파일

CMake 실행

$ workon cv
$ cd ~/opencv
$ mkdir build
$ cd build
$ echo $(which python3)
/usr/bin/python3
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
      -D ENABLE_NEON=ON \
      -D ENABLE_VFPV3=ON \
      -D BUILD_TESTS=OFF \
      -D OPENCV_ENABLE_NONFREE=ON \
      -D INSTALL_PYTHON_EXAMPLES=OFF \
      -D OPENCV_GENERATE_PKGCONFIG=YES \
      -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \
      -D BUILD_EXAMPLES=OFF ..
 
... 생략 ...

-- General configuration for OpenCV 4.1.1 =====================================
--   Version control:               unknown
-- 
--   Extra modules:
--     Location (extra):            /home/pi/opencv_contrib/modules
--     Version control (extra):     unknown
-- 
--   Platform:
--     Timestamp:                   2019-09-04T04:59:12Z
--     Host:                        Linux 3.4.113-sun8i armv7l
--     CMake:                       3.5.1
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/make
--     Configuration:               RELEASE
-- 
--   CPU/HW features:
--     Baseline:                    VFPV3 NEON
--       requested:                 DETECT
--       required:                  VFPV3 NEON
-- 
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ Compiler:                /usr/bin/c++  (ver 5.4.0)
--     C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):      -Wl,--gc-sections  
--     Linker flags (Debug):        -Wl,--gc-sections  
--     ccache:                      NO
--     Precompiled headers:         YES
--     Extra dependencies:          dl m pthread rt
--     3rdparty dependencies:
-- 
--   OpenCV modules:
--     To be built:                 aruco bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc line_descriptor ml objdetect optflow phase_unwrapping photo plot python3 quality reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab xfeatures2d ximgproc xobjdetect xphoto
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 cnn_3dobj cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv hdf java js matlab ovis python2 sfm viz
--     Applications:                perf_tests apps
--     Documentation:               NO
--     Non-free algorithms:         YES
-- 
--   GUI: 
--     GTK+:                        YES (ver 3.18.9)
--       GThread :                  YES (ver 2.48.2)
--       GtkGlExt:                  NO
--     VTK support:                 NO
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.8)
--     JPEG:                        /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver 80)
--     WEBP:                        build (ver encoder: 0x020e)
--     PNG:                         /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.2.54)
--     TIFF:                        /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 / 4.0.6)
--     JPEG 2000:                   build (ver 1.900.1)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
-- 
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      YES
--       avcodec:                   YES (56.60.100)
--       avformat:                  YES (56.40.101)
--       avutil:                    YES (54.31.100)
--       swscale:                   YES (3.1.101)
--       avresample:                NO
--     GStreamer:                   NO
--     v4l/v4l2:                    YES (linux/videodev2.h)
-- 
--   Parallel framework:            pthreads
-- 
--   Trace:                         YES (with Intel ITT)
-- 
--   Other third-party libraries:
--     Lapack:                      NO
--     Eigen:                       NO
--     Custom HAL:                  YES (carotene (ver 0.0.1))
--     Protobuf:                    build (3.5.1)
-- 
--   OpenCL:                        YES (no extra features)
--     Include path:                /home/pi/opencv/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
-- 
--   Python 3:
--     Interpreter:                 /home/pi/.virtualenvs/cv/bin/python3 (ver 3.5.2)
--     Libraries:                   /usr/lib/arm-linux-gnueabihf/libpython3.5m.so (ver 3.5.2)
--     numpy:                       /home/pi/.virtualenvs/cv/lib/python3.5/site-packages/numpy/core/include (ver 1.17.1)
--     install path:                lib/python3.5/site-packages/cv2/python-3.5
-- 
--   Python (for build):            /home/pi/.virtualenvs/cv/bin/python3
-- 
--   Java:                          
--     ant:                         NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
-- 
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
-- 
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/opencv/build

CPU 코어 개수 확인

$ grep -c processor /proc/cpuinfo
4

OpenCV 컴파일

$ make -j4

OpenCV 설치

$ sudo make install
$ sudo ldconfig

OpenCV 4를 Python 3 가상 환경에 복사(소프트링크)

$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
$ ln -s /usr/local/lib/python3.5/site-packages/cv2/python-3.5/cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so
$ cd ~

OpenCV 설치 확인

파이썬

$ python
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.1'
>>> exit()

C++

#include "opencv2/opencv.hpp"
 
using namespace cv;
using namespace std;
 
int main( int argc, char** argv )
{
  cout << "OpenCV version : " << CV_VERSION << endl;
  cout << "Major version : " << CV_MAJOR_VERSION << endl;
  cout << "Minor version : " << CV_MINOR_VERSION << endl;
  cout << "Subminor version : " << CV_SUBMINOR_VERSION << endl;
}

$ g++ version_check.cpp -o version_check -std=c++11 `pkg-config --cflags --libs opencv4`
$ ./version_check 
OpenCV version : 4.1.1
Major version : 4
Minor version : 1
Subminor version : 1
728x90

+ Recent posts