2016年5月8日 星期日

Raspberry Pi: Real-Time Face Detection With Camera Module

since: 2016/05/08
update: 2016/05/08
reference:
1. openframeworks
2. I touchs: openFrameworks: Control The Raspberry Pi Camera Module

A. 功能測試: opencvHaarFinderExample
    // 單張照片臉部辨識
    $ cd /home/pi/of_v0.9.3/examples/addons/opencvHaarFinderExample
    $ make
    $ ./bin/opencvHaarFinderExample    // 結果


-----------------------------------------------------------------------------------------------
B. 功能測試: example-texture-mode
     // Camera Module
     $ cd /home/pi/of_v0.9.3/addons/
     $ git clone https://github.com/jvcleave/ofxRPiCameraVideoGrabber
     $ cd /home/pi/of_v0.9.3/addons/ofxRPiCameraVideoGrabber/example-texture-mode
     $ make
     $ ./bin/example-texture-mode

-----------------------------------------------------------------------------------------------

C. Face Detection With Camera Module
     1. addons.make
         ofxOpenCv
         ofxRPiCameraVideoGrabber

***********************************************

     2. main.cpp
#include "ofMain.h"
#include "ofApp.h"
#include "ofGLProgrammableRenderer.h"

int main()
{
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> _linesOfTheFile;
    ofBuffer _buffer = ofBufferFromFile("config.txt");
    for (auto line : _buffer.getLines()){
        _linesOfTheFile.push_back(line);
    }
   
    // local variables
    int _debug = ofToBool(_linesOfTheFile[1]);
    int _camWidth = ofToInt(_linesOfTheFile[4]);
    int _camHeight = ofToInt(_linesOfTheFile[7]);
    bool _fullScreen = ofToBool(_linesOfTheFile[10]);
   
    // show debug message
    if(_debug) {
        ofLog() << "****** main()";
        ofLog() << "debug: " << _debug;
        ofLog() << "OpenGL width: " << _camWidth;
        ofLog() << "OpenGL height: " << _camHeight;
        ofLog() << "fullScreen: " << _fullScreen;
    }
   
    ofGLESWindowSettings settings;
    //settings.width = 320;
    //settings.height = 240;

    settings.width = _camWidth;
    settings.height = _camHeight;
   
    settings.setGLESVersion(2);
    ofCreateWindow(settings);
   
    ofRunApp( new ofApp());
}


***********************************************

     3. ofApp.h
#pragma once

#include "ofMain.h"
#include "TerminalListener.h"
#include "RPiVideoGrabber.h"
#include "ofxCvHaarFinder.h"

class ofApp : public ofBaseApp, public KeyListener{

    public:

        void setup();
        void update();
        void draw();
        void keyPressed(int key);

    void onCharacterReceived(KeyListenerEventData& e);
    TerminalListener consoleListener;
   
    //wrapper class for drop-in replacement of ofVideoGrabber
    RPiVideoGrabber vidGrabber;
   
    //@add for CvHaarFinder
    ofxCvHaarFinder finder;
    ofImage grayImg;
    //ofImage img;

    //@add second record
    float countROI;
    long readSeconds; // read from totalSeconds record file
    long writeSeconds; // write to totalSeconds record file
    long latestSeconds; // latestSeconds
   
    // config file
    bool debug;
    int camWidth;
    int camHeight;
    bool fullScreen;
    int frameRate;
    bool concurrentVisit;
    float minROI;
    float maxROI;
    float weightROI;
    string recordFile;
};


***********************************************

    4. ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------

