2016年11月7日 星期一

不用現代代數的 Galois Theory

現代代數在解釋 Galois Theory 大多是用 field/group 的 automorphism 和  homomorphism 解釋。

雖然簡潔優美,但缺乏直覺。其實 Galois 本身的思路是比較直覺容易理解。

前文提到結城浩的數學女孩就是 follow Galois 思路。雖然寫得很好,不過還是有些避重就輕。

雖然有解釋 Galois 的思路,但嚴謹度缺乏而顯得破碎。另一方面是缺少有分量的範例。

數學女孩大多用二次式來解釋。間或有三次以及四次的一些推論,但沒有札實的例子。

 

偏偏二次式是非常簡單的 case.  很難直觀推論到三次, 四次, 或五次方程式。

下文則是非常好的介紹文:  Galois theory without abstract algebra.  也是同樣用 Galois 原來的思路。

同時輔佐實際的 2, 3, 4, 5 次式例子。即使五次式沒有通解。但 F20 group 仍存在根式解。

 

首先定義有理多項式(方程式)的根式解。如下:

A, B, C, D, 以及 a, b, c, .. 都是有理數。這是所謂的根式解。

NewImage

二次式 x^2 + 2bx + c = 0 的根式解就是 1.  A = b- c;  B = -b;  a = 1/2

三次式的根式解就是 2. 或是 2. 的 linear combination.

依此類推。

前文有提過上述根式解的數,都可以找到對應有理係數多項式的根。因此稱為代數數。

代數數的定義就是有理係數多項式的根。但並非所有代數數都可以

 

再來是定義 elementary symmetric polynomial

Elementary symmetric polynomial 就是把 (x+r1)(x+r2)(x+r3) ... (x+rn) 展開,根據 xi  項歸類所得的係數。

For example:

(x+r1)(x+r2) = x2 + σ1 x + σ2   where σ1 = r1 + r2 ;  σ2 = r1 * r2 

對於高次多項式:
NewImage
同時如果定義 
NewImage
 

注意以上的公式適用於所有實數和複數,並無有理數的限制。

我們有興趣的 case 是有理數係數的多項式。當然根可能是或非有理數。但上述公式告訴我們。

根的 "基本對稱多項式" 如 σ是有理數!  這是很直接但非常重要的觀察結果。

 

 

這個推論 (有理係數多項式的根所構成的基本對稱對項式是有理數) 能 extend 多遠?  

相當遠!  可以証明任意有理對稱多項式滿足 Sn permutation invariant 結果都是有理數。同時可以表示為 σi 的有理式!

是用數學歸納法証明。

 

n=1 :  σ= r1 ∈ Q.  任意有理(對稱)多項式 f(r1) = f(σ1) ∈ Q.   明顯成立。

 

假設 n-1 成立:

i.e. 任何有理多項式  f(r1, r2, ..., rn-1) = g(σ1, σ2, ..., σn-1)  where f(r1, r2, ..., rn-1) is invariant under Sn-1 permutation

 

Prove n: for any rational symmetry polynomial f(r1, r2, ..., rn-1, rn) satisfy Spermutation invariant. 

First set rn = 0. 

f(r1, r2, ..., rn-1, rn) = f(r1, r2, ..., rn-1, 0)  當然仍然滿足 Sn-1 permutation invariant. 

By n-1 assumption,  f(r1, r2, ..., rn-1, rn=0) = f(r1, r2, ..., rn-1, 0) = g(σ1, σ2, ..., σn-1σn=0)  from (6)

=>  [f(r1, r2, ..., rn-1, rn) - g(σ1, σ2, ..., σn-1, σn)]rn=0 = 0  也就是 rn 是一個根。同理 r1, r2, ..., rn-1 都是根。

NewImage

Clearly,  1(r1, r2, ..., rn-1, rn) is invariant under Sn permutation.  同時比原來的 f 更低階。

我們可以重覆這個 operation.  一直到 k(r1, r2, ..., rn-1, rn) = g(σ1, σ2, ..., σn-1, σn)


