## 2012年12月24日月曜日

### macportsメンテナンスルーチン

デフォルトのgccであることを最初に確認しておく。 また、python24に依存したportsを全てアンインストールするときは 特定のパッケージを無視するときは 参考サイト

[追記]2017/02/25
OSをmacOS Sierra v10.12にアップグレードしたあとこのサイトの項目「Migration procedure」の1と2だけを実行した。macports.confは触っていない。

## 2012年12月1日土曜日

### std::listとstd::vectorのベンチマーク

isocppのサイトにstd::listとstd::vectorのベンチマークの記事が紹介されていました。
http://www.baptiste-wicht.com/2012/11/cpp-benchmark-vector-vs-list/

1. std::vector is insanely faster than std::list to find an element
2. std::vector performs always faster than std::list with very small data
3. std::vector is always faster to push elements at the back than std::list
4. std::list handles very well large elements, especially for sorting or inserting in the front
そして、実際にコードを書く際の指針を以下のように示しています。
1. Number crunching: use std::vector
2. Linear search: use std::vector
3. Random Insert/Remove: use std::list (if data size very small (< 64B on my computer), use std::vector)
4. Big data size: use std::list (not if intended for searching)
ここで、crunchingとはソートされたコンテナに乱数を挿入する操作のことです。

### C++11を使ってOpenCV-2.4.3をコンパイルする。

CentOS5.8上でC++11(gcc-4.7.2)を使ってOpenCV-2.4.3をコンパイルしました。以下覚え書きとして記します。

.bashrcには以下の記述が既にあります。 すなわち、gcc-4.7.2へのパスをシステムは認識しています。

### C++11を使ってBoost-1.52.0をコンパイルする。

CentOS5.8上でC++11(gcc-4.7.2)を使ってBoost-1.52.0をコンパイルしました。以下覚え書きとして記します。

.bashrcには以下の記述が既にあります。 すなわち、gcc-4.7.2へのパスをシステムは認識しています。そして、今いる場所はここ。 ここに従ってboost.buildをインストールします。 PATHに/usr/local/boost.build/binを追加します。そして、以下を実行します。 しばらくすると、「pyconfig.hがない」と出ました。なのでこれを実行します。 あらためて 今度は「zlib.hがない」「bzlib.hがない」と出ました。これらをインストールします。 あらためて 出来ました。stageディレクトリの下にライブラリができています。これをcpコマンドを使って「手動で」目的の場所にコピーしました。

## 2012年11月29日木曜日

### CentOS5.8にgcc-4.7.2をインストールする。

CentOS5.8上でgcc-4.7.2をコンパイルしました。 こちらのサイトを参考にしています。以下覚え書きとして記します。

1. gcc
2. gcc-c++
3. binutils
4. bzip2
5. gzip
6. m4
7. make
8. unzip
9. zip

## Introduction

Several years ago I implemented a command line application of the Level Set Method. In this page, I would like to introduce it.

demo-1

demo-2

demo-3

## Verification Environment(Mac)

1. Mac OS X 10.8.2
2. Processor：3.06 GHz Intel Core 2 Duo
3. Memory：4GB
4. Xcode4.5.2 with Apple LLVM 4.1（C++ Language Dialect → C++11, C++ Standard Library → libc++）

## Verification Environment(Windows)

1. Windows XP Professional Version 2002 Service Pack 3
2. Processor：Pentium(R) D CPU 3.20GHz
3. Memory：3GB
4. Visual Studio 2005
5. boost-1.51.0 (binaries for the VS2005)

## Source Code

Here is my source code. I verified it on the above two machines.

## Usage

An execution file name is LevelSetMethod. In the case of Windows, it's named LevelSetMethod.exe. Running it without any arguments, it writes the following usage statements on the standard output: The Level Set Method is carried out by using some of these parameters. The procedure is as follows:
1. see the size of an input image.
2. set an initial closed curve.
3. run the Level Set Method.
I will explain the detail of each process.

#### ①Size of Image

