728x90

M5Stack Korea인 WIZnet에서 운영하는 메이커 컨텐츠 커뮤니티 사이트의 후원을 받아서 작성되었습니다.

출처

M5Stack : BLE 통신 - App Inventor 2 과 BLE 통신

M5Stack를 이용해서 BLE 서버를 만들고 App Inventor를 이용해서 안드로이드 용 BLE 클라이언트를 만들어 보았습니다.

BLE통신을 간단하게 설명하면, BLE 서버는 BLE 이름, UUID(고유주소), 거리 정보를 송출하고, 이 정보로 BLE 클라이언트가 접속하면, BLE 기기는 다른 BLE 클라이언트가 접속하지 않도록, BLE 이름을 더 이상 송출하지않고, 서비스목록과 해당 서비스의 특성 정보를 송출합니다. BLE 클라이언트는 필요한 서비스와 특성을 찾아서 용도에 따라 다르겠지만 여기 예제에서는 간단하게 문자열을 주고 받도록 했습니다.

M5Stack BLE 서버 만들기

서비스 UUID, 특성 UUID를 미리 정해야 합니다. 예제 소스에는 상수로 미리 만들어 두었습니다.

BLE 접속상태의 이벤트로 받기 위해서 BLEServerCallbacks 클래스를 상속받아서 구현하고, 서비스의 특성을 이용해서 문자열 수신하는 이벤트를 받기 위해서 BLECharacteristicCallbacks 클래스를 상속 받아서 구현 합니다.

전체 소스

#include <M5Stack.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      M5.Lcd.println("connect");
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      M5.Lcd.println("disconnect");
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
  void onRead(BLECharacteristic *pCharacteristic) {
    M5.Lcd.println("read");
    pCharacteristic->setValue("Hello World!");
  }

  void onWrite(BLECharacteristic *pCharacteristic) {
    M5.Lcd.println("write");
    std::string value = pCharacteristic->getValue();
    M5.Lcd.println(value.c_str());
  }
};

void setup() {
  Serial.begin(115200);
  M5.begin();
  M5.setWakeupButton(BUTTON_A_PIN);
  M5.Lcd.println("BLE start.");
  m5.Speaker.mute();

  BLEDevice::init("m5-stack"); // BLD 이름 설정
  BLEServer *pServer = BLEDevice::createServer(); // BLE 서버 생성
  pServer->setCallbacks(new MyServerCallbacks()); // BLE 상태 콜백 함수 등록 (접속 이벤트 처리)
  BLEService *pService = pServer->createService(SERVICE_UUID); // 서비스 UUID 등록
  pCharacteristic = pService->createCharacteristic( 
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE |
                                         BLECharacteristic::PROPERTY_NOTIFY |
                                         BLECharacteristic::PROPERTY_INDICATE
                                       ); // BLE 특성 등록
  pCharacteristic->setCallbacks(new MyCallbacks()); // BLE 문자열 수신 콜백 함수 등록
  pCharacteristic->addDescriptor(new BLE2902());

  pService->start(); // BLE 서버 실행 -> BLE 이름 노출
  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start(); 
}

void loop() {
  if(M5.BtnA.wasPressed()) {
    M5.powerOFF();
  }
  if (deviceConnected) { // BLE가 연결되어 있는 경우
    if(M5.BtnB.wasPressed()) { // M5Stack의 B버튼이 선택한 경우
      M5.Lcd.println("Button B pressed!");
      pCharacteristic->setValue("Button B pressed!"); // BLE 클라이언트에 전달할 문자열 설정
      pCharacteristic->notify(); // BLE 클라이언트에 문자열 전달
    }
  }
  M5.update();
}

App Inventor 2 : BLE 클라이언트 만들기

App Inventor는 MIT에서 만든 블럭 형태의 코딩으로 안드로이드 어플을 쉽게 만들 수 있어서 IOT 개발시 많이 사용됩니다. 기본적으로 BT 통신만 지원했고, BLE 통신은 지원하지 않았지만, 최근에 확장 라이브러리를 통해서 지원하고 있습니다. BLE 확장 라이브러리를 다운 받아서 Import 하시면 BLE 통신을 구현 할 수 있습니다.

예제는 BLE 목록을 조회하고, 조회된 목록에서 M5Stack를 선택하여 BLE 서버에 접속하고, 미리 정해둔 서비스와 특성을 등록하고, M5Stack에서 B버튼을 선택시 전달 받은 문자열을 텍스트박스에 출력하고, 안드로이드 어플에서 문자열을 M5Stack에 전송 합니다.

