Monday, July 14, 2014

OpenCV on Carma - My First Example.

Let's start OpenCV-GPU with a sample application. Source code is listed as below:

 #include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/gpu/gpu.hpp>
using namespace cv;
using namespace std;

int main (int argc, char* argv[])

{
        Mat src_host;(Size(640,480),CV_8UC3);
        Mat dst_host;(Size(640,480),CV_8UC1);
        gpu::GpuMat  src(Size(640,480),CV_8UC3);
        gpu::GpuMat  tmp(Size(640,480),CV_8UC1);
        gpu::GpuMat  dst(Size(640,480),CV_8UC1);
        VideoCapture capture(0);

        while(1){
                capture >>src_host;
                src.upload(src_host);
                gpu::cvtColor(src,tmp,CV_BGR2GRAY);
                gpu::Canny(tmp,dst,50,100);

                dst.download(dst_host);
                imshow("output",dst_host);
                if(waitKey(5)==27) break;
        }
        return 0;
}
There are few things you need to take care:
  • Define necessary buffer in GPU side, it's simply done by: 
    • gpu::GpuMat  src(Size(640,480),CV_8UC3);
  • After you capture image from webcam, you need to copy this data from cpu side to gpu side, by:
    •  src.upload(src_host);
  • Process in GPU by using all GPU functions, in this example, they are color conversion and Canny filter
    •    gpu::cvtColor(src,tmp,CV_BGR2GRAY);
    •    gpu::Canny(tmp,dst,50,100);
  • After GPU completes processing, you need to copy processed image back to CPU side in order to display or save to file.
    •   dst.download(dst_host);
Compile the example(you can cross compile or compile using compiler on board):
arm-linux-gnueabi-g++ -I/usr/local/include src/cuda_sample.cpp -g -o cuda_sample -L/usr/local/cuda/lib -lcudart -lnpp -lcublas -lcufft -L/usr/local/cuda_opencv_libs/ -lopencv_gpu -lopencv_highgui -lopencv_calib3d -lopencv_core
 Here we go, our first example is ready to run. You can see something like this when you run the sample.

You may encounter long delay at the beginning, it's because system needs time to initialize GPU. So that to compare performance of CPU and GPU functions, you just ignore this phase, run the function many times(put inside a loop) and compare average processing time.

No comments:

Post a Comment