Ask Your Question

How to compile basic opencv program in C++ in ubuntu

asked 2013-12-18 09:18:13 -0500

kchaitu gravatar image

updated 2013-12-18 23:26:20 -0500

I have installed opencv in ubuntu 12.04. I have written a basic program in c++. How to compile this basic program in C++ using opencv libraries.

#include <cv.h>
#include <highgui.h>

int main(){

    Mat image;
    image = imread("google.jpg", CV_LOAD_IMAGE_UNCHANGED);   // Read the file

    if(! )                              // Check for invalid input
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;

    namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
    imshow( "Display window", image );                   // Show our image inside it.


      return 0;
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-12-19 07:04:32 -0500

Haris gravatar image
  • Using command line

Use below command to build binary from your source file directory.

g++ -I/usr/local/include/opencv -I/usr/local/include/opencv2 -L/usr/local/lib/ -g -o binary  main.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_stitching


binary -> The binary file to be created.

main.cpp -> Source file.

Note: Instead for running all these command every time, just create a file named , put the above command to it and change the file permission to executable by running chmod 777, and from next time run this file instead of running the whole command.

  • Using Camke

See OpenCV Documentation about OpenCV with gcc and CMake

  • Using Eclipse

See OpenCV Documentation about OpenCV with Eclipse (plugin CDT)

  • Using CodeBlocks
  1. Open CodeBlocks and create new C++ project.

  2. Now right click on your project->Buid Options.

  3. On the po-up window select Search directories tab

    -> In that select Compiler tab and add OpenCV include directory, usually /usr/local/include

Screen shot:-

image description

-> Now open Linker tab and set OpenCV bin directory, usually /usr/local/bin

Screen shot:-

image description

4.Finally Open Linker setting tab and on Other linker options add below libraries


Screen shot:-

image description

Done !

Now click ok and build your project.

edit flag offensive delete link more


Say I have a C++ class defined in example.h and example.cpp that uses opencv. How do I generate a .o file for this class so I can use it together with other .o files to generate an executable file?

pauloeddias gravatar imagepauloeddias ( 2015-12-09 15:20:40 -0500 )edit

Question Tools

1 follower


Asked: 2013-12-18 09:18:13 -0500

Seen: 89,020 times

Last updated: Dec 19 '13