tata色々な備忘録

データ解析、画像解析、化学分析などなど

Vagrant+VirtualBox環境の構築2(CentOS)

python2.7のインストール
参考
http://3rd-tl.blogspot.jp/2013/05/centosyumpython.html

$ sudo rpm -ivh http://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/epel-release-6-5.noarch.rpm
$ sudo rpm -ivh http://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/ius-release-1.0-11.ius.centos6.noarch.rpm 
$ sudo yum install python27

依存パッケージのインストール

#png jpg tiff
$ sudo yum install libpng-devel libjpeg-devel  png, jpeg
$ sudo yum install libtiff-devel
#GUIサポート
$ sudo yum install gtk2-devel  
#java
$ sudo yum install java-1.6.0-openjdk java-1.6.0-openjdk-devel ant
#ffmpeg
$ sudo yum install --enablerepo=rpmforge ffmpeg-devel 

$ sudo yum install blas-devel
$ sudo yum install lapack-devel
$ sudo yum install python27-devel

numpy
http://sourceforge.net/projects/numpy/files/NumPy/1.7.1/numpy-1.7.1tar.gz

$ cd /vagrant/numpy-1.7.1
$ sudo python2.7 setup.py build
$ sudo python2.7 setup.py install

opencvのソースファイル取得

#gitインストール
$ sudo yum install git
#Opencvのソース取得
$ git clone git://github.com/Itseez/opencv.git

時刻エラー対策

$ sudo rm -f /etc/localtime
$ sudo  cp -p /usr/share/zoneinfo/Japan /etc/localtime
$ date
$ sudo yum -y install ntp 
$ sudo yum ntpdate ntp.nict.jp 

cmake2.8.9
http://rpm.pbone.net/index.php3/stat/4/idpl/21801907/dir/centos_6/com/cmake-2.8.9-3.1.x86_64.rpm.html

共有フォルダへコピーして移動

#共有フォルダへ移動
$cd /vagrant
$sudo yum localinstall  cmake-2.8.9-3.1.x86_64.rpm

make
参考
http://rest-term.com/technote//index.php/OpenCV%20-%202.x

#opencvフォルダへ移動
$ cd ~/opencv
#cmake
$ cmake -D CMAKE_C_COMPILER=/usr/bin/gcc\
        -D CMAKE_BUILD_TYPE=RELEASE \
        -D CMAKE_INSTALL_PREFIX=/usr/local/ \
        -D BUILD_opencv_world=ON \
        -D BUILD_NEW_PYTHON_SUPPORT=ON \
        -D PYTHON_EXECUTABLE=/usr/bin/python2.7\
        -D PYTHON_LIBRARY=/usr/lib64/libpython2.7.so.1.0\
        -D PYTHON_INCLUDE_PATH=/usr/include/python2.7 \
        -D HAVE_OPENMP=ON \
        -D BUILD_EXAMPLES=ON \
        -D INSTALL_C_EXAMPLES=ON \
        -D INSTALL_PYTHON_EXAMPLES=ON .
#4コアでmake(j+使用コア数)
$ make -j4
#中間ファイルの削除(数ギガある)
$ make clean
$ sudo make install

エイリアスの設定

$ cd ~
$ vi .bashrc
# User specific aliases and functions
#追記
alias python='python2.7' 
export PYTHONPATH=/usr/local/lib/
export PYTHONPATH=/usr/local/lib/python2.7/site-packages
$ souce .bashrc
$ which python #確認

scipy+Opencv+numpyによる画像分類2

切り出したイメージからの続き。

import numpy as np
import cv2
import matplotlib.pyplot as plt
 
im = cv2.imread('bubbles.jpg')
im2 = cv2.imread('bubble2.jpg',0)

imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,100,255,0)

contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

i=3
for h,cnt in enumerate(contours):
    area = cv2.contourArea(cnt)
    if area >10000:
        mask = np.zeros(imgray.shape,np.uint8)
        cv2.drawContours(mask,[cnt],0,255,-1)
        #mean = cv2.mean(im2,mask = mask)
        #print mean
        plt.subplot(3,3,i),plt.imshow(mask,'gray')
        plt.axis('off')
        i+=1
        if i == 10:
            break
    else:
        pass
plt.subplot(3,3,3),plt.imshow(im2,'gray')
plt.axis('off')
plt.subplot(3,3,2),plt.hist(im.flat,bins=255,range=(0,255))
plt.subplot(3,3,1),plt.imshow(im,'gray')
plt.axis('off')