In summary

任意有理對稱多項式滿足 Sn permutation invariant 結果都是有理數。

同時可以表示為 σi (基本對稱多項式)的有理式!

 

Galois Group

Maximum group of roots permutation invariant under any function.  The result is a known function of polynomial coefficients.

 

Example:

二次式 (roots: r1, r2):

σ1 = r1 + r2  ,    t= (r1 - r2)2  ∈ Q    σand t ∈ S2.  t 開根號後可以計算 r1 and r2.

NewImage

結果就是一開始的根式解。

至於 Galois group:

S2=C2=Z2 ⊳ E   (The quotient group is Z2)

 

三次式 (roots: r1, r2, r3):

NewImage 

where α2 = ω, α3 = ω*ω

t1^3 is permutation invariant under A3.  t2^3 is also permutation invariant under A3.

但是 t1^3+t2^3 and t1^3*t2^3 則是 permutation invariant under S3.   

=> t1^3+t2^3, t1^3*t2^3 ∈ Q  =>  可以解出 t1 and t2 first. 

=> 再由 t1 and t2 解出 r1, r2, and r3 by (15).

如何找 t1^3 and t2^3?  就是展開上式利用根和係數得到 t1^3+t2^3 and t1^3*t2^3

 

S3 ⊳ A3=C3=Z3 ⊳ E   (The quotient group is Z2, and Z3, respectively)

 

四次式:

 

S4(24) ⊳ A4(12) ⊳ D2(4)=V4(4)=C2xC2 ⊳ C2=Z2(2) ⊳ E   (The quotient group is Z2, Z3, Z2, and Z2 respectively)

同樣可以先解出

NewImage 

如同三次式的 t1^3 and t2^3!  當然 θ1 and θ2 滿足 A4 permutation invariant.

所以 θ1+θ2 和 (θ1-θ2)^2 滿足 S4 permuation invariant. 

 

下一步就是要找到對應的 θ1 and θ2, 必須滿足 A4 permutation invariant. 

 

(t1 + ω t2 + ω^2 t3)^3 = θ1    

(t2 + ω t1 + ω^2 t3)^3 = θ2

(t1 + ω t3 + ω^2 t2)^3 = θ3  same as θ2, useless

t1 + t2 + t3 =?

看來只有 A3 permutation invariant? 

但 t1, t2, and t3 不是四次式的根。而是三次式的根。不過是什麼三次式的根?

答案是 it depends:

 

如果定義 (a)

t1 = (r1+r2)(r3+r4)

t2 = (r1+r3)(r2+r4)  

t3 = (r1+r4)(r2+r3)

可以得出一個三次式。


也可以定義 (b)

t1 = r1*r2 + r3*r4

t2 = r1*r3 + r2*r4  

t3 = r1*r4 + r2*r3

可以得出另一個三次式。


或是定義 (c)

t1 = [(r1-r2)(r3-r4)]^2

t2 = [(r1-r3)(r2-r4)]^2  

t3 = [(r1-r4)(r2-r3)]^2

可以得出另一個三次式。


或是定義 (d)

t1 = (r1-r2)^2 + (r3-r4)^2 = (r1-r2+ i r3 - i r4)*(r1-r2- i r3 + i r4) = (r1+ i*r3 -r2 - i*r4)(r1+ i*r4 -r2 - i*r3)

t2 = (r1-r3)^2 + (r2-r4)^2 = (r1-r3+ i r2 - i r4)*(r1-r3- i r2 + i r4) = (r1+ i*r2 -r3 - i*r4)(r1+ i*r4 -r3 - i*r2)

t3 = (r1-r4)^2 + (r2-r3)^2 = (r1-r4+ i r2 - i r3)*(r1-r4- i r2 + i r3) = (r1+ i*r2 -r4 - i*r3)(r1+ i*r3 -r4 - i*r2)

 

可以得出另一個三次式。

 

