>

2015년 7월 22일 수요일

OpenCV 3.0.0 in Yosemitte 10.10.x

Source: 
http://www.learnopencv.com/install-opencv-3-on-yosemite-osx-10-10-x/

git clone https://github.com/Itseez/opencv_contrib.git
cd opencv_contrib
git checkout tags/3.0.0


* with CUDA 7.0 (otherwise errors or setting changes)

cmake -D WITH_CUDA=OFF -D CMAKE_INSTALL_PREFIX=/full/path/to/opencv/build -D CMAKE_BUILD_TYPE=RELEASE   ..

---
cp lib/pkgconfig/opencv.pc /usr/local/lib/pkgconfig/opencv3.pc

---
cd /full/path/to/opencv/samples/cpp
 
# If you built it with no CUDA support or with CUDA 7 or above
g++ -ggdb `pkg-config --cflags --libs opencv3` facedetect.cpp -o /tmp/test && /tmp/test
 
---
export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/cuda/lib/:$DYLD_FALLBACK_LIBRARY_PATH
cd /full/path/to/opencv/samples/gpu
 
# If you built it with CUDA 7 or above
g++ -ggdb `pkg-config --cflags --libs opencv3` hog.cpp -o /tmp/hog && /tmp/hog
 

2015년 4월 8일 수요일

glm::mat has internally column major representation.

$ brew install glm
----------------------------
glm test code.
----------------------------
  • Each row and column in glm::mat4 is zero-based:
    
        glm::mat4 m4( 1.0f ); // construct identity matrix
        m4[ 0 ]     // column zero
        m4[ 0 ].x   // same as m4[ 0 ][ 0 ]
        m4[ 0 ].y   // same as m4[ 0 ][ 1 ]
        m4[ 0 ].z   // same as m4[ 0 ][ 2 ]
        m4[ 0 ].w   // same as m4[ 0 ][ 3 ]
    
    
  • Each column of matrix glm::mat4 is a vec4.
  • To set the entire column, e.g. for translation,
    
        glm::mat4 m4( 1.0f ); // construct identity matrix
        m4[ 3 ] = glm::vec4( vec3( x, y, z ), 1.0f );
    
    


1:  #include <iostream>  
2:  using namespace std;  
3:  // Include GLM  
4:  #include <glm/glm.hpp>  
5:  #include <glm/gtc/matrix_transform.hpp>  
6:  #include <glm/gtc/type_ptr.hpp>  
7:  #include <glm/gtx/transform.hpp>  
8:  #include <glm/gtx/string_cast.hpp>  
9:  #include <math.h>  
10:  float deg2rad(float deg) { return deg*M_PI/180.; }  
11:  void print (glm::mat3 r, string s)  
12:  {  
13:      cout << s << endl;  
14:      for (int i=0; i<3; i++) {  
15:          for (int j=0; j<3; j++) {  
16:              cout << " " << r[i][j] ;  
17:          }  
18:          cout << endl;  
19:      }  
20:  }  
21:  void print (const glm::mat4 &r, string s)  
22:  {  
23:      cout << s << endl;  
24:      for (int i=0; i<4; i++) {  
25:          for (int j=0; j<4; j++) {  
26:              cout << " " << r[i][j] ;  
27:          }  
28:          cout << endl;  
29:      }  
30:  }  
31:  void print(const glm::vec3& v, string s)  
32:  {  
33:      cout << s << endl;  
34:      for (int i=0; i<3; i++) {  
35:          cout << " " << v[i] ;  
36:      }  
37:      cout << endl;  
38:  }  
39:  int main()  
40:  {  
41:   float degree = 45.;  
42:   glm::vec3 zAxis(0.f, 0.f, 1.f);  
43:   glm::mat3 R3 = glm::mat3(glm::rotate (deg2rad(degree),zAxis));  
44:   glm::mat4 R4 = glm::rotate (deg2rad(degree),zAxis);  
45:   cout << "Note that glm matrices are stored in column major order!" << endl;  
46:   cout << "----" << endl;  
47:   print(R3, "R3");  
48:   printf("----\n");  
49:   cout << "The following will show you column vectors enclosed by parantheses." << endl;  
50:   cout << "R3: " << glm::to_string(R3) << endl;  
51:   printf("----\n");  
52:   print(R4, "R4");  
53:   printf("----\n");  
54:   glm::vec2 p(1,0), q(0,1);  
55:   glm::vec3 u(1,1,1);  
56:   glm::vec3 ru = R3 * u,  
57:        rp = R3 * glm::vec3(p,1),  
58:        rq = R3 * glm::vec3(q,1);  
59:   printf("This is the 1st column of R3.\n");  
60:   print(rp, "rp:");  
61:   printf("----\n");  
62:   printf("This is the 2nd column of R3.\n");  
63:   print(rq, "rq:");  
64:   printf("----\n");  
65:   printf("This is the 45 degrees rotation result of (1,1,1) about the z-axis.\n");  
66:   print(ru, "ru:");  
67:   printf("----\n");  
68:   glm::mat3 H(1.0); // identity matrix  
69:   H[2].x = 1.0; // (0,2)-element of H  
70:   cout << "H: " << glm::to_string(H) << endl;  
71:   H[2] = glm::vec3(2.0f, 3.0f, 1.0f); // 2d translation  
72:   cout << "H: " << glm::to_string(H) << endl;  
73:   glm::mat3 T = H * R3;  
74:   cout << "H*R: " << glm::to_string(T) << endl;  
75:   return 0;  
76:  }  
77:  // EOF //  