plt.show()  

f:id:tatabox2000:20130812013132p:plain

マスク画像が出来た。

mask2 =np.asarray(mask,np.bool8)
bubbles[-mask2]=0

で元画像をマスク出来る。

後日修正予定。

参考
http://opencvpython.blogspot.jp/2012/06/hi-this-article-is-tutorial-which-try.html

scipy+Opencv+numpyによる画像分類

ヒストグラムを利用した分類法。
定番っすね。

import cv2
import numpy as np
import pylab as plt
import scipy.ndimage as nd

def mask_test(im):
    if im.ndim == 2:
        im2= im[0:890,:]
        im_gray = im2

    else :
        im2= im[0:890,:]
        im_gray =cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
    im_gray_smooth=cv2.medianBlur(im_gray,5)
        
    bubbles = (im_gray_smooth <= 50) 
    sand = (im_gray_smooth > 50) & (im_gray_smooth <= 110)
    glass = (im_gray_smooth > 110)
     
    for img in (bubbles,sand,glass):
        img[:] = nd.binary_opening(img, iterations=3)
        img[:] = nd.binary_closing(img, iterations=3)
    
    colors = np.zeros((im2.shape[0],im2.shape[1],3),np.uint8)
    colors[bubbles]= (100,100,200)
    colors[sand]= (255,0,0)
    colors[glass]= (0,255,0)
        
    list = [('picture',im),('gray',im_gray),('gray_smooth',im_gray_smooth),('dummpy','dummy'),('glass',glass),('sand',sand),('bubbles',bubbles),('color',colors)]
    i=1
    for name,data in list :
        if i == 4:
            i += 1
        else:
            plt.subplot(2,4,i),plt.imshow(data,'gray')
            plt.title(name)
            plt.axis('off')
            i += 1

    plt.subplot(2,4,4),plt.hist(im_gray.flat,bins=80,range=(0,150))
    plt.show()
        
if __name__ == '__main__':
    im = cv2.imread("babble.jpg")
    if not (im == None):
        mask_test(im)

f:id:tatabox2000:20130811214629p:plain 後で修正予定。

参考
Scikit-Image
http://vimeo.com/53065496
Scipyチュートリアル
http://www.ike-dyn.ritsumei.ac.jp/~uchida/scipy-lecture-notes/intro/summary-exercises/answers_image_processing.html

Sublime text2の環境構築2

sublime textでmatplotlibやopencvを実行する。

sublime textを立ちあげ、 Preferences⇒packages folder⇒ pythonPython.sublime-build を開く

{
    "cmd": ["python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "env":{"PYTHONPATH":"C:/Python27/Lib/site-packages"},
    "selector": "source.python",
    "shell":true
}

"shell":true の行を追記した。

参考

http://stackoverflow.com/questions/10831882/matplotlib-plots-not-displaying-in-sublimetext

http://docs.sublimetext.info/en/latest/

python+Opencvによる画像処理11(フーリエ変換2、カラー)

2次元フーリエのコード、 numpy使うと非常に簡単でした……

import cv2
import numpy as np
import pylab as plt

im = cv2.imread('lena.jpg',)

im1 = im[:,:,::-1].copy()

im_RGB = cv2.split(im1)

plt.subplot(1,4,1),plt.imshow(im1)

j = 2

title = ('Red','Green','Blue')

for i in im_RGB:
    F= np.fft.fft2(i)
    F_= np.log(5 + np.fft.fftshift(np.abs(F)))

    plt.subplot(1,4,j),plt.imshow(F_)

    plt.title(title[j-2])
    j =j + 1
plt.show()

f:id:tatabox2000:20130729010902p:plain

python+Opencvによる画像解析1(ORB特徴量)

フリーの局所画像記述子であるORBによる特徴抽出

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('lena.jpg',0)

# 検出器の初期化
orb = cv2.ORB()


# 特徴量の検出と出力用の計算
kp, des = orb.detectAndCompute(img, None)

# 特徴の描画
img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0)
plt.imshow(img2)
plt.show()

f:id:tatabox2000:20130728055247p:plain

#検出器
cv2.SIFT() 
cv2.BRISK()
cv2.ORB()
cv2.SURF()

#他にもFASTとMSERが使用可能

orb =cv2.ORB()
kp = orb.detect(img)
kp,des =orb.detectAndCompute(img,none)

#cv2.ORB.compute() は2.4.6で動かない(バグ?)