共同的特點 t1, t2, t3 都滿足 V8 (8) permutation invariant.  Total 8*3 = 24 permutation 構成 S4 permutation invariant for t1+t2+t3, t1*t2+t2*t3+t3*t1, and t1*t2*t3.

藉著 S4 permutation invariant 代表三次方程式的係數都可由四次方程式的係數表示。

最常用的是 (a).  可以參考本文 for 三次式的 coefficient. 

 

如果是 (d), 可以定義類似四次分圓根 (1,i,-1,-i) 的關係。

z1  = r1 + i r2 - r3 - i r4

z1' = r1 + i r4 - r3 - i r2 

z2  = r3 + i r2 - r1 - i r4

z2' = r3 + i r4 - r1 - i r2

z3  = r2 + i r1 - r4 - i r3

z3' = r2 + i r3 - r4 - i r1 

z4  = r4 + i r1 - r2 - i r3

z4' = r4 + i r3 - r2 - i r1

z1*z1' = z2*z2' = z3*z3' = z4*z4' = t1

同樣可以定義 t2 and t3.

 

t1+t2+t3 = (r1-r2)^2 + (r2-r3)^2 + (r3-r4)^2 + (r1-r3)^2 + (r1-r4)^2 + (r2-r4)^2

= 3*(r1+r2+r3+r4)^2 - 8*(r1r2+r1r3+r1r4+r2r3+r2r4+r3r4)

t1*t2+t2*t3+t1*t3 and t1*t2*t3 就要再計算。此處忽略。

 

先以 (a) 定義的三次多項式來看。

首先三次多項式的 D 和四次多項式的 D 是一致。其實 (a),(b),(c),(d) 都一致。

另外就是三次多項是否是 reducible?  也就是是否有有理根。

t1 = (r1+r2)(r3+r4) 

r1+r2+r3+r4 = -a    --- (1)

=> (r1+r2 - r3 - r4)^2 = a^2 - 4*t1

r1 + r2 - r3 - r4 = +/-sqrt(a^2 - 4*t1)   --- (2)

r1 + r3 - r2 - r4 = +/-sqrt(a^2 - 4*t2)   --- (3)

r1 + r4 - r2 - r3 = +/-sqrt(a^2 - 4*t3)   --- (4)

 

From (1) to (4), we can solve r1, r2, r3, r4 unknowns.

也可以先解: r1+r2, r3+r4, r1+r3, r2+r4, r1+r4, r2+r3

從 r1+r2 只要有 r1-r2 就可解 r1, r2.   r1-r2 = (r1+r3) - (r2+r3)

最後可解 r1, r2, r3, r4. 

 

所以順序上是先解 θ1 and θ2.  ( S4(24) ⊳ A4(12) )

再解 t1, t2, t3.  ( A4(12) ⊳ V4(4)  or S4(24) ⊳ V8(8) )

再解 r1+r2, r1+r3, r1+r4, r2+r3, r2+r4, r3+r4 ( V8(8) ⊳ C2(2) )

最後再解 C2(2) ⊳ E

 

-a3 = (r1+r2)+(r3+r4)

d1 = r1+r2 - (r3+r4)         (12)(34)

d2 = (r1+r3) - (r2+r4)

d3 = (r1+r4) - (r2+r3)

 

(a3^2 - d1^2)/4  =  (r1+r2)(r3+r4) = t1

(a3^2 - d2^2)/4  =  (r1+r3)(r2+r4) = t2

(a3^2 - d3^2)/4  =  (r1+r4)(r2+r3) = t3

 

實務上先做出一個三次方程預解式,使用 t1, t2, t3 為根。

 NewImage

 

NewImage 

 

NewImage

 

2016年10月29日 星期六

Mac-mini 使用 USB3.0 external SSD 加速

原來想換一台新的 Mac, 像是 iMac 或是新的 touch ID Macbook Pro.  不過實在太貴了。

只好再把 2012 Late Mac-mini upgrade.  之前把 2GB + 2GB DRAM 換成 2GB + 8GB = 10GB DRAM.

不過還是有彩球。想想可能是 5400-rpm hard drive (500GB) 太慢。

 