void ofApp::setup()
{
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> linesOfTheFile;
    ofBuffer buffer = ofBufferFromFile("config.txt");
    for (auto line : buffer.getLines()){
        linesOfTheFile.push_back(line);
    }
    //for (int i = 0; i < linesOfTheFile.size(); i++) {
    //    ofLog(OF_LOG_VERBOSE, "cur.width = %s", linesOfTheFile[i].c_str());
    //}

   
    debug = ofToBool(linesOfTheFile[1]);
    camWidth = ofToInt(linesOfTheFile[4]);
    camHeight = ofToInt(linesOfTheFile[7]);
    fullScreen = ofToBool(linesOfTheFile[10]);
    frameRate = ofToInt(linesOfTheFile[13]);
    concurrentVisit = ofToBool(linesOfTheFile[16]);
    minROI = ofToFloat(linesOfTheFile[19]);
    maxROI = ofToFloat(linesOfTheFile[22]);
    weightROI = ofToFloat(linesOfTheFile[25]);
    recordFile = linesOfTheFile[28];
   
    if(debug)
    {
        ofLog() << "****** ofApp::setup()";
        ofLog() << "debug: " << debug;
        ofLog() << "camWidth: " << camWidth;
        ofLog() << "camHeight: " << camHeight;
        ofLog() << "fullScreen: " << fullScreen;
        ofLog() << "frameRate: " << frameRate;
        ofLog() << "concurrentVisit: " << concurrentVisit;
        ofLog() << "minROI: " << minROI;
        ofLog() << "maxROI: " << maxROI;
        ofLog() << "weightROI: " << weightROI;
        ofLog() << "recordFile: " << recordFile;
    }
   
    // read totalSeconds record file
    vector<string> totalSecondsFile;
    ofBuffer sbuffer = ofBufferFromFile(recordFile);
    for (auto line : sbuffer.getLines()){
        totalSecondsFile.push_back(line);
    }
   
    readSeconds = ofToFloat(totalSecondsFile[0]);
   
    if(debug)
    {
        ofLog() << "****** read totalSeconds record file";
        ofLog() << "readSeconds: " << readSeconds;
    }
   
    //ofSetFrameRate(5);
    ofSetFrameRate(frameRate);
   
    //allows keys to be entered via terminal remotely (ssh)
    consoleListener.setup(this);
   
    //vidGrabber.setDesiredFrameRate(30);
    vidGrabber.setDesiredFrameRate(frameRate);
    vidGrabber.initGrabber(camWidth, camHeight);
   
    //@add for CvHaarFinder
    //img.load("test.jpg");

    finder.setup("haarcascade_frontalface_default.xml");
    //finder.findHaarObjects(img);
}

//--------------------------------------------------------------
void ofApp::update()
{
    ofBackground(100, 100, 100);
    vidGrabber.update();
   
    if(vidGrabber.isFrameNew())
    {
        //ofPixels & pixels = vidGrabber.getPixels();
        //finder.findHaarObjects(pixels);

        grayImg.setFromPixels(vidGrabber.getPixels());
        grayImg.setImageType(OF_IMAGE_GRAYSCALE);

       
        finder.findHaarObjects(grayImg);
    }
}


//--------------------------------------------------------------
void ofApp::draw(){

    ofSetHexColor(0xffffff);
    //ofSetColor(ofColor::white);
   
    vidGrabber.draw(0, 0);
   
    //@add for CvHaarFinder
    //img.draw(0, 0);

    ofNoFill();
   
    for(unsigned int i = 0; i < finder.blobs.size(); i++) {
       
        ofRectangle cur = finder.blobs[i].boundingRect;
       
        //if(debug){
        //    ofLog(OF_LOG_VERBOSE, "ROI width = %f", cur.width);
        //    ofLog(OF_LOG_VERBOSE, "ROI height = %f", cur.height);
        //}

       
        //if((cur.width >= 50.0 && cur.width <= 150.0) &&
        //   (cur.height >= 50.0 && cur.height <= 150.0)) {

        if((cur.width >= (minROI * camWidth) && cur.width <= (maxROI * camWidth)) &&
           (cur.height >= (minROI * camWidth) && cur.height <= (maxROI * camWidth))) {
            countROI++;
            ofSetColor(255, 0, 0); // red color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
           
            if(debug) {
                ofSetColor(ofColor::yellow);
                ofDrawBitmapString("ROI = " + ofToString(cur.width) + " x " + ofToString(cur.height), camWidth/5, camHeight/1.02);
            }
            // not concurrent Visit
            if(!concurrentVisit){
                break;
            }
        }
        else {
            ofSetColor(0, 0, 255); // blue color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
        }
    }
   
    // writeSeconds
    writeSeconds = readSeconds + (countROI / frameRate * weightROI); // weightROI: for calibrate detect missing
   

    if(writeSeconds > latestSeconds){
        // Write data
        if(debug) {
            // totalSeconds record file
            ofLog() << "****** write totalSeconds record file: " << writeSeconds;
        }
       
        ofBuffer secondsBuff;
        secondsBuff.set(ofToString(writeSeconds));
        bool fileWritten = ofBufferToFile(recordFile, secondsBuff);
       
        latestSeconds = writeSeconds;
    }
   
    if(debug){
        // show message
        ofSetColor(ofColor::white);
        ofDrawBitmapString("total seconds: " + ofToString(writeSeconds), camWidth/5, camHeight/1.2);
        ofDrawBitmapString(ofToString(minROI * camWidth) + " <= ROI <= " + ofToString(maxROI * camWidth), camWidth/5, camHeight/1.1);
    }
   
    ofSetColor(100, 100, 100);
}

//--------------------------------------------------------------
void ofApp::keyPressed  (int key)
{
    ofLog(OF_LOG_VERBOSE, "%c keyPressed", key);
    //if (key == 'e')
    //{
    //}
    //@add for VideoGrabber

    if(key == 'd' || key == 'D'){
        debug = !debug;
    }
}

