conta's diary

思ったこと、やったことを書いてます。 twitter: @conta_

numpy.arrayをテキスト出力

c++からnumpyで作成したデータを読みたかったのでテキスト出力をつくる。

今回は

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

みたいな配列を

3 3
0 1 2
3 4 5
6 7 8

のような形でtext出力するものをつくる。

numpy.savetxtという関数が便利そうなのでつかってみる。

A = numpy.arange(9).reshape(3,3)
numpy.savetxt('test.txt', A)

結果。

0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00   

なるほど。


ヘッダーとフッターを付ける機能があるみたいなので付けてみる。

header = '{0} {1}'.format(A.shape[0], A.shape[1])
numpy.savetxt('test.txt', A, header=header)

結果

# 3 3
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00  


ほう、コメントついちゃう感じか。オプションのところにこう書いてあった。

comments : str, optional
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt. .. versionadded:: 1.7.0

commentsオプションをいじって

header = '{0} {1}'.format(A.shape[0], A.shape[1])
numpy.savetxt('test.txt', A, header=header, comments='')

結果

3 3
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00  


めでたしめでたし。
もっといじれば任意のフォーマットで出せるね!

*参考
http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt

1Passwordの入力フォームカスタムテンプレートを作成する

1Password 4.0リリースおめでとございます。
ちょっと使い勝手が良くなった!

簡単なサーバーの管理に1Passwordを使っているのだけれど、デフォルトのテンプレートがイケてない!
改造して1Passwordの入力フォームカスタムテンプレートを作成してみよう(・∀・)↑

とりあえず1Passwordのアプリ中を右クリック->Show Package Contentsで覗いてみる。
たいていの設定ファイルはそういうところに入っているのである。
怪しいフォルダ発見!
/Applications/1Password.app/Contents/Resources/CategoryTemplates/

/Applications/1Password.app/Contents/Resources/CategoryTemplates/Server.templateを覗いてみる。

{
    "uuid": "110",
    "localized": "yes",
    "hidden": "yes",
    "subtitle": "username",
    "icons": {
        "list": "type-server-list",
        "detail": "type-server-details"
    },
    "contents": [
        {
            "set": "",
            "disclosed": "yes",
            "fields": [
                {
                    "name": "url",
                    "type": "string"
                },
                {
                    "name": "username",
                    "type": "string",
                    "isUsername": "yes"
                },
                {
                    "name": "password",
                    "type": "concealed"
                }
            ]
        },
        {
            "set": "admin_console",
            "disclosed": "yes",
            "fields": [
                {
                    "name": "admin_console_url",
                    "type": "string"
                },
                {
                    "name": "admin_console_username",
                    "type": "string",
                    "isUsername": "yes"
                },
                {
                    "name": "admin_console_password",
                    "type": "concealed"
                }
            ]
        },
        {
            "set": "hosting_provider_details",
            "disclosed": "yes",
            "fields": [
                {
                    "name": "name",
                    "type": "string"
                },
                {
                    "name": "website",
                    "type": "string"
                },
                {
                    "name": "support_contact_url",
                    "type": "string"
                },
                {
                    "name": "support_contact_phone",
                    "type": "string"
                }
            ]
        }
    ]
}

ほう、変更してみよう。

/Applications/1Password.app/Contents/Resources/CategoryTemplates/Server.templateのコピーをとってから編集。。。


こんなかんじにしてみた。

{
    "uuid": "110",
    "localized": "yes",
    "hidden": "yes",
    "subtitle": "username",
    "icons": {
        "list": "type-server-list",
        "detail": "type-server-details"
    },
    "contents": [
        {
            "set": "",
            "disclosed": "yes",
            "fields": [
                {
                    "name": "IP",
                    "type": "string"
                },
                {
                    "name": "username",
                    "type": "string",
                    "isUsername": "yes"
                },
                {
                    "name": "password",
                    "type": "concealed"
                },
                {
                    "name": "port",
                    "type": "string"
                }
            ]
        },
        {
            "set": "admin_console",
            "disclosed": "yes",
            "fields": [
                {
                    "name": "username",
                    "type": "string"
                },
                {
                    "name": "password",
                    "type": "concealed",
                    "isUsername": "yes"
                },
                {
                    "name": "OS",
                    "type": "string"
                }
            ]
        }
    ]
}