也研究過把內建的 500GB hard drive 直接換成 SSD.  看了一些 YouTube 影片,覺得還是有風險。

萬一過程中手抖把 connector 弄壞,就得不償失。所以還是先用 USB3.0-to-SATA III 外接盒。之後所果有必要再改成內建。

 

本文是用 USB3.0 to SATA 外部 SSD.  好處是不用把 Mac-mini 開膛剖腹,避免風險。

壞處就是 USB3.0 外接 SSD performance 還是有一些差異。

SATA II 速度的上限是 3Gb/s (W/R ~ 275/285MB/sec, about 76% throughput)  

SATA III 速度的上限是 6Gb/s (W/R ~ 520/550MB/sec, about 73% throughput).  

USB3.0 速度的上限是 5Gb/s, 如果有支援 UASP (Usb Attached Scsi Protocol).  可以達到 W/R ~ 480/500MB/sec, about 80% throughput.  基本上已經非常接近 embedded SATA III SSD performance.

 

Step 1: SSD and USB3.0 to SATA III 外接盒

我買了 Micron Crucial MX300 SSD, 275GB.  查了一下是用 Micron TLC 3D NAND flash.  雖然比不上 MLC (更不提 SLC) 的強壯,但便宜 (2200) 加上大廠應該還是有保障。

外接盒是用台廠 AKiTio 的 Neutrino U3 hard drive enclosure, 轉換 USB3.0 to SATA III.

要注意 外接盒的 USB3.0 必須支援 UASP protocol 才能達到最高的 file transfer 速度 (400MB/s)!!

AKiTiio 是用 Asmedia 2105 IC.

 

Step 2: 設定 SSD and 外接盒

第一步先 format SSD to OS X Extended with GUID map scheme 如下:

https://www.akitio.com/information-center/formatting-external-hard-drives

 

NewImage

再來就是 download AJA 

https://www.aja.com/products/aja-system-test

確認 USB3.0 外接 SSD performance 可以達到 W/R > 400MB/sec!!

 NewImage

 

比較之下,原來 Mac-mini 500GB 5400rpm 的 HD 速度如下:

TBA

 

 

Step 3:  使用 carbon copy cloner (CCCloner) 把所有的檔案 copy to SSD. 同時 make SSD bootable.  

可以參考:

http://macintoshhowto.com/hardware/how-to-speed-up-your-mac-with-a-ssd-drive.html

其中有幾點我有不同的意見。主要的差異是參考文是用 embedded SSD (內部 SATA interface) 而我是用外部 USB3.0 轉 SATA III SSD.

1. Step 4: 為了要省 SSD 的 capacity, 該文只 copy system and applications folders to SSD.  但 users folders 都還留在 mac-mini 原來的 5400 rpm HD.   原來我也用相同的作法。不過發現最後 AJA performance 變得非常差,只有 30MB/sec (如下圖)。因此改成把所有 users folders 都 copy 到 SSD.  確認如此 performance 可以達到 4xx MB/sec. 

2. Step 4: CCCloner 的 interface 似乎有改變。Step 6: 改 user folder 可以忽略,因為 users folder 都 copy 到 SSD.

3. Step 7: Enable TRIM.  首先要看 SSD 是否有支援 TRIM.  如果 SSD 沒支援 TRIM 就無法使用。更重要的是 USB3.0 外接 SSD 沒有支援 TRIM.  所以可以跳過 step 7. 

 

唯一的問題是 SSD (275GB) 小於 hard drive (500GB).  如果 SSD 夠大。是可以考慮 copy 所有 data.  

如果無法 copy 所有 user data,  可以只讓 SSD 變成 boot disk 而非所有 users data disk.  不果只限於內建 SATAIII SSD.  如果是外接 SSD.  結果很不理想如下。

 

在第一次實驗。基本上 follow 該文。只把 SSD 變成 boot disk (見下一步), users folder 還是放在 mac-mini 原來的 5400rpm HD, 再做 AJA 測試。Performance 就大幅下降。尚不清楚為什麼???