2015년 3월 24일 화요일

OpenGL-tutorial_v0014_33, Tutorial-01 Mac OS X

1. download
2. brew install glew glfw3 glm
3. Tutorial-01
 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

 $ clang++ tutorial01.cpp -I /usr/local/include/GLFW -lglfw3 -framework opengl -lglew

4.
 $ clang++ -I /usr/local/include/GLFW -I .. -lglfw3 -framework opengl -lglew ../common/shader.cpp  tutorial02.cpp

2014년 12월 4일 목요일

opencv 2.4.9 & 3.0.0 둘 다 설치하기; install both

1. 2.4.9 를 설치한다.

$ brew tap homebrew/science
$ brew install opencv --with-ffmpeg --with-tbb

1.1. 설치가 끝난후에 다음을 확인한다.

$ ls -l /usr/local/Cellar/opencv
drwxr-xr-x  9 yndk  wheel  306 12  3 16:48 2.4.9

1.2. 맨 마지막 2.4.9 가 디렉토리의 이름이고, 그 안을 살펴보면 다음과 같다.

$ ls -l /usr/local/Cellar/opencv/2.4.9
 -rw-r--r--   1 yndk  staff   489 12  3 16:48 INSTALL_RECEIPT.json
 -rw-r--r--   1 yndk  wheel  1772 10  1 16:33 LICENSE
 -rw-r--r--   1 yndk  wheel   636 10  1 16:33 README.md
 drwxr-xr-x   6 yndk  wheel   204 12  3 16:48 bin
 drwxr-xr-x   4 yndk  wheel   136 12  3 16:48 include
 drwxr-xr-x  59 yndk  wheel  2006 12  3 16:48 lib
 drwxr-xr-x   3 yndk  wheel   102 12  3 16:48 share

2. cmake 를 이용하여 3.0.0 을 직접 컴파일하고 설치한다.
설치 디렉토리는 자신이 좋아하는 곳으로. 예를 들면 /usr/local/opencv-3.0.0-beta

2.1 make; make install 후에 /usr/local/opencv-3.0.0-beta 디렉토리를 보면 다음과 같이 되어있다.

$ ls -l /usr/local/opencv-3.0.0-beta
drwxr-xr-x    5 yndk  wheel   170 11 21 14:31 bin
drwxr-xr-x    4 yndk  wheel   136 11 21 13:45 include
drwxr-xr-x  110 yndk  wheel  3740 11 21 14:31 lib
drwxr-xr-x    3 yndk  wheel   102 11 21 13:45 share

2.2 이 디렉토리를 /usr/local/Cellar/opencv/3.0.0으로 복사한다.

$ cp -r /usr/local/opencv-3.0.0-beta /usr/local/Cellar/opencv/3.0.0

3. brew 를 실행하여 사용하고싶은 버전으로 설치한다.