In order to give the application an initial closed curve, we have to know the size of an input image. To do so, the following command is used. The output indicates the size of the input image(./input/sample3.jpg).

#### ②Setting Initial Closed Curve

We can draw an circle with a center (X, Y) and a radius R by the following command. In this command, -C indicates color of the circle, whose range is [0,255]. The circle is drawn on the input image. It is saved in the directory(./output) with the name "initial_loop.jpg" (see the below image). The circle corresponds to the initial closed curve. We can put it either outside an object or inside one. If it is placed outside the object, the Level Set Method shrinks it. On the other hand, if it is placed inside the object, the Level Set Method expands it. We have to decide appropriate values (X, Y, R) through a trial and error process.

#### ③Running Level Set Method

We have to make a setting file in which six parameters are described. The file name is arbitrary. In this page, we name it "params" to make the explanation easy. The sample of "params" is as follows: The meanings of the parameters are
1. time_step: time step
2. time_step_number: iteration of time evolution
3. space_step: space step. the same value for both x-axis and y-axis
4. constant_speed: a constant part of a speed function as we will discuss later
5. epsilon: a value of ε which appears in the definition of a speed function
6. sigma: a degree of the Gaussian blur
The speed function which the application uses is defined as,

where, is the curvature.
The parameter epsilon indicates and the parameter constant_speed corresponds to . If we shrink(expand) the curve, we set it to negative(positive) value. After making the setting file, we run the following command: After the argument -F, we type the path to "params." During execution, the progress bar is displayed. Under the above parameters, the time evolution is repeated up to 400 steps, and one image is saved per 10, which is a value after -T, time steps. The output directory is ./output and the file name is front_xxx.jpg, where xxx represents integer. The calculation time is displayed in the last line of the standard output. In the current parameters, 40 images are saved. I converted these images into a movie by use of ffmpeg to show the demonstration at the beginning of this page.

### Compilation of Boost by clang with C++11

My procedure is as follows: When using it on the Xcode, we need to add a variable DYLD_LIBRARY to "Product→Edit Scheme→Arguments→Environment Variables" and set the path to dylib to the variable.

## はじめに

ずいぶん昔になりますが、Level Set 法を実装しました。今回はこれを公開します。

こんな感じです。

## 検証環境(Mac)

1. Mac OS X 10.8.2
2. プロセッサ：3.06 GHz Intel Core 2 Duo
3. メモリ：4GB
4. Xcode4.5.2 with Apple LLVM 4.1（C++ Language Dialect → C++11, C++ Standard Library → libc++）
5. boost-1.51.0（上記コンパイラでコンパイルしたもの。こちら

## 検証環境(Windows)

1. Windows XP Professional Version 2002 Service Pack 3
2. プロセッサ：Pentium(R) D CPU 3.20GHz
3. メモリ：3GB
4. Visual Studio 2005
5. boost-1.51.0（VS2005用バイナリ版）

## ソース

こちらです。上記2つの検証環境で動作確認しました。

## 使い方

1. 入力画像の大きさを知る。
2. 初期閉曲線を設定する。
3. LevelSet法を実行する。

#### ③LevelSet法の実行

1. time_step: 時間発展の刻み幅
2. time_step_number: 時間発展の繰り返し数
3. space_step: 空間刻み幅。x軸方向、y軸方向ともに同じです。
4. constant_speed: 速度関数の定数部分の値（後述）。
5. epsilon: 速度関数に現れるεの値（後述）。
6. sigma: 入力画像に施すガウスぼかしの度合い。

ここで、 は曲率です。constant_speed に相当します。閉曲線を内側に向かって収縮させるなら負の値を、その逆なら正の値を設定します。また、epsilon に相当します。

## 2012年11月19日月曜日

### Universal References in C++11

Scott Meyers氏による右辺値参照の解説です。大変分かりやすいです。 Universal References in C++11

in Japanese

## Introduction

In the previous page, I showed the application that is using the OpenNI and the Open Dynamics Engine libraries with the Xtion Pro Live. Recently I have introduced the SceneAnalyzer node, which is supported by the OpenNI library, to the application. In this page, I provide you with an explanation on the new application. (Here is my first introduction to the ODE.)