可能是因為做為 boot disk 會有大幅的 system data in and out of SSD, 造成 video file transfer 大幅下降?

還是有其它因素?  但是開機速度的確有大幅改善。

NewImage 

 

因此重新修改的方式就是儘量 copy 所有 data (system, applications, and users) to external SSD.  除了移掉 picture folder 以減少 SSD size.

SSD 只有 273GB.  HD 有 319GB.  需要少 50GB!

NewImage

不過 photo 就有 300GB!!  Lots of redundancy!!  Need to clean later.

NewImage

 

Step 4: Make SSD default booting disk

Under System Preferences click Startup Drive select the SSD Drive, then restart! 

在用 external SSD boot 之後,第一個明顯的感覺是 boot 速度變快了。在白蘋果出現, white bar 變化的前 10-15 秒其實速度很慢和之前一樣,應該是 on-board bias (flash) 在開機。但在 white bar 中後段開始 load from HD, 速度突然一飛沖天。整體的加速很明顯。

再用 AJA run SSD 的 W/R 速度仍有 4xx MB/sec.  

NewImage

 

用 AJA run Mac-mini 5400rpm HD 的 W/R 速度如下: 也有 9X MB/SEC!!

似乎也有大幅的進步。或許是 SSD 仍然有幫到 cache or program file/system file 的加速?

NewImage

 

 

 

Step 5: Wha’s working and not working

Need to fix: 

* Microsoft Office not working properly because it requires to key or 365 subscription

* Dropbox need to re-login and re-set it’s path

* Google drive need to re-start it’s path

Working: 

* Browser (Chrome and Safari) work fine

* Printer works properly

* Blogger tool works fine

 

2016年9月11日 星期日

Group Theory 應用 - 方程式

從上次的 Group Theory - 我的經驗 之後。很少花時間在 group, 因此又忘的差不多。

這次看了結城浩的數學女孩 x 伽羅瓦理論,非常驚艷於其中非常清楚而且淺顯的內容介紹 group theory.  如何從解方程式 (2, 3, 4, 5 次元) 體 (field) 的問題,轉化為 group 問題。以及 Gaolois 的論文清楚解說。Bonus 是順便解釋 Greek 作圖的三等分角問題。

本文摘錄其中的重點。

2016年7月2日 星期六

OpenCV 筆記 - Basic Operation

本文主要參考 Marc 的 OpenCV 筆記

OpenCV 主要 support C++ 和 Python 兩種 interfaces.

之前主要以 python 為主。不過在某些情況 C++ 的 computation efficiency 有優勢。

因此熟悉基本操作仍有需要。

基本操作 (Base Operation)

OpenCV 最重要的 data format 是 (2-D) matrix.  因為這是多數影像的型態。  

 

Basic Matrix Operation:  OpenCV 常會用到 cv::Mat 陣列。

如何建立矩陣? 直接宣告矩陣大小和型態。

Mat image(240, 320, CV_8UC3);

image size 是 240x320.  格式是 CV_8UC3 -> CV_<bit-depth> {U|S|F}C(<number of channels>)

U 是 unsigned integer type, S 是 signed integer type, and F 是 float type.

所以 8UC3 就是 8bit, unsigned integer, 3 channels (e.g. RGB or actually BGR image).

 

重新分配矩陣大小

image.create(480, 640, CV_8UC3);

 

宣告矩陣並設定初始值 (下例都初始化為 5), 和 matlab 類似

Mat A33(3, 3, CV_32F, Scalar(5));

另一種方式是用 ones matrix

Mat B33 = Mat::ones(3, 3, CV_32F)*5.;

或是用 zeros matrix

Mat C33 = Mat::zeros(3, 3, CV_32F) + 5.;

以上的方法似乎只用於 1 channel case.

如果宣告 3 channels.  只有 channel 1 有初始值。

 

如果要 3 channels 都有初始值。可以用以下的方法:

Mat img1(5, 5, CV_8UC1, Scalar(9) );