* opencv 3.0 을 사용할 경우

$ brew switch opencv 3.0.0

* 확인해본다. 3.0.0 으로 설치한 후

$ ls -l /usr/local/include/opencv*
 lrwxr-xr-x  1 yndk  wheel  37 12  5 09:07 /usr/local/include/opencv@ -> ../Cellar/opencv/3.0.0/include/opencv
 lrwxr-xr-x  1 yndk  wheel  38 12  5 09:07 /usr/local/include/opencv2@ -> ../Cellar/opencv/3.0.0/include/opencv2

* opencv 2.4.9를 사용할 경우

$ brew switch opencv 2.4.9

* brew 실행할 때 특정 파일들이 중복된다거나 지우라는 내용이 나오면 그대로 실행하면 된다.
* 둘 다 설치되어 있지만 실제로 사용할 때는 한 개만 선택해서 사용하는 것으로 이해하는 것이 좋음.


끝.

cv::cascadeClassifier training & example

Quick Start
1. cut and make a template image (size: 164x164), save it to faceSample.png.

2. do the following
    $ opencv_createsamples -img faceSample.png -vec faceSample.vec -num 10000

2. have a look at the samples
   $ opencv_createsamples -show -vec faceSample.vec

3. run
   $ opencv_haartraining -data result -vec faceSample.vec  -bg bg.txt

4. test
   $ ./haarObjectDetection result.xml group.jpg

Here is group.jpg downloaded from google image search. sorry, privacy.

Actually, the template image is cropped from the group.jpg.

* haarObjectDetection.cpp
----------------------------------------------------------------------------
// modifed version of objectDetect.cpp
/**
 * @file objectDetection.cpp
 * @author A. Huaman ( based in the classic facedetect.cpp in samples/c )
 * @brief A simplified version of facedetect.cpp, show how to load a cascade classifier and how to find objects (Face + eyes) in a video stream
 */
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

/** Function Headers */
void detectAndDisplay( Mat frame );

/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
CascadeClassifier face_cascade;
string window_name = "Capture - Face detection";
RNG rng(12345);

int main( int argc, char *argv[] )
{
  Mat frame;

  if (argc!=3) {
cerr << "usage: " << argv[0] << " haar_cascade.xml   testimage.jpg" << endl;
return 0;
  }

  //-- 1. Load the cascades
  if( !face_cascade.load( argv[1] ) ){ printf("--(!)Error loading\n"); return -1; };

  //-- 2. Read the video stream
      frame = imread (argv[2]);

      //-- 3. Apply the classifier to the frame
      if( !frame.empty() )
       { detectAndDisplay( frame ); }
      else
       { printf(" --(!) No captured frame -- Break!"); return 0; }

      int c = waitKey();

  return 0;
}

/**
 * @function detectAndDisplay
 */
void detectAndDisplay( Mat frame )
{
   std::vector<Rect> faces;
   Mat frame_gray;

   cvtColor( frame, frame_gray, COLOR_BGR2GRAY );
   equalizeHist( frame_gray, frame_gray );
   //-- Detect faces
   face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

   for( size_t i = 0; i < faces.size(); i++ )
    {
      Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
      ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2), 0, 0, 360, Scalar( 255, 0, 255 ), 2, 8, 0 );
    }
   //-- Show what you got
   imshow( window_name, frame );
}
----------------------------------------------------------------------------


-------------
http://docs.opencv.org/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html
http://docs.opencv.org/doc/user_guide/ug_traincascade.html


opencv_traincascade 
supports both Haar [Viola2001] and LBP [Liao2007] (Local Binary Patterns) features.

opencv_createsamples 
is used to prepare a training dataset of positive and test samples.
The output is a file with *.vec extension, it is a binary format which contains images.

-- Training Data Preparation
Set of negative samples must be prepared manually, whereas set of positive samples is created using opencv_createsamples utility.

-- Negative Samples
Make a file of imagefile names
$ cat bg.txt
img/bg1.png
img/bg2.png

-- Positive Samples
Positive samples are created by opencv_createsamples utility. 
They may be created from a single image with object 
or from a collection of previously marked up images.

2014년 12월 1일 월요일