App Inventor BLE 확장 라이브러리 다운로드

http://appinventor.mit.edu/extensions 에 접속하셔서 BluetoothLE.aix 파일을 다운 받습니다.

App Inventor 프로젝트 만들기 (http://ai2.appinventor.mit.edu/)

http://ai2.appinventor.mit.edu/ 접속해서 [새 프로젝트 시작하기...] 선택합니다.

프로젝트 이름 설정

App Inventor BLE 확장 라이브러리 Import

팔레트 -> Extension -> import extension 에서 파일 선택버튼을 누른 후 위에서 다운받은 bluetoothLE.aix 를 선택해줍니다.

App Inventor 화면 구성

전역 변수 선언 (서비스, 특성 UUID 정의)

[버튼1]을 선택해서 BLE 목록 조회

BLE 목록이 조회되면 목록를 리스트 박스(목록_선택1)에 담기

BLE 목록에서 접속하려고 하는 BLE 기기 선택했을 경우 BLE 주소 UUID(리스트의 문자열 1에서 17의 문자열)를 가지고 와서 해당 BLE에 접속 시도

BLE 기기에 접속하면 BLE로 문자열 수신 이벤트를 받기 위해서 서비스와 특성 등록

BLE 기기에서 문자열을 수신 했을 경우 텍스트 박스(텍스트_상자1)에 수신한 문자열 출력

[버튼3]을 선택해서 텍스트 박스(텍스트_상자2)의 문자열을 BLE기기에 전송

[버튼2]을 선택해서 BLE 연결끊기

App Inventor 전체 소스

실행 영상

M5Stack 물품 구매는 <네이버 검색/쇼핑에서 M5StackKorea>를 검색하시거나, M5Stack 공식 파트너인 <위즈네트 쇼핑몰: Shop.wiznet.io> 으로 접속하세요.

728x90
728x90

M5Stack Korea인 WIZnet에서 운영하는 메이커 컨텐츠 커뮤니티 사이트의 후원을 받아서 작성되었습니다.

출처

M5Stack : PWM 이용해서 LED 밝기 조절

M5Go의 PORT A의 PWM을 이용해서 LED의 밝기 조절하는 예제를 실행해보았습니다. M5Stack의 A버튼을 선택하면 밝기를 높여주고, B버튼을 선택하면 어둡게 해주는 예제입니다.

M5Go Port

PORT A : GPIO 21, 22 pin
PORT B : GPIO 26, 36 pin
PORT C : GPIO 16, 17 pin

소스

#include <M5Stack.h>

int pwmChannel = 1;
int ledPin = 21;
int ledState = 0;

void setup() {
  M5.begin(true, false, true);
  M5.Lcd.setTextFont(4);
  M5.Lcd.setCursor(70, 100);
  M5.Lcd.print("PWM Example");

  ledcSetup(pwmChannel, 10000, 8);
  ledcAttachPin(ledPin, pwmChannel);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (M5.BtnA.isPressed()) {
    ledState += 5;
    if (ledState > 255)
      ledState = 255;
    ledcWrite(pwmChannel, ledState);
    delay(25);
  }
  if (M5.BtnB.isPressed()) {
    ledState -= 5;
    if (ledState < 1)
      ledState = 0;
    ledcWrite(pwmChannel, ledState);
    delay(25);
  }
  M5.update();
}

실행

M5Stack 물품 구매는 <네이버 검색/쇼핑에서 M5StackKorea>를 검색하시거나, M5Stack 공식 파트너인 <위즈네트 쇼핑몰: Shop.wiznet.io> 으로 접속하세요.

728x90
728x90

출처

Raspberry Pi 3와 4 : OpenCV - 캐니 에지(Canny Edge) 속도 비교

캐니 에지(Canny Edge)는 1986년. John F. Canny 에 의해 개발된 알고리즘으로 윤곽을 원래 영상의 회색물질과 관련된 모든 에지(Edge)들을 제거하는 함수 입니다. Raspberry Pi 3와 4 실행해서 속도 비교를 해보았는데, 실행 결과를 보면 라즈베리파이3에서 실행 한것 보다 2배 약간 못되게 빠르게 동작하고 있습니다.

소스

#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 `pkg-config --cflags --libs opencv4`

실행 (라즈베리파이3와 라즈베리파이4의 실행 시간 비교)

왼쪽은 라즈베리파이3에서 오른쪽은 라즈베리파이4에서 실행한 결과 입니다. 결과를 보시면 라즈베리파이4에서 실행결과가 라즈베리파이3에서 실행 한것 보다 2배 약간 못되게 빠르게 동작하고 있습니다.

pi@raspberrypi:~$ ./main          pi@raspberrypi:~ $ ./main
585.437[ms]                       293.316[ms]              
514.686[ms]                       258.292[ms]              
538.228[ms]                       257.687[ms]              
585.28[ms]                        255.691[ms]              
525.669[ms]                       272.336[ms]              
558.1[ms]                         255.374[ms]              
501.31[ms]                        263.007[ms]              
536.957[ms]                       256.362[ms]              
546.125[ms]                       258.705[ms]              
526.227[ms]                       259.988[ms]              
592.775[ms]                       254.891[ms]              
516.922[ms]                       255.25[ms]               
558.278[ms]                       260.084[ms]              
506.094[ms]                       261.073[ms]              
563.045[ms]                       256.056[ms]              
511.093[ms]                       270.214[ms]              
514.54[ms]                        264.756[ms]              
575.578[ms]                       256.604[ms]              
510.783[ms]                       256.996[ms]              
593.594[ms]                       268.694[ms]              
508.261[ms]                       257.855[ms]              
547.456[ms]                       259.229[ms]              
521.765[ms]                       255.19[ms]               
521.937[ms]                       255.639[ms]              
539.471[ms]                       255.995[ms]              
511.757[ms]                       258.853[ms]              
585.117[ms]                       256.869[ms] 

실행 영상

728x90
728x90

출처

다운로드 디렉토리 생성

$ mkdir -p /home/bluesanta/torrent/torrent.temp
$ mkdir -p /home/bluesanta/torrent/torrent.auto
$ sudo chown -R debian-transmission:debian-transmission /home/bluesanta/torrent
$ mkdir -p /bluesanta/torrent/torrent.incoming
$ sudo chown -R debian-transmission:debian-transmission /bluesanta/torrent/torrent.incoming

Transmission 설치

$ sudo apt-get install transmission-daemon

환경 설정 (/etc/transmission-daemon/settings.json)

$ sudo vi /etc/transmission-daemon/settings.json

서비스가 종료된 경우만 수정 가능

IP filter 설정

    "blocklist-enabled": true,
    "blocklist-url": "http://list.iblocklist.com/?list=bt_level1&fileformat=p2p&archiveformat=gz",

외부 웹 접속 설정

    "rpc-authentication-required": true, 
    "rpc-password": "asdf1234",
    "rpc-port": 9091,
    "rpc-url": "/transmission/",
    "rpc-username": "trans",
    "rpc-whitelist": "127.0.0.1,192.168.0.1,192.168.0.1",
    "rpc-whitelist-enabled": true,

최대 다운로드, 최대 업로드 관련 설정

"speed-limit-down-enabled": true 일 경우에만 speed-limit-down 가 적용
"speed-limit-up-enabled": true 일 경우에만 speed-limit-up 가 적용

    "speed-limit-down": 0,
    "speed-limit-down-enabled": false,
    "speed-limit-up": 100,
    "speed-limit-up-enabled": true,

다운로드 경로 설정

    "download-dir": "/bluesanta/torrent/torrent.incoming",
    "incomplete-dir": "/home/bluesanta/torrent/torrent.temp",
    "incomplete-dir-enabled": true,
    "watch-dir": "/home/bluesanta/torrent/torrent.auto",
    "watch-dir-enabled": true,
    "trash-original-torrent-files": true,

서비스 시작

$ sudo service transmission-daemon start

서비스 종료

$ sudo service transmission-daemon stop

서비스 상태 확인

$ sudo service transmission-daemon status
● transmission-daemon.service - Transmission BitTorrent Daemon
   Loaded: loaded (/lib/systemd/system/transmission-daemon.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2019-07-07 11:25:31 KST; 1h 25min ago
  Process: 3902 ExecStop=/bin/kill -s STOP $MAINPID (code=exited, status=0/SUCCESS)
 Main PID: 3919 (transmission-da)
   Status: "Uploading 327.56 KBps, Downloading 3761.33 KBps."
    Tasks: 4 (limit: 4915)
   CGroup: /system.slice/transmission-daemon.service
           └─3919 /usr/bin/transmission-daemon -f --log-error
 
 7월 07 11:25:30 bluesanta-ubuntu systemd[1]: Starting Transmission BitTorrent Daemon...
 7월 07 11:25:31 bluesanta-ubuntu systemd[1]: Started Transmission BitTorrent Daemon.
 7월 07 11:25:32 bluesanta-ubuntu transmission-daemon[3919]: [2019-07-07 11:25:32.024] UDP Failed to set receive buffer:
 7월 07 11:25:32 bluesanta-ubuntu transmission-daemon[3919]: [2019-07-07 11:25:32.024] UDP Failed to set send buffer: re

웹 접속

transmisson-remote-gui

https://code.google.com/p/transmisson-remote-gui/

728x90
728x90

Raspberry Pi 4

Raspberry Pi 4 전원

Raspberry Pi 4에서 사용하는 전원은 5.1v 3A로 PC의 USB의 전원으로 연결하면 정상적으로 운영이 되지 않는 것 같습니다.

OS설치 (NOOBS 설치)

아직 테스트가 더 필요하지만, 현재 배포 되는 Raspbian (2019-06-20 배포판) 의 이미지(img파일)파일 설치는 아직 설치가 안되는 것 같고, NOOBS (2019-06-24 배포판)으로 설치해보았습니다.

Micro HDMI

Micro HDMI 어댑터를 구입해서 기존에 사용하던 HDMI케이블에 연결해서 사용하면 문제 없이 사용이 가능했습니다.

한글폰트 설치

$ sudo apt install fonts-unfonts-core

RDP (원격 데스크톱) 설치

$ sudo apt-get install xrdp
$ sudo apt-get install xorgxrdp

YouTube 시청

728x90
728x90

본 체험 제품은 아이씨뱅큐㈜ 에서 진행하는 무상 체험단 활동으로 작성한 것입니다.

 

지니어스 키트의 경우 레고 마운트가 가능합니다.

 

마이크로비트 지니어스키트 공식 구입처 : 아이씨뱅큐 http://www.icbanq.com/
아이씨뱅큐 공식 카페 : http://cafe.naver.com/icbanq
아이씨뱅큐 공식 블로그 : http://blog.naver.com/icbanq
마이크로비트 공식 카페 : http://cafe.naver.com/bbcmicro
나도메이커 유튜브 채널 : https://www.youtube.com/user/ICbanQ

728x90
728x90

출처

Raspberry Pi 4 개봉기

주문한지 3일만에 받았습니다.
외관상 크기는 이전과 동일하지만 기존 pi3 케이스는 사용 할 수가 없어서 같이 주문한 케이스와 방열판을 붙여 보았습니다.

Raspberry Pi 4 스펙

  • 1.5GHz 64 비트 쿼드 코어 ARM Cortex-A72 CPU (ARM v8, BCM2837)
  • 1GB, 2GB 또는 4GB RAM (LPDDR4)
  • 온보드 무선 LAN - 듀얼 밴드 802.11 b / g / n / ac
  • 온보드 Bluetooth 5.0, 저에너지 (BLE)
  • 2x USB 3.0 포트, 2x USB 2.0 포트
  • 기가비트 이더넷
  • Power-over-Ethernet (추가 Raspberry Pi PoE HAT가 필요함)
  • 40 핀 GPIO 헤더
  • 2 × 마이크로 HDMI 포트 (최대 4Kp60 지원)
  • H.265 (4Kp60 디코드)
  • H.264 (1080p60 디코드, 1080p30 인 코드)
  • OpenGL ES, 3.0 그래픽
  • DSI 디스플레이 포트, CSI 카메라 포트
  • 결합 된 3.5mm 아날로그 오디오 및 컴포지트 비디오 잭
  • 마이크로 SD 카드 슬롯
  • USB-C 전원

728x90
728x90

출처

불필요한 패키지 제거

$ sudo apt-get purge wolfram-engine
$ sudo apt-get purge libreoffice*
$ sudo apt-get clean
$ sudo apt-get autoremove

라즈비안(Raspberry pi OS)의 업데이트와 업그레이드

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

OpenCV 4.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

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 다운로드

OpenCV 4.1.0 소스 다운로드

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

압축풀기

$ unzip opencv.zip
$ unzip opencv_contrib.zip

디렉토리명 변경

$ mv opencv-4.1.0 opencv
$ mv opencv_contrib-4.1.0 opencv_contrib

OpenCV 4.1 용 Python 3 가상 환경 구성

pip 설치

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python3 get-pip.py
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pip
  Downloading https://files.pythonhosted.org/packages/5c/e0/be401c003291b56efc55aeba6a80ab790d3d4cece2778288d65323009420/pip-19.1.1-py2.py3-none-any.whl (1.4MB)
     |████████████████████████████████| 1.4MB 1.1MB/s 
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.1.1

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 관련 패키지 추가

$ 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:~$ 

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

pi@raspberrypi:~$ workon cv
(cv) pi@raspberrypi:~$ pip install numpy
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting numpy
  Using cached https://www.piwheels.org/simple/numpy/numpy-1.16.4-cp37-cp37m-linux_armv7l.whl
Installing collected packages: numpy
Successfully installed numpy-1.16.4
(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 컴파일

CMake 실행

$ cd ~/opencv
$ mkdir build
$ cd build
$ 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 BUILD_EXAMPLES=OFF ..
 
... 생략 ...
 
-- General configuration for OpenCV 4.1.0 =====================================
--   Version control:               unknown
-- 
--   Extra modules:
--     Location (extra):            /home/pi/opencv_contrib/modules
--     Version control (extra):     unknown
-- 
--   Platform:
--     Timestamp:                   2019-07-01T15:38:09Z
--     Host:                        Linux 4.19.50-v7+ armv7l
--     CMake:                       3.13.4
--     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 8.3.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 -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -mfp16-format=ieee -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 -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -mfp16-format=ieee -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 -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -mfp16-format=ieee -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 -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -mfpu=neon -mfp16-format=ieee -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.24.5)
--       GThread :                  YES (ver 2.58.3)
--       GtkGlExt:                  NO
--     VTK support:                 NO
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.11)
--     JPEG:                        /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver 62)
--     WEBP:                        build (ver encoder: 0x020e)
--     PNG:                         /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.6.36)
--     TIFF:                        /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 / 4.0.10)
--     JPEG 2000:                   build (ver 1.900.1)
--     OpenEXR:                     build (ver 1.7.1)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
-- 
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      YES
--       avcodec:                   YES (58.35.100)
--       avformat:                  YES (58.20.100)
--       avutil:                    YES (56.22.100)
--       swscale:                   YES (5.3.100)
--       avresample:                NO
--     GStreamer:                   NO
--     v4l/v4l2:                    YES (linux/videodev2.h)
-- 
--   Parallel framework:            pthreads
-- 
--   Trace:                         YES (built-in)
-- 
--   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.7.3)
--     Libraries:                   /usr/lib/arm-linux-gnueabihf/libpython3.7m.so (ver 3.7.3)
--     numpy:                       /home/pi/.virtualenvs/cv/lib/python3.7/site-packages/numpy/core/include (ver 1.16.4)
--     install path:                lib/python3.7/site-packages/cv2/python-3.7
-- 
--   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