書き換えたら一応ここJSONLint - The JSON Validator.でValidateして、間違いがないか確認する。

1Passwordを再起動してテンプレートから新規作成!

結果
f:id:contaconta:20131004014625p:plain

できた!

もしかするとアプリをアップデートするたびに書きなおさないといけないかもね(´・ω・`)

*補足1
なぜか一番初めの"contents": [ { "set": "",の部分に文字をセットするとset.〜になってしまう。バグなのかなんなのか。
*補足2
ServerCustom.templateというものを同じフォルダ内に作ったけど読み込んでくれないっぽい。"uuid": "110"も変えてみたけどだめ。
今あるテンプレートを改造しないとダメなのかね。


*くれぐれも自己責任でお願い致します。

*参考How to define a new wallet item in 1Password

ubuntuでVNCサーバーを構築+sshポートフォワーディングによるアクセス

環境

client : Mac OSX 10.7
server: Ubuntu server 12.04

install

# desktop
sudo apt-get install --no-install-recommends ubuntu-desktop

# vnc server
sudo apt-get install vnc4server

--no-install-recommendsを指定すると、余計なパッケージが入らなくなる

一旦起動(設定ファイル作成)

vncserver :1

*初回起動時にパスワードを入力する

すると、~/.vnc/ができる

一旦止める

vncserver -kill :1

設定

設定ファイルを変更して、unityモードで起動できるようにする。

emacs ~/.vnc/xstartup 

設定ファイルの最後に下記を追加

gnome-session --session=ubuntu-2d &

パスワードを変更したい場合は

sudo vncpasswd /etc/vncpass

うまくいかないときは下記コマンドパスワードを削除。
次回起動時に初回起動時と同様の形でパスワードを聞かれる。

rm ~/.vnc/passwd

起動&停止

初期設定のポート番号は起動時のスクリーン番号になる。
vncserver :1 なら5901
vncserver :2 なら5902

# start
vncserver -geometry 1280x720 :1

# kill
vncserver -kill :1

接続

macならFinderを開いて"cmd+K"をすれば”Connect to Server”というウィンドウが立ち上がるので下記を入力して接続。

vnc://user@192.168.111.123:5901

あとはPasswordを入力すればログイン成功〜
f:id:contaconta:20130807173059p:plain

SSHでポートフォワーディング

クライアントのターミナル上で下記のように入力

ssh -N username@192.168.111.123 -L 8888:192.168.111.123:5901

これでssh接続するとlocalhost:8888 ->192.168.111.123:5901に転送される。

あとは、クライアント上で下記へアクセスすればログイン出来る。

vnc://localhost:8888

OpenNIで取得した画像をOpenCVで利用する

DepthとColorの画像を解析したかったので、作ってみた。

color

注意点はRGBで流れてくるので、BGRへ変換する必要がある

cv::Mat getColorImage(openni::VideoFrameRef& color_frame)
{
  if(!color_frame.isValid())
  {
    return cv::Mat();
  }
  openni::VideoMode video_mode = color_frame.getVideoMode();
  cv::Mat color_img = cv::Mat(video_mode.getResolutionY(),
                              video_mode.getResolutionX(),
                              CV_8UC3, (char*)color_frame.getData());
  cv::Mat ret_img;
  cv::cvtColor(color_img, ret_img, CV_RGB2BGR);
  return ret_img;
}

depth

0 - 10000mmの値が各ピクセルに入ってくる。CV_16Uで受け取ってあげる。
あと、getData()で受け取った値をそのままMatで使うと元のデータが書き換わるので、cloneして渡しておく。

// CV_16U
cv::Mat getDepthImage(openni::VideoFrameRef& depth_frame)
{
  if(!depth_frame.isValid())
  {
    return cv::Mat();
  }

  openni::VideoMode video_mode = depth_frame.getVideoMode();
  cv::Mat depth_img = cv::Mat(video_mode.getResolutionY(),
                              video_mode.getResolutionX(),
                              CV_16U, (char*)depth_frame.getData());
  return depth_img.clone();
}

CMakeLists.txt

こんな感じで書いてみた。

project(OpenNI_OpenCV_Viewer)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})


##########################
# opencv
##########################
set(OpenCV_DIR "/usr/local/opencv/share/OpenCV/OpenCVConfig.cmake"
    CACHE PATH "The path where OpenCVConfig.cmake is placed")
find_package(OpenCV REQUIRED)
if(OpenCV_FOUND)
  message(STATUS "Found 'opencv library' ${OpenCV_VERSION}")
else()
  message(FATAL_ERROR "Couldn't find OpenCV")
endif()

##########################
# OpenNI
##########################
include_directories("~/OpenNI-2.1.0/Include")
find_library(OPENNI_LIBRARY
             NAMES OpenNI2
             HINTS "~/OpenNI-2.1.0/Redist"
             PATHS "$ENV{PROGRAMFILES}/OpenNI/Lib${OPENNI_SUFFIX}" "$ENV{PROGRAMW6432}/OpenNI/Lib${OPENNI_SUFFIX}"
             PATH_SUFFIXES lib
)
link_directories("~/OpenNI-2.1.0/Redist")

if(APPLE)
  set(OPENNI_LIBRARIES ${OPENNI_LIBRARY} usb)
else()
  set(OPENNI_LIBRARIES ${OPENNI_LIBRARY})
endif()

target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
target_link_libraries(${PROJECT_NAME} ${OPENNI_LIBRARY})

一応動くソース。

これは、depthをcolorに合わせてキャリブレーションしてくれるっぽい。

device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);


下記ソース。

#include <iostream>
#include <OpenNI.h>
#include <opencv2/opencv.hpp>

using namespace std;


cv::Mat getColorImage(openni::VideoFrameRef& color_frame)
{
  if(!color_frame.isValid())
  {
    return cv::Mat();
  }
  openni::VideoMode video_mode = color_frame.getVideoMode();
  cv::Mat color_img = cv::Mat(video_mode.getResolutionY(),
                              video_mode.getResolutionX(),
                              CV_8UC3, (char*)color_frame.getData());
  cv::Mat ret_img;
  cv::cvtColor(color_img, ret_img, CV_RGB2BGR);
  return ret_img;
}


// CV_16U
cv::Mat getDepthImage(openni::VideoFrameRef& depth_frame)
{
  if(!depth_frame.isValid())
  {
    return cv::Mat();
  }

  openni::VideoMode video_mode = depth_frame.getVideoMode();
  cv::Mat depth_img = cv::Mat(video_mode.getResolutionY(),
                              video_mode.getResolutionX(),
                              CV_16U, (char*)depth_frame.getData());
  return depth_img.clone();
}


cv::Mat getDepthDrawableImage(cv::Mat depth_image)
{
  cv::Mat drawable;
  depth_image.convertTo(drawable, CV_8UC1, 255.0/10000);
  drawable = 255 - drawable; // 近い方を白に
  return drawable;
}


int main()
{
  openni::Device device;
  openni::VideoStream color_stream, depth_stream;
  const char* deviceURI = openni::ANY_DEVICE;

  openni::Status rc = openni::STATUS_OK;

  rc = openni::OpenNI::initialize();

  cout << "After initialization:" << openni::OpenNI::getExtendedError();

  rc = device.open(deviceURI);
  if (rc != openni::STATUS_OK)
  {
    cout << "SimpleViewer: Device open failed:" << openni::OpenNI::getExtendedError();
    openni::OpenNI::shutdown();
    return 1;
  }

  rc = depth_stream.create(device, openni::SENSOR_DEPTH);
  if (rc == openni::STATUS_OK)
  {
    rc = depth_stream.start();
    if (rc != openni::STATUS_OK)
    {
      cerr << "SimpleViewer: Couldn't start depth stream:" << openni::OpenNI::getExtendedError();
      depth_stream.destroy();
    }
  }
  else
  {
    cerr << "SimpleViewer: Couldn't find depth stream:" << openni::OpenNI::getExtendedError();
  }

  rc = color_stream.create(device, openni::SENSOR_COLOR);
  if (rc == openni::STATUS_OK)
  {
    rc = color_stream.start();
    if (rc != openni::STATUS_OK)
    {
      cerr << "SimpleViewer: Couldn't find color stream:" << openni::OpenNI::getExtendedError();
      color_stream.destroy();
    }
  }
  else
  {
    cerr << "SimpleViewer: Couldn't find color stream:" << openni::OpenNI::getExtendedError();
  }

  if (!depth_stream.isValid() || !color_stream.isValid())
  {
    cerr << "SimpleViewer: No valid streams. Exiting" << std::endl;
    openni::OpenNI::shutdown();
    return 2;
  }


  std::vector<openni::VideoStream*> streams;
  streams.push_back(&color_stream);
  streams.push_back(&depth_stream);

  openni::VideoFrameRef color_frame;
  openni::VideoFrameRef depth_frame;

  device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);

  while(true)
  {
    int changedIndex;
    openni::Status rc = openni::OpenNI::waitForAnyStream(&streams[0], streams.size(), &changedIndex);
    if (rc != openni::STATUS_OK)
    {
      cerr << ("Wait failed\n");
      return -1;
    }

    switch(changedIndex)
    {
      case 0:
        color_stream.readFrame(&color_frame);
        break;

      case 1:
        depth_stream.readFrame(&depth_frame);
        break;

      default:
        cout << "Error in wait" << endl;
    }

    cv::Mat color_img;
    if(color_frame.isValid())
    {
      color_img = getColorImage(color_frame);
      cv::imshow("color", color_img);
    }

    cv::Mat depth_img;
    if(depth_frame.isValid())
    {
      depth_img = getDepthImage(depth_frame);
      cv::Mat depth_img_debug = getDepthDrawableImage(depth_img);
      cv::imshow("depth", depth_img_debug);
    }

    if(!depth_img.empty() && !color_img.empty())
    {
      cv::Mat depth_img_debug = getDepthDrawableImage(depth_img);
      cv::cvtColor(depth_img_debug, depth_img_debug, cv::COLOR_GRAY2BGR);
      cv::Mat debug_img = color_img * 0.5 + depth_img_debug * 0.5;
      cv::imshow("blend", debug_img);
    }

    int key = cv::waitKey(1);
    if( key == 'q' )
    {
      break;
    }
  }
  return 0;
}

適当に書いたけど動いた!
ちょっとカクつくことがあるが、colorとdepthを使う方法が悪いのかな?

Ubuntu 12.04にEthernet Driver(AR8161用)をインストール

ASUSP8H77-Vというマザーボードを購入してUbuntuをインストールいたのだけれどEthernetを認識してくれない!
ifconfigしてもlocal loopbackしかでてこないので原因を探ってみたら、
これに利用されているAR8161 Gigabit Ethernetというドライバが新しいらしく
OSに組み込まれていないらしい。Ubuntu Server 12.04.2からインストールしたら行けるよ!とどっかのサイトに書いてあったが、全然いけませんでした。Ubuntuインストール後wirelessネットワークでapt-get upgradeしても動かず。。。
結局ここを参考にドライバをDLしてインストールしました。

どういう状況かチェック

まずハードウェアの状態をチェック。

sudo lshw -class network
  *-network UNCLAIMED    
       description: Ethernet controller
       product: AR8161 Gigabit Ethernet
       vendor: Atheros Communications Inc.
       physical id: 0
       bus info: pci@0000:03:00.0
       version: 10
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi msix bus_master cap_list
       configuration: latency=0
       resources: memory:f7c00000-f7c3ffff ioport:e000(size=128)
  *-network
       description: Wireless interface
       physical id: 2
       bus info: usb@3:4
       logical name: wlan0
       serial: 10:6f:3f:c7:02:48
       capabilities: ethernet physical wireless
       configuration: broadcast=yes driver=rt2800usb driverversion=3.5.0-23-generic firmware=0.29 ip=192.168.111.5 link=yes multicast=yes wireless=IEEE 802.11bgn

UNCLAIMEDはドライバーがないですヨーということらしい。

ドライバーのインストール

ドライバーのビルドに必要なモノをインストール

sudo apt-get install build-essential linux-headers-generic linux-headers-`uname -r`

alx | The Linux Foundationから
最新のドライバーをゲット。

wget https://www.kernel.org/pub/linux/kernel/projects/backports/2013/03/04/compat-drivers-2013-03-04-u.tar.bz2

解凍してから下記コマンドでビルド&インストール

./scripts/driver-select alx
make
sudo make install

あとはethernetDHCPを自動に設定

sudo vi /etc/network/interfaces

下記を書き込む

auto eth0
iface eth0 inet dhcp

そしてリブートしてみる。


立ち上がったらifconfigで確認。

ifconfig 
eth0      Link encap:Ethernet  HWaddr ---  
          inet addr:192.168.111.19  Bcast:192.168.111.255  Mask:255.255.255.0
          inet6 addr: fe80::62a4:4cff:feac:4833/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:132 errors:0 dropped:0 overruns:0 frame:0
          TX packets:83 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:16913 (16.9 KB)  TX bytes:11133 (11.1 KB)
          Interrupt:16

lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

wlan0     Link encap:Ethernet  HWaddr ---  
          inet addr:192.168.111.5  Bcast:192.168.111.255  Mask:255.255.255.0
          inet6 addr: fe80::126f:3fff:fec7:248/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:64 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:18791 (18.7 KB)  TX bytes:1490 (1.4 KB)

動いた!良かった!
USBのwirelessLanがなかったら積んでたな(・・;
そのうちOSにドライバーが組み込まれることを祈ってます。

*参考Atheros AR8161 Ethernet card not working on 12.10 on an ASUS N56VM - Ask Ubuntu

ubuntu 12.04にboostとmongo c++ driver をインストール

boost 1.49をインストール

MongoDBの公式ページにBoostのバージョンは1.49推奨と書いてあるので、1.49を入れる。
(以前Macで最新のboostを使ってドライバーをインストールしたらビルドが通らなかった。)

wget http://downloads.sourceforge.net/project/boost/boost/1.49.0/boost_1_49_0.tar.bz2
tar jzfv boost_1_49_0.tar.bz2
cd boost_1_49_0
./bootstrap.sh --prefix=/usr/local/boost
sudo ./b2 install

これで完了

*参考Boost Getting Started on Unix Variants - 1.53.0

mongoのインストール

Ubuntu のデフォルトパッケージからmongodbを入れるとboost1.46のライブラリをインストールしようとするので、最新版のmongodbを引っ張ってくる。

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

/etc/apt/sources.list.d/10gen.listを作成して下記を追加。

deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen

アップデート

sudo apt-get update

インストール

sudo apt-get install mongodb-10gen

*参考http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

mongodb c++ driverのインストール

ここDownloads for cxx-driverからドライバーをDLしてきてインストール。

wget http://downloads.mongodb.org/cxx-driver/mongodb-linux-x86_64-2.4.3.tgz
tar zxfv mongodb-linux-x86_64-2.4.3.tgz
cd mongo-cxx-driver-v2.4
sudo scons --prefix=/usr/local/mongo  --extrapath=/usr/local/boost install

*参考http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-cpp-driver/

これで快適Mongo生活!

Ubuntu server 12.04にNvidia CUDAをインストールしてOpenCVのgpuモジュールを利用する

1.ドライバーのインストール

リポジトリを追加してインストール。

sudo apt-add-repository ppa:ubuntu-x-swat/x-updates
sudo apt-get update 
sudo apt-get install nvidia-current

2.CUDAのインストール

CUDAの公式サイトCUDA Downloads | NVIDIA Developer Zoneから、最新のものをDLする。最新のものは11.10になっているけど、12.04に入れても大丈夫かな?

wget http://developer.download.nvidia.com/compute/cuda/5_0/rel-update-1/installers/cuda_5.0.35_linux_64_ubuntu11.10-1.run

下記コマンドにてインストール。

sudo zsh ./cuda_5.0.35_linux_64_ubuntu11.10-1.run

Agreement的なものがでるけど、よく読んで"s"ボタンでスキッp"accept"と入力。
ドライバーはインストールしているので”n”を入力、後は"y"を入力。

下記出力結果。

===========
= Summary =
===========

Driver:   Not Selected
Toolkit:  Installed in /usr/local/cuda-5.0
Samples:  Installed in /usr/local/cuda-5.0/samples (pristine) and /home/===/NVIDIA_CUDA-5.0_Samples (writable)

* Please make sure your PATH includes /usr/local/cuda-5.0/bin
* Please make sure your LD_LIBRARY_PATH *   for 32-bit Linux distributions includes /usr/local/cuda-5.0/lib
*   for 64-bit Linux distributions includes /usr/local/cuda-5.0/lib64:/lib
* OR
*   for 32-bit Linux distributions add /usr/local/cuda-5.0/lib
*   for 64-bit Linux distributions add /usr/local/cuda-5.0/lib64 and /lib
* to /etc/ld.so.conf and run ldconfig as root
 * To uninstall CUDA, remove the CUDA files in /usr/local/cuda-5.0
* Installation Complete

Please see CUDA_Getting_Started_Guide_For_Linux.pdf in /usr/local/cuda-5.0/doc/pdf for detailed information on setting up CUDA.

***WARNING: Incomplete installation! This installation did not install the CUDA Driver. A driver of version at least 304.54 is required for CUDA 5.0 functionality to work.
            To install the driver using this installer, run the following command, replacing <CudaInstaller> with the name of this run file:
                sudo <CudaInstaller>.run -silent -driver

ここで、

Driver:   Not Selected
Toolkit:  Installed in /usr/local/cuda-5.0
Samples:  Installation Failed. Missing required libraries.

となっていて、"Missing required library libglut.so"というログが残っている場合には、

sudo ln -s /usr/lib/x86_64-linux-gnu/libglut.so.3 /usr/lib/libglut

でうまくいくらしい。

もし、glutが入ってなければ下記コマンドでインストール。

sudo apt-get install freeglut3 freeglut3-dev

*参考How to Install OpenGL/Glut libraries in Ubuntu 12.04 | Singh Gurjot


インストール後、CUDAのパスを通す。

export PATH=/usr/local/cuda-5.0/bin:${PATH}
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/cuda-5.0/lib64:/usr/local/cuda-5.0/lib

3.CUDAサンプルのビルド

NVIDIA_CUDA-5.0_Samplesにサンプルがインストールされるらしいので、試しにビルドしてみる。

cd ~/NVIDIA_CUDA-5.0_Samples
make

ここで、

 /usr/bin/ld: cannot find -lcuda

と言われたので、

LIBRARY_PATH=/usr/lib/nvidia-current:$LIBRARY_PATH

を追加。

*サンプルを全部ビルドしたい場合はOpen MPI 関連のパッケージも必要。
下記コマンドでインストール。

sudo apt-get install openmpi-bin openmpi-dev

4. OpenCVでgpuモジュールをビルド

cmakeのオプションをWITH_CUDA=ONにして実行。

下記のように怒られた。

CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
CUDA_nvcuvid_LIBRARY (ADVANCED)
    linked by target "opencv_gpu" in directory /home/XXX/opencv/OpenCV-2.4.3/modules/gpu

-- Configuring incomplete, errors occurred!

下記のように対応。

sudo ln -s /usr/lib/nvidia-current/libnvcuvid.so /usr/lib/libnvcuvid.so

*参考opencv-users - [CUDA] cmake error when when running WITH_CUDA on linux

最終的な実行コマンドは下記の通り。

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local/opencv -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON WITH_CUDA=ON  CUDA_nvcuvid_LIBRARY=/usr/local/cuda-5.0 ..

あとは、

make
make install

でインストール完了。

と思ったら、下記エラーが発生。

[ 22%] Built target opencv_ts
Linking CXX executable ../../bin/opencv_perf_core
../../lib/libopencv_core.so.2.4.3: error: undefined reference to 'cuDeviceGetAttribute'
collect2: ld はステータス 1 で終了しました
make[2]: *** [bin/opencv_perf_core] エラー 1
make[1]: *** [modules/core/CMakeFiles/opencv_perf_core.dir/all] エラー 2
make: *** [all] エラー 2

取り急ぎ、CMakeCache.txt内のCUDA_CUDA_LIBRARY:FILEPATH
CUDA_CUDA_LIBRARY:FILEPATH=/usr/lib/nvidia-current/libcuda.so
のように変更。
*参考 Compiling OpenCV 2.4.3 on Ubuntu 12.10 « AmmarkoV `s Personal Website

動かしてみる

ちょうどいいサンプルが、sample/gpu/hog.hppにあったのでビルドしてみる。

g++ hog.cpp `/usr/bin/pkg-config --cflags --libs opencv`

このサンプルはCPUとGPUの切り替えができる。
大体4倍ぐらい性能差が出ました。


*ここを参考に参考にさせて頂きました。
Nvidia drivers for Ubuntu 12.10 Quantal/Ubuntu 12.04 Precise/Ubuntu 11.10 Oneiric Ocelot/Linux Mint ~ Noobs on Ubuntu and Windows, HD Wallpapers, Tutorials