## Demo

I start by showing a demo movie.

## Developement Environment

1. Mac OS X 10.8.2
2. Processor：3.06 GHz Intel Core 2 Duo
3. Memory：4GB
4. Xcode4.5.1

## Primary Libraries

1. boost-1.51.0
2. pcl-1.6.0
3. OpenNI-Bin-Dev-MacOSX-v1.5.4.0
4. ode-0.12

## My Source Code

Here is my source code. I do not confirm the behavior of the application on environments other than mine.

## Compile Options

Path Purpose
/usr/include/ni/ to include the OpenNI headers
/opt/local/include/ to include the Boost and the ODE headers
/usr/local/include/pcl-1.6/ to include the PCL headers
/opt/local/include/eigen3/ to include the Eigen headers on which the PCL depends
/opt/local/include/vtk-5.10/ to include the VTK headers on which PCL dependes

Library Search Path:
Path Purpose
/opt/local/lib to link the Boost library
/usr/local/lib to link the PCL library

 -lboost_thread-mt -lboost_filesystem-mt -lboost_unit_test_framework-mt -lboost_chrono-mt -lboost_program_options-mt -lboost_system-mt /usr/lib/libOpenNI.dylib -framework OpenGL -framework GLUT -lpcl_filters -lpcl_kdtree -lpcl_segmentation -lpcl_surface -lpcl_search -lpcl_features -lpcl_common -lode -lpcl_io

## Usage

An execution file name is InteractiveObjects. Running it with an argument --help, it writes the following usage statements on the standard output. As shown above, the default window size is 320x240. I encountered the following error when running it with arguments --width 640 --height 480: The 21th-22th lines are output from the OpenNI library. I may be mistaken, but I think that the SceneAnalyzer node does not support the resolution 640x480.
Running it without any arguments (i.e. default size), it opens a viewer and begins to display frames captured by the Xtion Pro Live. Typing "m" on the keyboard under the situation where the application focuses on the viewer, a triangular mesh is constructed from a point cloud. The point cloud is calculated from the depth data in the frame at the moment when typing "m." The triangular mesh is used to create the background objects which consist of a floor, a wall, and so on. Then typing "r" brings virtual rigid bodies (balls and cylinders) into the captured scenes. The cylinders are fastened on to the floor. In the viewer, you can see that the balls collide with the cylinders, the background objects, and the other balls. Typing "o" enables an object detection, and the viewer begins to draw the collision between the detected object (human body) and the balls. To quit the application, type "q."

## Brief Overview Of Source Code

I will show you different code from the previous one.

#### Transforming Depth into Point Cloud

In the method Device::create_cloud, a depth data captured by the Xtion Pro Live is transformed into three point clouds:
1. a point cloud which is used to draw RGB images (cloud_)
2. a point cloud which is used to calculate a triangular mesh which describes the background objects (background_cloud_)
3. a point cloud which is used to calculate a triangular mesh which describes the objects detected by the SceneAnalyzer node (object_cloud_)
The 11th-13th lines and the 39th-44th lines in the code shown below are related to the SceneAnalyzer node. The point cloud object_cloud_ is captured per frame, while background_cloud_ is captured at the moment when typing "m" and it is fixed until typing "m" again.

#### Rigid Bodies

I use the ODE library to describe the rigid bodies. The ODE objects in the application are defined as follows: The prefix character "d" indicates the class provided by the ODE library. The object which moves based on the rigid body dynamics is represented by the dBody object. The object which requires the collision detection is represented by the dGeom object. In the application, a ball moves under the rigid body dynamics and collides with each other and other objects. Therefore, it is defined as the 5th-9th lines, where dSphere is the derived class from dGeom.
On the other hand, a cylinder is fastened on to the floor, so it does not move, but only collides with the balls. For that reason, as shown in the 18th line, I defined it as the object of the class dCylinder which is the derived class from dGeom.

