顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2017年3月12日 星期日

Raspberry Pi: Install OpenCV 3 with Python2,Python3

since: 2017/03/12
since: 2017/03/31
reference:
1. Install guide: Raspberry Pi 3 + Raspbian Jessie + OpenCV 3 - PyImageSearch
2. Accessing the Raspberry Pi Camera with OpenCV and Python - PyImageSearch

A. 前置準備
    1. Raspberry Pi 3
    2. 16 GB microSD Card (編譯 OpenCV 大約會佔用 3G 的容量)
    3. Camera Module
    4. Enable Camera Interface
         > $ sudo raspi-config




    5. (optional) delete the Wolfram engine to free up some space
        $ sudo apt-get purge wolfram-engine

    6. check Python version
        $ python -V
           Python 2.7.9

        $ python3 -V
           Python 3.4.2

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

B. 安裝相關套件
    1. update and upgrade any existing packages
        $ sudo apt-get update
        $ sudo apt-get upgrade

    2. install some developer tools
        $ sudo apt-get install build-essential cmake pkg-config

    3. install some image I/O packages
        $ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev


    4. install some video I/O packages
        $ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
        $ sudo apt-get install libxvidcore-dev libx264-dev

    5. install the GTK development for highgui
        $ sudo apt-get install libgtk2.0-dev

    6. installing a few extra dependencies for optimized
        $ sudo apt-get install libatlas-base-dev gfortran

    7. install both the Python 2.7 and Python 3 header files
        $ sudo apt-get install python2.7-dev python3-dev

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

C. 下載 OpenCV source code
     1. opencv
         $ cd ~
         $ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.2.0.zip
         $ chmod 755 opencv.zip
         $ unzip opencv.zip

     2. opencv_contrib (full install of OpenCV)
         $ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.2.0.zip
         $ chmod 755 opencv_contrib.zip
         $ unzip opencv_contrib.zip

Note: Make sure your opencv  and opencv_contrib  versions are the same
          (in this case, 3.2.0)


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

D. Install Python package manager
     $ wget https://bootstrap.pypa.io/get-pip.py
     $ chmod 755 get-pip.py
     $ sudo python get-pip.py
     $ sudo python3 get-pip.py

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

E. Installing NumPy
    $ pip install numpy (it may take a bit of time)

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

F. Compile and Install OpenCV
    $ cd ~/opencv-3.2.0
    $ mkdir build
    $ cd build
    $ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.2.0/modules -D BUILD_EXAMPLES=ON ..

備註: 選擇性參數: -D INSTALL_C_EXMAPLES=ON

   => Ensuring that Python 2.7 and Python 3 will be used

   > compile OpenCV
     // The Raspberry Pi 3 has four cores, thus we supply a value of 4  to allow OpenCV
     // to compile faster. However, due to race conditions, there are times when
     // make  errors out when using multiple cores.
     // $ make -j4

     $ make // about 7 hours
     $ sudo make install
     $ sudo ldconfig

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

G. 檢查與測試安裝結果
     1. 檢查
         $ ls -al /usr/local/lib/python2.7/dist-packages/cv2.so
         $ ls -al /usr/local/lib/python3.4/dist-packages/cv2.cpython-34m.so
         //$ cd /usr/local/lib/python3.4/dist-packages/
         //$ sudo cp cv2.cpython-34m.so cv2.so    

     2. 測試 
// python2
$ cd
$ python
>>> import cv2
>>> cv2.__version__
'3.2.0'
>>> exit()

// python3
$ cd
$ python3
>>> import cv2
>>> cv2.__version__
'3.2.0'
>>> exit()

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

H. 程式測試   
     1. Test out the camera module
         $ raspistill -o output.jpg

-----------------------------------------------------------------------------------------------
     2. Installing picamera
         // when using Python bindings, OpenCV represents images as NumPy arrays

         $ pip install "picamera[array]"

-----------------------------------------------------------------------------------------------
     3. Grabbing a single image (需要先啟動 X Window: $ startx)
         // test_image.py


# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
rawCapture = PiRGBArray(camera)

# allow the camera to warmup
time.sleep(0.1)

# grab an image from the camera
camera.capture(rawCapture, format="bgr")
image = rawCapture.array

# display the image on screen and wait for a keypress
cv2.imshow("Image", image)
cv2.waitKey(0)


$ python test_image.py


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

     4. access the video stream (需要先啟動 X Window: $ startx)
         // test_video.py

# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))

# allow the camera to warmup
time.sleep(0.1)

# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image, then initialize the timestamp
    # and occupied/unoccupied text

    image = frame.array

    # show the frame
    cv2.imshow("Frame", image)
    key = cv2.waitKey(1) & 0xFF

    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

 
$ python test_video.py


2016年5月19日 星期四

Raspberry Pi: OSC for Python3

since: 2016/05/19
update: 2016/05/19
reference:
1. Osc4py3 documentation

A. 安裝 OSC for Python3
    $ sudo pip3 install osc4py3

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

B. OSC 接收端 (client)
     // osc_client.py

#!/usr/bin/python3