void ofApp::onCharacterReceived(KeyListenerEventData& e)
{
    keyPressed((int)e.character);
}


***********************************************

   5. bin/data 資料夾
        a. haarcascade_frontalface_default.xml // from ofxOpenCv

        b. totalSeconds.txt // record second
            0

        c. config.txt // config file
# debug (true/false)
false

# cam width (int)
320

# cam height (int)
240

# full screen (true/false)
false

# frame rate (int)
5

# concurrent visit (true/false)

false

# minimum width ratio of ROI(region of interest) (float)
0.125

# maximum width ratio of ROI(region of interest) (float)
0.5

# weight of ROI (float)
1.0

# recordFile (string)
totalSeconds.txt

Raspberry Pi: Real-Time Face Detection With USB Webcam & GPIO(I2C)

since: 2016/05/08
update: 2016/08/11
reference:
1. openframeworks
2. GitHub - kashimAstro/ofxGPIO
3. I touchs: Raspberry Pi: Connected Arduino Using I2C


A. 功能測試: opencvHaarFinderExample

    // 單張照片臉部辨識
    $ cd /home/pi/of_v0.9.3/examples/addons/opencvHaarFinderExample
    $ make
    $ ./bin/opencvHaarFinderExample    // 結果

-----------------------------------------------------------------------------------------------

B. 功能測試: videoGrabberExample
    // USB Web Cam
    $ cd /home/pi/of_v0.9.3/examples/video/videoGrabberExample
    $ make
    $ ./bin/videoGrabberExample

    // 結果

-----------------------------------------------------------------------------------------------

C. Face Detection With USB Webcam
    1. addons.make
        ofxOpenCv

***********************************************

    2. main.cpp
#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> _linesOfTheFile;
    ofBuffer _buffer = ofBufferFromFile("config.txt");
    for (auto line : _buffer.getLines()){
        _linesOfTheFile.push_back(line);
    }
   
    // local variables
    int _debug = ofToBool(_linesOfTheFile[1]);
    int _camWidth = ofToInt(_linesOfTheFile[4]);
    int _camHeight = ofToInt(_linesOfTheFile[7]);
    bool _fullScreen = ofToBool(_linesOfTheFile[10]);
   
    // show debug message
    if(_debug) {
        ofLog() << "****** main()";
        ofLog() << "debug: " << _debug;
        ofLog() << "OpenGL width: " << _camWidth;
        ofLog() << "OpenGL height: " << _camHeight;
        ofLog() << "fullScreen: " << _fullScreen;
    }

    // fullScreen
    if(_fullScreen) {
        // set camWidth & camHeight as window's
        ofSetupOpenGL(_camWidth, _camHeight, OF_FULLSCREEN);
    }
    // window
    else {
        // set camWidth & camHeight as window's
        ofSetupOpenGL(_camWidth, _camHeight, OF_WINDOW);
    }
   
    // this kicks off the running of my app
    // can be OF_WINDOW or OF_FULLSCREEN
    // pass in width and height too:

    ofRunApp(new ofApp());
}


***********************************************

    3. ofApp.h
#pragma once

#include "ofMain.h"
#include "ofxCvHaarFinder.h"

class ofApp : public ofBaseApp{

    public:
        void setup();
        void update();
        void draw();

        void keyPressed(int key);
        void keyReleased(int key);
        void mouseMoved(int x, int y );
        void mouseDragged(int x, int y, int button);
        void mousePressed(int x, int y, int button);
        void mouseReleased(int x, int y, int button);
        void mouseEntered(int x, int y);
        void mouseExited(int x, int y);
        void windowResized(int w, int h);
        void dragEvent(ofDragInfo dragInfo);
        void gotMessage(ofMessage msg);
   
        //@add for VideoGrabber
        ofVideoGrabber vidGrabber;

        //@add for CvHaarFinder
        //ofImage img;

        ofxCvHaarFinder finder;
   
        //@add second record
        float countROI;
        long readSeconds; // read from totalSeconds record file
        long writeSeconds; // write to totalSeconds record file
        long latestSeconds; // latestSeconds
   
        // config file
        bool debug;
        int camWidth;
        int camHeight;
        bool fullScreen;
        int frameRate;
        bool concurrentVisit;
        float minROI;
        float maxROI;
        float weightROI;
        string recordFile;
};