Mat dst;

cvtColor(img1, dst, CV_GRAY2RGB);

此是 dst 會是 CV_8UC3 且初始化為 9.

 

宣告指定數值的矩陣

Mat A22 = Mat_<float>(2,2) << 5, -15, 20, -15);

或是

float B22data[] = { 5, -15, 20, -15};

Mat B22 = Mat(2, 2, CV_32F, B22data).clone();

註: 用 clone 會複製到新的 memory.

如果不用 clone 也可以。但變成 pointer 而非 memory copy.

如果 B22data 改變,也會改變 B22.

 

 

轉移矩陣但不複製 memory

cv::Mat 轉換成 cv::Mat

Mat image_alias = image

 

將一般陣列轉換成 cv::Mat

float* Idata = new float[480*640*3];

Mat I(480, 640, CV_32FC3, Idata); 

 

vector陣列轉換成cv::Mat

vector<Point> iptvec(10); Mat dstMat(iptvec); 

IplImage轉換成cv::Mat

IplImage* iMG = cvCreateImage(cvSize(320,240), 16, 1); Mat dstMat = cvarrToMat(iMG);

cv::Mat轉換成IplImage

Mat srcMat; IplImage iMG = srcMat; 

cv::Mat轉換成CvMat

Mat srcMat; CvMat dstCvMat = srcMat;

轉移矩陣且複製 memory

IplImage複製給cv::Mat

IplImage* iMG = cvCreateImage(cvSize(320,240), 16, 1); Mat dstMat = cvarrToMat(iMG).clone();

cv::Mat複製給vector

Mat srcMat; vector<Point2f> ptvec = Mat_<Point2f>(srcMat);

cv::Mat 合併、插入、移除

cv::Mat hMat(5,1,CV_8UC1,cv::Scalar(2)); cv::Mat sMat(5,1,CV_8UC1,cv::Scalar(5)); cv::Mat tmpMat(5,2, CV_8UC1 ); hMat.copyTo( tmpMat.col(0) ); sMat.copyTo( tmpMat.col(1) ); /* 25 25 25 25 25 */

合併cv::Mat

cv::Mat mat1(1,3, CV_8UC1,cv::Scalar(2)); cv::Mat mat2(2,3, CV_8UC1,cv::Scalar(3)); cv::Mat matM; matM.push_back(mat1); matM.push_back(mat2); /* 222 333 333 */

型態轉換(int、float、double)

** CV_8UC1 to CV_32FC1

cv::Mat mat8U(3,2,CV_8UC1,cv::Scalar(2)); cv::Mat mat32F; mat8U.convertTo(mat32F, CV_32FC1);

陣列運算cv::Mat

計算陣列中非0值的數量

cv::Mat src(5,3,CV_8UC1, cv::Scalar(3)); int total = cv::countNonZero(src); std::cout<<total; //15

 

 

 

2016年6月25日 星期六

Install Octave in Ubuntu

 

Step1

> sudo apt-get infall octave

> sudo apt-get install octave-control octave-image octave-signal

2016年5月11日 星期三

Install OpenCV3 on Raspberry Pi 3 (Raspbian Jessie)

本文主要參考 pyimagesearch

http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/

 

OpenCV 目前是 de facto computer vision 的開放平台以及提供許多範例。

除了 kernel 是  C/C++ 提供高效率外,另外有多種 interface 如 python or matlab.

OpenCV 唯一比較麻煩的是沒有一鍵 installation, 或是 apt-get or rpm. 

需要 download OpenCV source code 重新 compile.  

 

如果要使用 python interface, Anaconda 沒有直接包含 OpenCV, 需要 conda install (menpo) reposite.

Enthought Canopy 是有包 OpenCV 2.4.9 (舊的版本).  如果要用最新的版本 (3.1.0 at 2016/5/11), 還是要自己 compile.

 

因為 OpenCV 仍然持續 evolve.  為了要得到最新版本,還是要知道如何 compile source code.

 

Step #1: Install dependencies