# Import needed modules from osc4py3
from osc4py3.as_eventloop import *
from osc4py3 import oscmethod as osm

print('start osc client....'+'\n')

def osc_receive_function(address, s, x, y):
    # Will receive message address, and message data flattened in s, x, y
    print("osc client receive:")
    print('address = '+address)
    print('s = ' + s)
    print('x = ' + str(x))
    print('y = ' + str(y))

# Start the system.
osc_startup()

# Make server channels to receive packets.
osc_udp_server("192.168.1.17", 2781, "aservername")

# Associate Python functions with message address patterns
osc_method("/test/*", osc_receive_function, argscheme=osm.OSCARG_ADDRESS + osm.OSCARG_DATAUNPACK)

# Periodically call osc4py3 processing method in your event loop.
finished = False
while not finished:
    # …
    osc_process()
    # …

# Properly close the system.
osc_terminate()


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

C. OSC 發送端 (server)
     // osc_server.py

#!/usr/bin/python3

# Import needed modules from osc4py3
from osc4py3.as_eventloop import *
from osc4py3 import oscbuildparse

print('start osc server....'+ '\n')
# Start the system.
osc_startup()

# Make client channels to send packets.
osc_udp_client("192.168.1.17", 2781, "aclientname")

# Build a simple message and send it.
s = 'text'
x = 672
y = 8.871
address = '/test/me'

msg = oscbuildparse.OSCMessage(address, ",sif", [s, x, y])
osc_send(msg, "aclientname")

print("osc server send:")
print('address = ' + address)
print('s = ' + s)
print('x = ' + str(x))
print('y = ' + str(y))

# Periodically call osc4py3 processing method in your event loop.
finished = False
while not finished:
    # You can send OSC messages from your event loop too…
    # …

    osc_process()
    # …
    finished = True # finish the process

# Properly close the system.
osc_terminate()

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

D. 測試:
     1. 啟動 OSC client:
         $ ./osc_client.py
         start osc client....

     2. 啟動 OSC server:
         $ ./osc_server.py
         start osc server....

         osc server send:
         address = /test/me
         s = text
         x = 672
         y = 8.871


     3. 查看 OSC client:
         start osc client....

         osc client receive:
         address = /test/me
         s = text
         x = 672
         y = 8.871000289916992

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月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

2016年3月2日 星期三

Raspberry Pi: Connected Arduino Using I2C

since: 2016/02/25
update: 2016/03/03

reference:
1.Raspberry Pi and Arduino Connected Using I2C - OscarLiang.net
2. [I2C] onRequest and onReceive as slave with Raspberry Pi Master

A. 檢查 Raspberry Pi:
   
1. Linux 版本

    $ uname -a
Linux raspberrypi 4.1.17-v7+ #843 SMP Mon Feb 15 23:35:33 GMT 2016 armv7l GNU/Linux

    2. python 版本
    $ python -V
Python 2.7.9

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

B. 安裝 I2C 與 python相關套件:
    $ sudo apt-get install python-smbus
    $ sudo apt-get install python3-smbus // for python3
    $ sudo apt-get install i2c-tools

    // check
    $ sudo aptitude search smbus
p   pypy-smbus-cffi        - This Python module allows SMBus access through the I2C /dev              
i   python-smbus            - Python bindings for Linux SMBus access through i2c-dev                   
v   python2.7-smbus      -                                                                          
i   python3-smbus          - Python 3 bindings for Linux SMBus access through i2c-dev


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

C. 安裝 I2C 的 Kernel Support:
     $ sudo raspi-config
        > 9 Advanced Options

        > A7 I2C

        > Yes
       ....
        > Yes

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

D. 檢查設定(選擇性)
     $ cat /etc/modules
....
i2c-dev
    
     $ cat /etc/modprobe.d/raspi-blacklist.conf
# ...
# ...


    $ cat /boot/config.txt
....
dtparam=i2c_arm=on

    $ cat /etc/group | grep i2c
i2c:x:998:pi
      // $ sudo adduser pi i2c

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

E. I2C 測試:
    $ sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- -- 


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

F. Arduino Code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    //Serial.println(“Ready!”);
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        number = Wire.read();
        //Serial.print(“data received: “);
        //Serial.println(number);


        if (number == 1){

            if (state == 0){
                digitalWrite(13, HIGH); // set the LED on
                state = 1;
            }
            else{
                digitalWrite(13, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}


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

G. Raspberry Pi's  Python Code:
#!/usr/bin/python
#encoding: utf-8

import smbus
import time

# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("Enter 1 – 9:")
    if not var:
        continue

    writeNumber(var)
    print "RPI: Hi Arduino, I sent you ", var
    # sleep one second
    time.sleep(1)

    number = readNumber()
    print "Arduino: Hey RPI, I received a digit ", number
    print


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

H. 備註:
When we use read_i2c_block_data(), It was too fast to write a command byte and read the data.

In that time, if we use Serial.println() to print log to serial. Arduino will can not follow the speed. and it missing the i2c read flag.

So, the dataReceive() funtion will not be run at all.

The solution is simple: just do not use Serial library until the i2c is free.