***********************************************

    4. ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> linesOfTheFile;
    ofBuffer buffer = ofBufferFromFile("config.txt");
    for (auto line : buffer.getLines()){
        linesOfTheFile.push_back(line);
    }
    //for (int i = 0; i < linesOfTheFile.size(); i++) {
    //    ofLog(OF_LOG_VERBOSE, "cur.width = %s", linesOfTheFile[i].c_str());
    //}

   
    debug = ofToBool(linesOfTheFile[1]);
    camWidth = ofToInt(linesOfTheFile[4]);
    camHeight = ofToInt(linesOfTheFile[7]);
    fullScreen = ofToBool(linesOfTheFile[10]);
    frameRate = ofToInt(linesOfTheFile[13]);
    concurrentVisit = ofToBool(linesOfTheFile[16]);
    minROI = ofToFloat(linesOfTheFile[19]);
    maxROI = ofToFloat(linesOfTheFile[22]);
    weightROI = ofToFloat(linesOfTheFile[25]);
    recordFile = linesOfTheFile[28];
   
    if(debug)
    {
        ofLog() << "****** ofApp::setup()";
        ofLog() << "debug: " << debug;
        ofLog() << "camWidth: " << camWidth;
        ofLog() << "camHeight: " << camHeight;
        ofLog() << "fullScreen: " << fullScreen;
        ofLog() << "frameRate: " << frameRate;
        ofLog() << "concurrentVisit: " << concurrentVisit;
        ofLog() << "minROI: " << minROI;
        ofLog() << "maxROI: " << maxROI;
        ofLog() << "weightROI: " << weightROI;
        ofLog() << "recordFile: " << recordFile;
    }
   
    // read totalSeconds record file
    vector<string> totalSecondsFile;
    ofBuffer sbuffer = ofBufferFromFile(recordFile);
    for (auto line : sbuffer.getLines()){
        totalSecondsFile.push_back(line);
    }
   
    readSeconds = ofToFloat(totalSecondsFile[0]);
   
    if(debug)
    {
        ofLog() << "****** read totalSeconds record file";
        ofLog() << "readSeconds: " << readSeconds;
    }
   
    //ofSetFrameRate(5);
    ofSetFrameRate(frameRate);
   
    //@add for VideoGrabber
    //we can now get back a list of devices.

    vector<ofVideoDevice> devices = vidGrabber.listDevices();
   
    for(int i = 0; i < devices.size(); i++){
        if(devices[i].bAvailable){
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName;
        }else{
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName << " - unavailable ";
        }
    }
   
    vidGrabber.setDeviceID(0);
    //vidGrabber.setDesiredFrameRate(60);
    vidGrabber.setDesiredFrameRate(frameRate);
    vidGrabber.initGrabber(camWidth, camHeight);
    ofSetVerticalSync(true);
   
    //@add for CvHaarFinder
    //img.load("test.jpg");

    finder.setup("haarcascade_frontalface_default.xml");
    //finder.findHaarObjects(img);
}