The first thing we should do is update and upgrade any existing packages, followed by updating the Raspberry Pi firmware.

Timing: 3m 33s

You’ll need to reboot your Raspberry Pi after the firmware update:

Now we need to install a few developer tools:

Timing: 51s

Now we can move on to installing image I/O packages which allow us to load image file formats such as JPEG, PNG, TIFF, etc.:

Timing: 42s

Just like we need image I/O packages, we also need video I/O packages. These packages allow us to load various video file formats as well as work with video streams:

Timing: 58s

We need to install the GTK development library so we can compile the highgui  sub-module of OpenCV, which allows us to display images to our screen and build simple GUI interfaces:

Timing: 2m 48s

Various operations inside of OpenCV (such as matrix operations) can be optimized using added dependencies:

Timing: 50s

Lastly, we’ll need to install the Python 2.7 and Python 3 header files so we can compile our OpenCV + Python bindings:

 

Step #2: Grab the OpenCV source code

At this point we have all of our prerequisites installed, so let’s grab the 3.1.0  version of OpenCV from the OpenCV repository. (Note: As future versions of OpenCV are released just replace the 3.1.0  with the most recent version number):

Timing: 2m 29s

For the full install of OpenCV 3 (which includes features such as SIFT and SURF), be sure to grab the opencv_contrib repo as well. (Note: Make sure your opencv  and opencv_contrib  versions match up, otherwise you will run into errors during compilation. For example, if I download v3.0.0 of opencv , then I’ll want to download v3.0.0 of opencv_contrib  as well):

Timing: 1m 54s

Step #3: Setup Python

The first step in setting up Python for our OpenCV compile is to install pip , a Python package manager:

Timing: 26s

I’ve discussed both virtualenv and virtualenvwrapper many times on the PyImageSearch blog before, especially within these installation tutorials. Installing these packages is certainly not a requirement to get OpenCV and Python up and running on your Raspberry Pi, but I highly recommend that you install them!

Using virtualenv  and virtualenvwrapper  allows you to create isolated Python environments, separate from your system install of Python. This means that you can run multiple versions of Python, with different versions of packages installed into each virtual environment — this solves the “Project A depends on version 1.x, but Project B needs 4.x” problem that often arises in software engineering.

Again, it’s standard practice in the Python community to use virtual environments, so I highly suggest that you start using them if you are not already:

Timing: 17s

After virtualenv  and virtualenvwrapper  have been installed, we need to update our~/.profile  file and insert the following lines at the bottom of the file:

You can use your favorite editor to edit this file, such as vim , emacs , nano , or any other graphical editor included in the Raspbian Jessie distribution. Again, all you need to do is open the file located at /home/pi/.profile  and insert the lines above at the bottom of the file.

Now that your ~/.profile  has been updated, you need to reload it so the changes can take affect. To force a reload of the ~/.profile  file you can (1) logout and log back in, (2) close your terminal and open up a new one, or (3) just use the source  command:

Note: You’ll likely need to run the source ~/.profile  command each time you open up a new terminal to ensure your environment has been setup correctly.

The next step is to create our Python virtual environment where we’ll be doing our computer vision work:

The above command will create a virtual environment named cv  using Python 2.7.

If you want Python 3, run this command instead:

Again, it’s important to note that the cv  Python environment is entirely independent from the default version of Python included in the download of Raspbian Jesse.

If you ever reboot your system, logout and log back in, or open up a new terminal, you’ll need to use the workon  command to re-access the cv  virtual environment, otherwise you’ll be using the system version of Python instead:

You can ensure you are in the cv  virtual environment by examining your command line. If you see the text “(cv)” preceding your prompt, then you are in the cv  virtual environment:

Figure 1: Make sure you see the "(cv)" text on your prompting, indicating that you are in the cv virtual environment.

Figure 1: Make sure you see the “(cv)” text on your prompting, indicating that you are in the cv virtual environment.

Otherwise, you are not in the cv  virtual environment:

Figure 2: If you do not see the "(cv)" text on your prompt, then you are not in the cv virtual environment.