Additional details (e.g. the transformation of a point cloud to a triangular mesh, registration of a mesh to the ODE, a collision detection, and so on) are seen in the previous page or my source code.

in English

こんな感じです。

## 開発環境

1. Mac OS X 10.8.2
2. プロセッサ：3.06 GHz Intel Core 2 Duo
3. メモリ：4GB
4. Xcode4.5.1

## 主要ライブラリ

1. boost-1.51.0
2. pcl-1.6.0
3. OpenNI-Bin-Dev-MacOSX-v1.5.4.0
4. ode-0.12

## ソース

こちらです。自分のマシーンでしか動作確認していません。

## コンパイルオプション

パス 目的
/usr/include/ni/ OpenNIヘッダー
/opt/local/include/ boost/odeヘッダー
/usr/local/include/pcl-1.6/ PCLヘッダー
/opt/local/include/eigen3/ eigenヘッダー(PCLがこれに依存している）
/opt/local/include/vtk-5.10/ vtkヘッダー(PCLがこれに依存している）

Library Search Path:
パス 目的
/opt/local/lib boostライブラリ
/usr/local/lib PCLライブラリ

 -lboost_thread-mt -lboost_filesystem-mt -lboost_unit_test_framework-mt -lboost_chrono-mt -lboost_program_options-mt -lboost_system-mt /usr/lib/libOpenNI.dylib -framework OpenGL -framework GLUT -lpcl_filters -lpcl_kdtree -lpcl_segmentation -lpcl_surface -lpcl_search -lpcl_features -lpcl_common -lode -lpcl_io

## ソースの概要

#### ポイントクラウドへの変換

Device::create_cloudで行います。以下3つのポイントクラウドを生成します。
1. カラー画像描画のためのポイントクラウド（cloud_
2. 背景の三角メッシュを算出するためのポイントクラウド（background_cloud_
3. 人物の三角メッシュを算出するためのポイントクラウド（object_cloud_
object_cloud_を生成するため、OpenNIのSceneAnalyzerを導入しました。それに関連するコードが11行目から13行目、39行目から44行目にあります。SceneAnalyzerが捉えた物体はフレーム単位で三角メッシュに変換され、ODEに登録されます。一方、背景となる三角メッシュは「m」が押された瞬間のフレームから作られ、それ以降は固定されます。

#### 剛体オブジェクト

その他、ポイントクラウドから三角メッシュへの変換、三角メッシュのODEへの登録、衝突の検出などは以前のページ、あるいはソースをご覧ください。

in Japanese

## Introduction

In the previous page, I implemented an application with the use of the OpenNI library. The application includes the simple simulation by the Newtonian dynamics. Recently, I have replaced the simulation with the Open Dynamics Engine(ODE). In this page, I give you an explanation on the new application. (Here is my first introduction to the ODE.)

## Development Environment

1. Mac OS X 10.8.2
2. Processor：3.06 GHz Intel Core 2 Duo
3. Memory：4GB
4. Xcode4.5.1

## Primary Libraries

1. boost-1.51.0
2. pcl-1.6.0
3. OpenNI-Bin-Dev-MacOSX-v1.5.4.0
4. ode-0.12

## My Source Code

Here is my source code. I do not confirm the behavior of the application on other environments.

## Compile Options

Path Purpose
/usr/include/ni/ to include the OpenNI headers
/opt/local/include/ to include the Boost and ODE headers
/usr/local/include/pcl-1.6/ to include the PCL headers
/opt/local/include/eigen3/ to include the Eigen header on which the PCL depends
/opt/local/include/vtk-5.10/ to include the VTK headers on which the PCL depends

Library Search Path:
Path Purpose
/opt/local/lib to link the Boost libraries
/usr/local/lib to link with the PCL libraries

 -lboost_thread-mt -lboost_filesystem-mt -lboost_unit_test_framework-mt -lboost_chrono-mt -lboost_program_options-mt -lboost_system-mt /usr/lib/libOpenNI.dylib -framework OpenGL -framework GLUT -lpcl_filters -lpcl_kdtree -lpcl_segmentation -lpcl_surface -lpcl_search -lpcl_features -lpcl_common -lode -lpcl_io

## Usage

An execution file name is BouncingBallWithOde. Running it with an argument --help, it writes the following usage statements on the standard output. Running it without any arguments, it opens a viewer and begins to display frames captured by the Xtion Pro Live. Typing "m" on the keyboard under the situation where the application focuses on the viewer, a triangular mesh is constructed from a point cloud. The point cloud is calculated from the depth data in the frame at the moment when typing "m". Typing "b" generates virtual balls in the captured scenes, and the interactions between the balls and the objects in the environment are drawn in real time. You can generate balls as many times as needed. Though an error occurs in the 29th line, no major disruptions are observed. To quit the application, type "q."

## Brief Overview of Source code

#### View Point of OpenGL

The view point of the OpenGL is as follow: A unit of length in the application is mm. You might need some changes to the arguments in the 6th line according to the environment captured by your depth sensor.

#### Transforming Depth into Point Cloud

A depth data is transformed into a point cloud in the method Device::create_cloud. In this application, two point clouds are generated, one (cloud_) is for displaying the color frames and another (cloud_xyz_) is for calculating a triangular mesh. RGB values are set in the 25,26th lines. The depth data is transformed into the point cloud in the 29th-30th lines. The point cloud used to calculate the triangular mesh is generated in the 33th line.

#### Drawing Color Image

The point cloud cloud_ is passed to the method Viewer::display_point_cloud as follows: The arguments buf and size indicate the pointer to the head address of cloud_ and the size of cloud_, respectively.

#### Calculation of Triangular Mesh

In the method Device::convert_to_polyton_mesh, the triangular mesh is constructed from the point cloud cloud_xyz_ by the use of the PCL library. (Here is my first introduction to the PCL library.) You might need to change parameters in the 27th-36th lines according to your environment.

#### Making Balls

A ball treated in the application is an ODE object. It consists of a dBody object and a dGeom one. The former manages the rigid body dynamics and the latter manages the collision detection. dSphere is the derived class from the base class dGeom. In the method PhysicalSimulator::create_balls(), balls are registered to the ODE framework. world_ in the 20th line and space_ in the 41th line are the dWorld and the dSpace objects, respectively. In the ODE framework, the object which moves based on the rigid body dynamics has to be registered to the dWorld object. The object which collides with other objects has to be registered to the dSpace object.

#### Registration of Triangular Mesh

The triangular mesh is registered to the ODE framework in the method PhysicalSimulator::register_triangular_mesh. triangular_mesh_ is the dGeomID object.

#### Collision Detection

The ODE library supports the method dCollide which handles the collision detection. The collision detection is carried out per frame. In the loop, the various properties are set to the collision points. The variable bounce in the 14th line corresponds to the reflection coefficient.

in English

## 動画

こんな感じ（アップロードしたら画質が悪くなった）。

## 開発環境

1. Mac OS X 10.8.2
2. プロセッサ：3.06 GHz Intel Core 2 Duo
3. メモリ：4GB
4. Xcode4.5.1

## 主要ライブラリ

1. boost-1.51.0
2. pcl-1.6.0
3. OpenNI-Bin-Dev-MacOSX-v1.5.4.0
4. ode-0.12

## ソース

こちらです。自分のマシーンでしか動作確認していません。

## コンパイルオプション

パス 目的
/usr/include/ni/ OpenNIヘッダー
/opt/local/include/ boost/odeヘッダー
/usr/local/include/pcl-1.6/ PCLヘッダー
/opt/local/include/eigen3/ eigenヘッダー(PCLがこれに依存している）
/opt/local/include/vtk-5.10/ vtkヘッダー(PCLがこれに依存している）

Library Search Path:
パス 目的
/opt/local/lib boostライブラリ
/usr/local/lib PCLライブラリ

 -lboost_thread-mt -lboost_filesystem-mt -lboost_unit_test_framework-mt -lboost_chrono-mt -lboost_program_options-mt -lboost_system-mt /usr/lib/libOpenNI.dylib -framework OpenGL -framework GLUT -lpcl_filters -lpcl_kdtree -lpcl_segmentation -lpcl_surface -lpcl_search -lpcl_features -lpcl_common -lode -lpcl_io

## ソースの概要

#### ポイントクラウドへの変換

Device::create_cloudで行います。カラー画像描画のためのポイントクラウド（cloud_）と三角メッシュ算出用のポイントクラウド（cloud_xyz_）の２種類を生成しています。 25,26行目でRGB値を設定しています。29,30行目でデプスから３次元座標への変換を行っています。33行目で三角メッシュ用のポイントクラウドを取得しています。

#### カラー画像の描画

カラー画像用のポイントクラウド（cloud_）は、OpenGLのglInterleavedArraysに以下（5行目）のように渡されます。bufcloud_の先頭ポインタ、sizecloud_のサイズです。

#### ボールの投入

ボールはODEのオブジェクトです。これは、剛体力学の計算に関与するdBodyと衝突計算に関与するdGeomから構成されます。 dSpheredGeomの子クラスです。 そして、ボールはPhysicalSimulator::create_balls()で環境内に投入されます。 20行目のworld_dWorldのオブジェクトです。41行目のspace_dSpaceのオブジェクトです。ODEでは、剛体力学の計算を必要とするオブジェクトはdWorldに、衝突計算を行うオブジェクトはdSpaceに登録しなければなりません。

## 2012年10月6日土曜日

### マジックナンバー70

3次までテイラー展開すると

ここで、 を仮定し、 で置き換えると

となります。これの実数解は0.6988854...です。おおよそ0.7です。 つまり となります。両辺に100をかければ

となります。これがマジックナンバーの正体です（たぶん）。 上の計算から、nは大きいほど、xは小さいほど精度は上がることがわかります。

## Introduction

Recently I installed the Open Dynamics Engine(ODE) to my iMac and compiled its sample program on the Xcode. In this page, I describe my procedure to do so.

## Development Environment

1. iMac
2. Mac OS X 10.8.1
3. Processor：3.06GHz Intel Core 2 Duo
4. Memory：4GB
5. Xcode4.4.1

## Installation

It's simple because the Macports supports the ODE. The ODE consists of two libraries:
1. the library to calculate the rigid body dynamics, which is called "ode"
2. the library to draw the dynamics by use of the OpenGL, which is called "drawstuff"
The Macports installs only "ode." As I also want to use "drawstuff", I downloaded the source code of ODE from here. Here are its installation instructions. At this point, the script warned that there is no libtoolize. I enabled statements from the 36th line to the 38th one in autogen.sh. The comments in the script tell us that the libtoolize corresponds to glibtoolize in Mac. I tried again. In turn, it's successful. The procedure compiles not only the "drawstuff" but also the "ode." I don't need the "ode" because it's already installed by the Macports. I manually copied the "drawstuff" as follows: The preparation to compile a sample program is completed.

## Interface of ODE

Here is the following statement: Though the library itself is written in C++, it appears that the library is more in favor of being used through the C interfaces. But, my favorite language is C++...

## Sample Program

Here is a beginner course of the ODE in Japanses. Using C++, I rewrote the sample source code "サンプルプログラム６マルチ" in the 6th chapter of the course. This page gives us an explanation about the C interfaces, but I could not find the corresponding page to the C++ ones. Fortunately the "ode" library provides us with the header file "odecpp.h." It helps me rewrite the sample in the C++. My source code is as follows: A path in the 10th line is the path to a directory included in the ODE source code.

## Compile Options

Path Purpose

Library Search Path:
Path Purpose
/opt/local/lib to find "ode" library
/usr/local/lib to find the "drawstuff" library

Red balls fall to the ground, and bounce. The variable contact.surface.bounce in the 55th line corresponds to the reflection coefficient. When it equals to 1, the completely-elastic collision is realized. The range is [0, 1].