//--------------------------------------------------------------
void ofApp::update(){
    //@add for VideoGrabber
    ofBackground(100, 100, 100);
    vidGrabber.update();
   
    //@add for CvHaarFinder
    if(vidGrabber.isFrameNew()){
        ofPixels & pixels = vidGrabber.getPixels();
        finder.findHaarObjects(pixels);
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
   
    //@add for VideoGrabber
    ofSetHexColor(0xffffff);
    vidGrabber.draw(0, 0);
   
    //@add for CvHaarFinder
    //img.draw(0, 0);

   
    ofNoFill();
    for(unsigned int i = 0; i < finder.blobs.size(); i++) {
       
        ofRectangle cur = finder.blobs[i].boundingRect;
       
        //if(debug){
        //    ofLog(OF_LOG_VERBOSE, "ROI width = %f", cur.width);
        //    ofLog(OF_LOG_VERBOSE, "ROI height = %f", cur.height);
        //}
       
        //if((cur.width >= 50.0 && cur.width <= 150.0) &&
        //   (cur.height >= 50.0 && cur.height <= 150.0)) {

        if((cur.width >= (minROI * camWidth) && cur.width <= (maxROI * camWidth)) &&
          (cur.height >= (minROI * camWidth) && cur.height <= (maxROI * camWidth))) {
           
            countROI++;
            ofSetColor(255, 0, 0); // red color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
           
            if(debug) {
                ofSetColor(ofColor::yellow);
                ofDrawBitmapString("ROI = " + ofToString(cur.width) + " x " + ofToString(cur.height), camWidth/5, camHeight/1.02);
            }
           
            // not concurrent Visit
            if(!concurrentVisit){
                break;
            }
        }
        else {
            ofSetColor(0, 0, 255); // blue color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
        }
    }
   
    // writeSeconds
    writeSeconds = readSeconds + (countROI / frameRate * weightROI); // weightROI: for calibrate detect missing
   
    if(writeSeconds > latestSeconds){
        // Write data
        if(debug) {
            // totalSeconds record file
            ofLog() << "****** write totalSeconds record file: " << writeSeconds;
        }
       
        ofBuffer secondsBuff;
        secondsBuff.set(ofToString(writeSeconds));
        bool fileWritten = ofBufferToFile(recordFile, secondsBuff);
       
        latestSeconds = writeSeconds;
    }

    if(debug){
        // show message
        ofSetColor(ofColor::white);
        ofDrawBitmapString("total seconds: " + ofToString(writeSeconds), camWidth/5, camHeight/1.2);
        ofDrawBitmapString(ofToString(minROI * camWidth) + " <= ROI <= " + ofToString(maxROI * camWidth), camWidth/5, camHeight/1.1);
    }
   
    ofSetColor(100, 100, 100);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    //@add for VideoGrabber
    if(key == 'd' || key == 'D'){
        debug = !debug;
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){

}

//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


***********************************************

    5. bin/data 資料夾
        a. haarcascade_frontalface_default.xml // from ofxOpenCv

        b. totalSeconds.txt // record second
            0

        c. config.txt // config file
# debug (true/false)
false

# cam width (int)
320

# cam height (int)
240

# full screen (true/false)
false

# frame rate (int)
5

# concurrent visit (true/false)

false

# minimum width ratio of ROI(region of interest) (float)
0.125

# maximum width ratio of ROI(region of interest) (float)
0.5

# weight of ROI (float)
1.0

# recordFile (string)
totalSeconds.txt

-----------------------------------------------------------------------------------------------

* 無法正常作用(可能要配合 ofx 0.9.2) *
D. 利用 GPIO( or I²C: Inter-Integrated Circuit) 傳送資料給 Arduino
     1. 參考: I touchs: Raspberry Pi: Connected Arduino Using I2C
         > 讓 Raspberry Pi 的 I2C 功能啟用, 並且記下以下的資料

           $ ls /dev/i2c*
           /dev/i2c-1

           以及 Arduino 裡的定義:
          
#define SLAVE_ADDRESS 0x04
 
     2. 安裝 ofxGPIO
         $ cd /home/pi/of_v0.9.3/addons 
         $ git clone https://github.com/kashimAstro/ofxGPIO

     3. 修改專案的 addons.make 檔案如下:
         /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/addons.make
         ofxOpenCv
         ofxGPIO


     4.
修改 ofApp.h 如下:
/home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/src/
ofApp.h
 
#pragma once

#include "ofMain.h"
#include "ofxCvHaarFinder.h"
//@add for GPIO
#include "ofxGPIO.h"

class ofApp : public ofBaseApp{

    public:
        void setup();
        void update();
        void draw();
        //@add for GPIO 
        //void exit();

        void keyPressed(int key);
        void keyReleased(int key);
        void mouseMoved(int x, int y );
        void mouseDragged(int x, int y, int button);
        void mousePressed(int x, int y, int button);
        void mouseReleased(int x, int y, int button);
        void mouseEntered(int x, int y);
        void mouseExited(int x, int y);
        void windowResized(int w, int h);
        void dragEvent(ofDragInfo dragInfo);
        void gotMessage(ofMessage msg);
   
        //@add for VideoGrabber
        ofVideoGrabber vidGrabber;

        //@add for CvHaarFinder
        //ofImage img;
        ofxCvHaarFinder finder;
   
        //@add second record
        float countROI;
        long readSeconds; // read from totalSeconds record file
        long writeSeconds; // write to totalSeconds record file
        long latestSeconds; // latestSeconds
   
        // config file
        bool debug;
        int camWidth;
        int camHeight;
        bool fullScreen;
        int frameRate;
        bool concurrentVisit;
        float minROI;
        float maxROI;
        float weightROI;
        string recordFile;

        //@add for I2C
        //I2CBus * bus;

        //@add for GPIO
        //GPIO ofxGPIO;
        GPIO* ofxGPIO;

};

 
     5.
修改 ofApp.cpp 如下:
/home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/src/ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetLogLevel(OF_LOG_VERBOSE);

    // read config file
    vector<string> linesOfTheFile;
    ofBuffer buffer = ofBufferFromFile("config.txt");
    for (auto line : buffer.getLines()){
        linesOfTheFile.push_back(line);
    }
    //for (int i = 0; i < linesOfTheFile.size(); i++) {
    //    ofLog(OF_LOG_VERBOSE, "cur.width = %s", linesOfTheFile[i].c_str());
    //}
   
    debug = ofToBool(linesOfTheFile[1]);
    camWidth = ofToInt(linesOfTheFile[4]);
    camHeight = ofToInt(linesOfTheFile[7]);
    fullScreen = ofToBool(linesOfTheFile[10]);
    frameRate = ofToInt(linesOfTheFile[13]);
    concurrentVisit = ofToBool(linesOfTheFile[16]);
    minROI = ofToFloat(linesOfTheFile[19]);
    maxROI = ofToFloat(linesOfTheFile[22]);
    weightROI = ofToFloat(linesOfTheFile[25]);
    recordFile = linesOfTheFile[28];
   
    if(debug)
    {
        ofLog() << "****** ofApp::setup()";
        ofLog() << "debug: " << debug;
        ofLog() << "camWidth: " << camWidth;
        ofLog() << "camHeight: " << camHeight;
        ofLog() << "fullScreen: " << fullScreen;
        ofLog() << "frameRate: " << frameRate;
        ofLog() << "concurrentVisit: " << concurrentVisit;
        ofLog() << "minROI: " << minROI;
        ofLog() << "maxROI: " << maxROI;
        ofLog() << "weightROI: " << weightROI;
        ofLog() << "recordFile: " << recordFile;
    }
   
    // read totalSeconds record file
    vector<string> totalSecondsFile;
    ofBuffer sbuffer = ofBufferFromFile(recordFile);
    for (auto line : sbuffer.getLines()){
        totalSecondsFile.push_back(line);
    }
   
    readSeconds = ofToFloat(totalSecondsFile[0]);
   
    if(debug)
    {
        ofLog() << "****** read totalSeconds record file";
        ofLog() << "readSeconds: " << readSeconds;
    }
   
    //ofSetFrameRate(5);
    ofSetFrameRate(frameRate);
   
    //@add for VideoGrabber
    //we can now get back a list of devices.
    vector<ofVideoDevice> devices = vidGrabber.listDevices();
   
    for(int i = 0; i < devices.size(); i++){
        if(devices[i].bAvailable){
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName;
        }else{
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName << " - unavailable ";
        }
    }
   
    vidGrabber.setDeviceID(0);
    //vidGrabber.setDesiredFrameRate(60);
    vidGrabber.setDesiredFrameRate(frameRate);
    vidGrabber.initGrabber(camWidth, camHeight);
    ofSetVerticalSync(true);
   
    //@add for CvHaarFinder
    //img.load("test.jpg");
    finder.setup("haarcascade_frontalface_default.xml");
    //finder.findHaarObjects(img);

    //@add for GPIO
    //bus = new I2CBus("/dev/i2c-1");
    //bus->addressSet(0x04);


    //@add for GPIO (pin) 
    //ofxGPIO.setup("7");
    //ofxGPIO.export_gpio();
    //ofxGPIO.setdir_gpio("out");

    ofxGPIO = new GPIO("7");
    ofxGPIO->export_gpio();
    ofxGPIO->setdir_gpio("out");

}

//--------------------------------------------------------------
void ofApp::update(){
    //@add for VideoGrabber
    ofBackground(100, 100, 100);
    vidGrabber.update();
   
    //@add for CvHaarFinder
    if(vidGrabber.isFrameNew()){
        ofPixels & pixels = vidGrabber.getPixels();
        finder.findHaarObjects(pixels);
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
   
    //@add for VideoGrabber
    ofSetHexColor(0xffffff);
    vidGrabber.draw(0, 0);
   
    //@add for CvHaarFinder
    //img.draw(0, 0);
   
    ofNoFill();
    for(unsigned int i = 0; i < finder.blobs.size(); i++) {
       
        ofRectangle cur = finder.blobs[i].boundingRect;
       
        //if(debug){
        //    ofLog(OF_LOG_VERBOSE, "ROI width = %f", cur.width);
        //    ofLog(OF_LOG_VERBOSE, "ROI height = %f", cur.height);
        //}
       
        //if((cur.width >= 50.0 && cur.width <= 150.0) &&
        //   (cur.height >= 50.0 && cur.height <= 150.0)) {
        if((cur.width >= (minROI * camWidth) && cur.width <= (maxROI * camWidth)) &&
          (cur.height >= (minROI * camWidth) && cur.height <= (maxROI * camWidth))) {
           
            countROI++;
            ofSetColor(255, 0, 0); // red color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
           
            if(debug) {
                ofSetColor(ofColor::yellow);
                ofDrawBitmapString("ROI = " + ofToString(cur.width) + " x " + ofToString(cur.height), camWidth/5, camHeight/1.02);
            }
           
            // not concurrent Visit
            if(!concurrentVisit){
                break;
            }
        }
        else {
            ofSetColor(0, 0, 255); // blue color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
        }
    }
   
    // writeSeconds
    writeSeconds = readSeconds + (countROI / frameRate * weightROI); // weightROI: for calibrate detect missing
   
    if(writeSeconds > latestSeconds){
        // Write data
        if(debug) {
            // totalSeconds record file
            ofLog() << "****** write totalSeconds record file: " << writeSeconds;
        }
       
        ofBuffer secondsBuff;
        secondsBuff.set(ofToString(writeSeconds));
        bool fileWritten = ofBufferToFile(recordFile, secondsBuff);
       
        latestSeconds = writeSeconds;

        //@add for GPIO
        //bus->writeByte(0x04, writeSeconds);
        //usleep(50000); // sleep for 0.05 second

        //@add for test

        /*
        bus->writeByte(0x04,1);
        usleep(500000); // sleep for 0.5 second
        bus->writeByte(0x04,0);
        usleep(500000); // sleep for 0.5 second  

        */  

        //@add for GPIO
        //ofxGPIO.setval_gpio("1");
        //usleep(50000); // sleep for 0.05 second
        //ofxGPIO.setval_gpio("0");
        //usleep(50000); // sleep for 0.05 second

        ofxGPIO->setval_gpio("1");
        usleep(50000); // sleep for 0.05 second
        ofxGPIO->setval_gpio("0");
        usleep(50000); // sleep for 0.05 second

    }

    if(debug){
        // show message
        ofSetColor(ofColor::white);
        ofDrawBitmapString("total seconds: " + ofToString(writeSeconds), camWidth/5, camHeight/1.2);
        ofDrawBitmapString(ofToString(minROI * camWidth) + " <= ROI <= " + ofToString(maxROI * camWidth), camWidth/5, camHeight/1.1);
    }
   
    ofSetColor(100, 100, 100);
}

/*
//--------------------------------------------------------------
void ofApp::exit(){
   
    //@add for GPIO
    ofxGPIO.unexport_gpio();
}

*/

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    //@add for VideoGrabber
    if(key == 'd' || key == 'D'){
        debug = !debug;
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}

//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}

 
     6. 編譯與執行:
         $ cd /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB
         $ make         

         $ ./bin/DPHeadTrackingUSB

     7. 開機後自動執行: (console 的訊息會出不來, 建議改成在 .bashrc 裡執行程式)
         $ cd
         $ touch startHeadTracking.sh
         $ chmod 755 startHeadTracking.sh

         $ sudo nano startHeadTracking.sh
#!/bin/bash
sleep 5
cd /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB
./bin/DPHeadTrackingUSB


         $ cat startHeadTracking.sh

         $ sudo crontab -e
         ....
         @reboot /home/pi/startHeadTracking.sh

         $ sudo crontab -l

2016年4月28日 星期四

Raspberry Pi: Geolocation

since: 2016/04/28
update: 2016/04/28
reference:
1. geocoder : Python Package Index
2. geopy: Python Package Index
3. python-geoip — python-geoip

A. Get current IP location
    1. install geocoder (for python2 only)
        $ pip --upgrade geocoder

    2. get latitude(緯度) and longitude(經度) from current IP
pi@raspberrypi:~ $ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import geocoder
>>> g = geocoder.ip('me')
>>> g.latlng
[23.5, 121.0]
>>> exit()


-----------------------------------------------------------------------------------------------

B. Measuring Distance
    1. install geopy (for both python2 and python3)
       $ sudo pip install geopy
       $ sudo pip install python-geoip-python3

    2. Measuring Distance (Using great-circle distance)
pi@raspberrypi:~ $ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from geopy.distance import great_circle
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(great_circle(newport_ri, cleveland_oh).meters)
864456.7616296598
>>> exit()


-----------------------------------------------------------------------------------------------

C. Looks up the IP information (test for python2 only)
    1. install geoip
       $ sudo pip install python-geoip
       $ sudo pip install python-geoip-python3
       $ sudo pip install python-geoip-geolite2

    2. Looks up the IP information (real IP)
pi@raspberrypi:~ $ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from geoip import geolite2
>>> match = geolite2.lookup('17.0.0.1')
>>> match.location
(37.323, -122.0322)
>>> exit()

2016年3月29日 星期二

Raspberry Pi: Turn It Into An Beacon Node

since: 2016/03/29
update: 2016/04/01

reference:
1. Raspberry Pi應用 - Bluetooth 4.0 使用 iBeacon 
2. Overview | piBeacon - DIY Beacon with a Raspberry Pi 
3. Raspberry Pi 3 as an Eddystone URL beacon 


A. Install Required Libraries
    $ sudo apt-get install libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev libreadline-dev

-----------------------------------------------------------------------------------------------

B. Download Bluez

    $ sudo mkdir bluez
    $ cd bluez
    $ sudo wget www.kernel.org/pub/linux/bluetooth/bluez-5.38.tar.xz

-----------------------------------------------------------------------------------------------

C. Unzip and Compile Bluez

    $ sudo unxz bluez-5.38.tar.xz
    $ sudo tar xvf bluez-5.38.tar
    $ cd bluez-5.38
    $ sudo ./configure --disable-systemd
   
    $ sudo make
    $ sudo make install
-----------------------------------------------------------------------------------------------

D. Check for your USB Module

    $ cd /home/pi/bluez/bluez-5.38
    $ tools/hciconfig

    hci0:    Type: BR/EDR  Bus: USB
    BD Address: 00:1A:7D:DA:71:13  ACL MTU: 310:10  SCO MTU: 64:8
    UP RUNNING
    RX bytes:652 acl:0 sco:0 events:43 errors:0
    TX bytes:1533 acl:0 sco:0 commands:43 errors:0


-----------------------------------------------------------------------------------------------

E. Enable the USB Device
    $ sudo tools/hciconfig hci0 up
    $ sudo tools/hciconfig hci0 leadv 3

      LE set advertise enable on hci0 returned status 12

    $ sudo tools/hciconfig hci0 noscan

-----------------------------------------------------------------------------------------------

F. Enter the Beacon Advertising Data
   $ sudo tools/hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00

< HCI Command: ogf 0x08, ocf 0x0008, plen 32
  1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F
  17 D1 AD 07 A9 61 00 00 00 00 C8 00
> HCI Event: 0x0e plen 4
  01 08 20 00


-----------------------------------------------------------------------------------------------

G. 測試軟體
     1. Mac: Beacon Scan

     2. iOS: Locate Beacon

     3. Android: Locate Beacon

-----------------------------------------------------------------------------------------------

H. 簡易開機自動啟動

     $ sudo nano /home/pi/iBeacon.sh
#!/bin/bash
sleep 5
cd /home/pi/bluez/bluez-5.38/
tools/hciconfig hci0 leadv 3
tools/hciconfig hci0 noscan
tools/hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00


     $ sudo crontab -e
        ....
        @reboot /home/pi/iBeacon.sh

-----------------------------------------------------------------------------------------------
I. 測試結果:(iOS)








2016年3月3日 星期四

Raspberry Pi: Python Remote Development With PyCharm

since: 2016/03/03
update: 2017/01/21

reference:
1. Feature Spotlight: Python remote development with PyCharm | PyCharm Blog
2. https://www.mercurial-scm.org/wiki/Download

A. 在 Pi 上建立專案資料夾:
    $ cd
    $ mkdir project
    $ cd project
    $ mkdir routine_task

-----------------------------------------------------------------------------------------------

(選擇性)
B. 在  Mac 上安裝 Mercurial 版本控制
     

1. install brew: http://brew.sh
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

     

2. install mercurial
$ brew install mercurial


3. check PyCharm, add hg path: (later)

   
/usr/local/bin/hg


4. add configuration file
    $ cd
    $ vi .hgrc
[ui]
username = Lanli <yourID@gmail.com>


[tortoisehg]
ui.language = zh_TW


[auth]
bitbucket.org.prefix = bitbucket.org
bitbucket.org.username = lanli
bitbucket.org.password =
yourPass 

5. check again
    $ cat .hgrc

 
-----------------------------------------------------------------------------------------------

C. 在 Mac 上用 PyCharm 建立新的專案:

    1. Create New Project:

    2. Setting:
        Location: 本地專案位置
        Interpreter: 直譯器, 選取 remote 的 ssh 連線方式
         > Create

-----------------------------------------------------------------------------------------------

D. 設定將專案內容部署至遠端
     1. PyCharm > Preferences... > Build, Execution, Deployment > Deployment:

         Name: Rasberry Pi2
         Type: SFTP
          > OK


     2. 設定 Connection 頁籤內容:
         Type: SFTP
         SFTP host: 192.168.1.6
         Port: 22
         Root path: /       (建議設為 / )
         User name: pi
         Password: **

     3. 設定 Mapping 頁籤內容:
         Local path: 本地專案位置
         Development path on server 'Raspberry Pi2': 遠端專案目錄
         (備註: 會以
Connection 頁籤裡的 Root path 作為相對位置 )
         > OK


-----------------------------------------------------------------------------------------------

E. 測試:
     1. 將檔案部署至遠端

        a. 新增 python 檔案: HelloPython.py
      #!/usr/bin/python3      
      print('Hello Python')

    b. Tools > Deployment > Upload to Raspberry Pi2

    C. 檢查 pi 上的專案目錄: 

     2. 執行遠端程式:
         a. Run > Run 'HelloPython'


         b. 結果:

-----------------------------------------------------------------------------------------------

F. Create Project By Check out Version Control

    1. 確定已完成:
        B. 在  Mac 上安裝 Mercurial 版本控制


    2. Check out from Version Control

    3. Clone Repository

    4. Checkout From Version Control