caffe compile and install in Mac OSX 10.10.1, CUDA 6.5

** gflags 1.0  must be installed!
** glog 0.3.3 based on gflags 1.0.
** Make test gives run time error
[----------] 1 test from SolverTest/1, where TypeParam = caffe::DoubleCPU
[ RUN      ] SolverTest/1.TestInitTrainTestNets
test_all.testbin(95309,0x7fff7d0e2300) malloc: *** error for object 0x110afa7a0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

make: *** [runtest] Abort trap: 6

--------------------
mybuild $ cmake ..
-- Found leveldb in /usr/local/include /usr/local/lib/libleveldb.dylib
-- Found Snappy: /usr/local/lib/libsnappy.dylib  
-- LMDB lib: /usr/local/lib/liblmdb.dylib
-- LMDB include: 
-- Found LMDB: /usr/local/include  
-- Boost version: 1.56.0
-- Found the following Boost libraries:
--   system
--   thread
-- Found PROTOBUF: /usr/local/lib/libprotobuf.dylib  
-- Found PROTOBUF Compiler: /usr/local/bin/protoc
-- Examples enabled
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/yndk/Downloads/caffe-master/mybuild

mybuild $ make all
Scanning dependencies of target gtest
[  1%] Building CXX object src/gtest/CMakeFiles/gtest.dir/gtest-all.cpp.o
In file included from /Users/yndk/Downloads/caffe-master/src/gtest/gtest-all.cpp:39:
/Users/yndk/Downloads/caffe-master/src/gtest/gtest.h:1561:13: fatal error: 'tr1/tuple' file not
      found
#   include <tr1/tuple>  // NOLINT
            ^
1 error generated.
--------------------------
So, I modified the line 28 of CMakeList.txt file as follows

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -stdlib=libstdc++") # set global flags
--------------------------
mybuild $ make all
...
caffe-master/include/caffe/util/mkl_alternate.hpp:11:10: fatal error: 
      'cblas.h' file not found
#include <cblas.h>
         ^

1 error generated.
--------------------------
So, I modified the line 28 of CMakeList.txt file as follows

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -stdlib=libstdc++ -I/System/Library/Frameworks/Accelerate.framework/Versions/C    urrent/Frameworks/vecLib.framework/Versions/Current/Headers -framework Accelerate") # set global flags
--------------------------
mybuild $ make
-- Found leveldb in /usr/local/include /usr/local/lib/libleveldb.dylib
-- LMDB lib: /usr/local/lib/liblmdb.dylib
-- LMDB include: 
-- Boost version: 1.56.0
-- Found the following Boost libraries:
--   system
--   thread
-- Found PROTOBUF Compiler: /usr/local/bin/protoc
-- Examples enabled
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/yndk/Downloads/caffe-master/mybuild
[  1%] Built target gtest
[  1%] Built target gtest_main
[  4%] Built target proto
[  5%] Building NVCC (Device) object src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
/usr/local/include/boost/config/suffix.hpp(496): error: identifier "__int128" is undefined

/usr/local/include/boost/config/suffix.hpp(497): error: expected a ";"

2 errors detected in the compilation of "/var/folders/cn/yf6gmhss2g96zb6933m4v0t00000gn/T//tmpxft_00012ea7_00000000-12_math_functions.compute_35.cpp1.ii".
CMake Error at caffe_cu_generated_math_functions.cu.o.cmake:264 (message):
  Error generating file
  /Users/yndk/Downloads/caffe-master/mybuild/src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o


make[2]: *** [src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o] Error 1
make[1]: *** [src/caffe/CMakeFiles/caffe_cu.dir/all] Error 2
make: *** [all] Error 2

------------------------------------
So, I added the following to /usr/local/include/boost/config/compiler/nvcc.hpp
// yndk
#ifdef BOOST_HAS_INT128
#undef BOOST_HAS_INT128
#endif
------------------------------------