SWAP 사이즈 늘리기

dphys-swapfile 편집

$ sudo vi /etc/dphys-swapfile

CONF_SWAPSIZE 값을 2024 (2GB)로 설정

# set size to absolute value, leaving empty (default) then uses computed value
#   you most likely don't want this, unless you have an special disk situation
# CONF_SWAPSIZE=100
CONF_SWAPSIZE=2048

dphys-swapfile 재실행

$ sudo /etc/init.d/dphys-swapfile stop
Stopping dphys-swapfile (via systemctl): dphys-swapfile.service.
$ sudo /etc/init.d/dphys-swapfile start
Starting dphys-swapfile (via systemctl): dphys-swapfile.service

OpenCV 컴파일

$ make -j4

OpenCV 설치

$ sudo make install
$ sudo ldconfig

SWAP 이전 사이즈 돌려놓기

1. CONF_SWAPSIZE를 100MB로 재설정
2. 스왑 서비스를 재시작

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

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

OpenCV 설치 확인

파이썬

$ workon cv
$ 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 cv2
>>> cv2.__version__
'4.1.0'
>>> 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++ opencv_check_version.cpp -o opencv_check_version `pkg-config --cflags --libs opencv4`
$ ./opencv_check_version 
OpenCV version : 4.1.0
Major version : 4
Minor version : 1
Subminor version : 0
728x90

+ Recent posts