Figure 2: If you do not see the “(cv)” text on your prompt, then you are not in the cv virtual environment.

If this is the case, you need to run the source  and workon  commands above.

Assuming that you are in the cv  virtual environment, we can install NumPy, an important dependency when compiling the Python bindings for OpenCV. You might want to grab a cup of coffee or go for a walk while NumPy downloads and installs:

Timing: 16m 10s

Step #4: Compile and install OpenCV

At this point, we are ready to compile OpenCV.

First, make sure you are in the cv  virtual environment:

Followed by setting up the build:

Update (3 January 2016): In order to build OpenCV 3.1.0 , you need to set -DINSTALL_C_EXAMPLES=OFF  (rather than ON ) in the cmake  command. There is a bug in the OpenCV v3.1.0 CMake build script that can cause errors if you leave this switch on. Once you set this switch to off, CMake should run without a problem.

Before you move on to the compilation step, make sure you examine the output of CMake!

Scroll down the section titled Python 2  and Python 3 .

If you’re compiling OpenCV 3 for Python 2.7, then you’ll want to make sure the Python 2  section looks like this (highlighted) in red:

Figure 3: Ensuring that Python 2.7 will be used for the compile.

Figure 3: Ensuring that Python 2.7 will be used for the compile.

Notice how both the Interpreter  and numpy  variables point to the cv  virtual environment.

Similarly, if you’re compiling OpenCV for Python 3, then make sure the Python 3  section looks like this:

Figure 4: Ensuring that Python 3 will be used for the compile.

Figure 4: Ensuring that Python 3 will be used for the compile.

Again, both the Interpreter  and numpy  variables are pointing to our cv  virtual environment.

In either case, if you do not see the cv  virtual environment for these variables MAKE SURE YOU ARE IN THE cv  VIRTUAL ENVIRONMENT PRIOR TO RUNNING CMAKE!

Now that our build is all setup, we can compile OpenCV:

Timing: 1h 35m

The -j4  switch stands for the number of cores to use when compiling OpenCV. Since we are using a Raspberry Pi 2, we’ll leverage all four cores of the processor for a faster compilation.

However, if your make  command errors out, I would suggest starting the compilation over again and only using one core:

Using only one core will take much longer to compile, but can help reduce any type of strange race dependency condition errors when compiling.

Assuming OpenCV compiled without error, all we need to do is install it on our system:

 

Step #5: Finishing the install

We’re almost there! Just a few more things and we’ll be 100% done.

For Python 2.7:

Provided you finished Step #4 without error, OpenCV should now be installed in/usr/local/lib/python2.7/site-packages :

Note: In some instances OpenCV can be installed in /usr/local/lib/python2.7/dist-packages  (note the dist-packages  rather than site-packages ). If you do not find thecv2.so  bindings in site-packages , be sure to check dist-packages  as well.

The last step here is to sym-link the OpenCV bindings into the cv  virtual environment:

 

For Python 3:

OpenCV should now be installed in /usr/local/lib/python3.4/site-packages :

For some reason, unbeknownst to me, when compiling the Python 3 bindings the output .so  file is named cv2.cpython-34m.so  rather than cv2.so .

Luckily, this is an easy fix. All we need to do is rename the file:

Followed by sym-linking OpenCV into our cv  virtual environment:

 

Step #6: Verifying your OpenCV 3 install

At this point, OpenCV 3 should be installed on your Raspberry Pi running Raspbian Jessie!

But before we wrap this tutorial up, let’s verify that your OpenCV installation is working by accessing the cv  virtual environment and importing cv2 , the OpenCV + Python bindings:

You can see a screenshot of my terminal below, indicating that OpenCV 3 has been successfully installed:

Figure 5: OpenCV 3 + Python 3 bindings have been successfully installed on my Raspberry Pi 2 running Rasbian Jessie.

Figure 5: OpenCV 3 + Python 3 bindings have been successfully installed on my Raspberry Pi 2 running Rasbian Jessie.

 

 

追蹤者