mybuild $ make
-- Found leveldb in /usr/local/include /usr/local/lib/libleveldb.dylib
-- LMDB lib: /usr/local/lib/liblmdb.dylib
-- LMDB include: 
-- Boost version: 1.56.0
-- Found the following Boost libraries:
--   system
--   thread
-- Found PROTOBUF Compiler: /usr/local/bin/protoc
-- Examples enabled
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/yndk/Downloads/caffe-master/mybuild
[  1%] Built target gtest
[  1%] Built target gtest_main
[  4%] Built target proto
[  5%] Building NVCC (Device) object src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
clang: warning: -framework Accelerate: 'linker' input unused
/usr/local/include/boost/config/suffix.hpp(496): error: identifier "__int128" is undefined

/usr/local/include/boost/config/suffix.hpp(497): error: expected a ";"

2 errors detected in the compilation of "/var/folders/cn/yf6gmhss2g96zb6933m4v0t00000gn/T//tmpxft_00012ea7_00000000-12_math_functions.compute_35.cpp1.ii".
CMake Error at caffe_cu_generated_math_functions.cu.o.cmake:264 (message):
  Error generating file
  /Users/yndk/Downloads/caffe-master/mybuild/src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o


make[2]: *** [src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o] Error 1
make[1]: *** [src/caffe/CMakeFiles/caffe_cu.dir/all] Error 2
make: *** [all] Error 2

------------------------
So, another file. I placed at the beginning of the file: /usr/local/include/boost/config/suffix.hpp
//yndk
#if defined(BOOST_HAS_INT128)
#undef BOOST_HAS_INT128
#endif
//yndk
------------------------
mybuild $ make
[  1%] Built target gtest
[  1%] Built target gtest_main
[  4%] Built target proto
[  5%] Building NVCC (Device) object src/caffe/CMakeFiles/caffe_cu.dir/util/./caffe_cu_generated_math_functions.cu.o
...
[ 85%] Built target caffe
Scanning dependencies of target caffe.bin
[ 87%] Building CXX object tools/CMakeFiles/caffe.bin.dir/caffe.cpp.o
clang: warning: -framework Accelerate: 'linker' input unused
Linking CXX executable caffe
Undefined symbols for architecture x86_64:
  "cv::imread(std::string const&, int)", referenced from:
      caffe::ReadImageToDatum(std::string const&, int, int, int, bool, caffe::Datum*) in libcaffe.a(io.cpp.o)
      caffe::WindowDataLayer<float>::InternalThreadEntry() in libcaffe.a(window_data_layer.cpp.o)
      caffe::WindowDataLayer<double>::InternalThreadEntry() in libcaffe.a(window_data_layer.cpp.o)
  "google::SetUsageMessage(std::string const&)", referenced from:
      _main in caffe.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [tools/caffe] Error 1
make[1]: *** [tools/CMakeFiles/caffe.bin.dir/all] Error 2
make: *** [all] Error 2
-------------------------------
Now, I need an appropriate opencv for caffe.
opencv-3.0.0-beta with CUDA is installed.
----
caffe-master $ make
/usr/bin/clang++ src/caffe/layers/window_data_layer.cpp -stdlib=libstdc++ -framework Accelerate -pthread -fPIC -DNDEBUG -O2 -I/usr/local/include -I.build_release/src -I./src -I./include -I/usr/local/cuda/include -I/System/Library/Frameworks/Accelerate.framework/Versions/Current/Frameworks/vecLib.framework/Versions/Current/Headers -Wall -Wno-sign-compare -Wno-unneeded-internal-declaration -c -o .build_release/src/caffe/layers/window_data_layer.o 2> .build_release/src/caffe/layers/window_data_layer.o.warnings.txt \
|| (cat .build_release/src/caffe/layers/window_data_layer.o.warnings.txt; exit 1)
clang: warning: -framework Accelerate: 'linker' input unused
src/caffe/layers/window_data_layer.cpp:230:48: error: use of undeclared identifier 'CV_LOAD_IMAGE_COLOR'
      cv::Mat cv_img = cv::imread(image.first, CV_LOAD_IMAGE_COLOR);
                                               ^
1 error generated.

make: *** [.build_release/src/caffe/layers/window_data_layer.o] Error 1
---------
line 230 is replaced as follows
      //cv::Mat cv_img = cv::imread(image.first, CV_LOAD_IMAGE_COLOR);
      cv::Mat cv_img = cv::imread(image.first, cv::IMREAD_COLOR);
--------