:::: MENU ::::

Using OpenCV 3.0.0 with Eclipse

Posted in October 19, 2014

In this article, we’re going to see how to use OpenCV with Eclipse. We’ll use their latest releases: OpenCV 3.0.0 alpha e Eclipse Luna for C/C++ Developers. We’ll pass from downloading Eclipse, by setting a project linked with OpenCV until the implementation of our program. Don’t forget to check out the video demonstration of this process at the end of this article.

Pre-requirements:
-- Ubuntu 14.04 LTS 64 bits installed and updated;
-- OpenCV 3.0.0 alpha installed: How to install OpenCV 3.0.0 on Ubuntu

Let’s start!

Before we start, we’re going to need to download Eclipse. I use OpenCV with C++, then I’m going to download the specific release to C/C++ of Eclipse Luna: Eclipse IDE for C/C++ Developers.
Note: I didn’t add any image to exemplify each step, because there’s a video demonstration at the end. Watch the video: youtu.be/9ksMjQ2sBSQ!

Downloading and Installing Eclipse

  1. Go to Eclipse Downloads;
  2. In Package Solutions, search for Eclipse IDE for C/C++ Developers;
  3. Select Linux 32 or 64 bits; (in my case, Linux 64 bits);
  4. Unzip in any folder of your choice;
  5. Done!

You also can install Eclipse using sudo apt-get install eclipse-cdt

Creating a New C++ Project on Eclipse

  1. File » New » C++ Project;
  2. Give a name to your project in Project Name;
  3. Choose Executable » Empty Project in Project Type;
  4. Check Linux GCC in Toolchains and press Next;
  5. Uncheck Debug; (personal choice)
  6. Click on Finish;

Linking OpenCV to the newly created project

  1. Select the project and go to the menu Project » Properties (or press Alt+ENTER);
  2. We’re going to modify somethings on Tool Settings tab of C/C++ Build » Settings;
  3. In GCC C++ Compiler » Includes, add “/usr/local/include/opencv” in Include paths (-l). Discover the correct path by typing the following on the terminal: pkg-config --cflags opencv;
  4. Go to GCC C++ Linker » Libraries and add “/usr/local/lib” in Library search paths (-L). Discover the correct path by typing the following on the terminal:: pkg-config --libs opencv;
  5. Still in GCC C++ Linker » Libraries, add the libraries you’ll need in your project in Libraries (-l). We’re going to need 3 to our project (don’t forget to link opencv_imgcodecs, since imread() has moved to it in OpenCV 3):
    • opencv_core
    • opencv_imgcodecs
    • opencv_highgui
  6. Done!

Lets test it!

Can we build our programs using OpenCV in this project? Let’s test? Coming right up!

Creating and building our program

  1. Right-click on the project in Project Explorer and go to New » File;
  2. Give a name to the file, for instance: main.cpp and type (or copy and paste) the code snippet below. Don’t forget to save the file.
  3. Project » Build All (or Ctrl+B) to build;

Running the program

On the Terminal, go to the folder where you created the project(cd {workspace}/{project_name}/). Inside, you’re going to see our program (main.cpp) and the folder “Release/”. Access the folder Release and run our program.

./{project_name} {image}
E.g.: ./OpenCV ~/Images/lena.jpg

If your image has opened, congratulations! You just ran your first program using OpenCV with Eclipse.
Do you want to know how to run our program directly from Eclipse? Watch the video.


In case you have any question about how to execute any of the steps above, watch the video below demonstrating the whole process.

Do you still have questions? Has an error occurred?
Leave a comment or contact me.


  • Olga

    Hey Rodrigo,

    You helped me a lot with the installation and the first steps, but do you have a way of linking the libraries permanently so that I don’t have to do it again for every new project?

    Thanks again! 🙂
    Olga

  • Saurabh Marpadge

    thanx, for saving our time.
    It really worked with out any error.

  • Jormar Turizo

    Hi Rodrigo,

    In terminal run but not in eclipse. My bug is

    QXcbConnection: Could not connect to display

    What I can do?

    • Hi Jormar, I don’t know. AFAIK, this bug is not related to OpenCV.

  • Khalid Usman

    01:32:42 **** Incremental Build of configuration Release for project img ****
    make all
    Building target: img
    Invoking: GCC C++ Linker
    g++ -L/usr/local/lib -o “img” ./img.o -l opencv_core -l opencv_highgui -l opencv_imgcodecs
    /usr/bin/ld: cannot find -l opencv_core
    /usr/bin/ld: cannot find -l opencv_highgui
    /usr/bin/ld: cannot find -l opencv_imgcodecs
    collect2: error: ld returned 1 exit status
    make: *** [img] Error 1

    01:32:43 Build Finished (took 89ms)

    i have following your all tutorials but this error does not finished

    • There is no space between “-l” and the lib name. It should be “-lopencv_core” and so on…

      • Khalid Usman

        well as you mentioned in the above tutorial to include the libraries without using -l
        i did same

        Still in GCC C++ Linker » Libraries, add the libraries you’ll need in your project in Libraries (-l). We’re going to need 3 to our project (don’t forget to link opencv_imgcodecs, since imread() has moved to it in OpenCV 3):

        opencv_core

        opencv_imgcodecs

        opencv_highgui

        so i am getting error

      • That’s akward, because Eclipse wouldn’t add that space if you have typed it correctly. Does ‘pkg-config –cflags opencv’ perform as expected?

  • Hyon Kim

    Hi Rodrigo

    Thanks for the great tutorial. I have managed to follow it until the test.
    I cannot find Release folder in the project file in my terminal. I also tried to compile it by g++ in the terminal but it returned an error.
    Could you please let me know how I can go through successfully this situation and make sure my eclipse is working together with OpenCV?

    Thank you so much for your help!
    Hyon

  • Bruno Carazato

    It is necessary link the library

    “opencv_imgproc”

    • Actually, for the sample I provide here, it isn’t.

      • Bruno Carazato

        Yes, but this library is widely used and could avoid some errors. Thanks for this tutorial it is very detailed.

  • Raphael Rocha

    dude, thanks for the tutorial, works like a charm. but did you already created a template plugin? i’m trying to create one but it’s really difficult make it work.
    After some time it’s really annoying having to declare all the libs

    • Haha, I completely agree. That’s why I use CMake 🙂 Also, because I program both on Windows and Linux. So, I never tried to create a template. Sorry, I can’t help you with that but recommend using CMake.

  • Юра Попів

    Hey Rodrigo, your example is succesfully running, after this i’m trying run this

    #include
    #include
    #include

    int main(int argc, char** argv) {
    cvNamedWindow( “PlayVideo”, CV_WINDOW_AUTOSIZE ); // Создание окна
    CvCapture* capture = cvCreateFileCapture( argv[1] ); // Открытие видеофайла для формирования структуры CvCapture
    IplImage* frame; // Кадр
    while(1)
    {
    frame = cvQueryFrame( capture ); // Последовательное чтение кадров
    if( !frame ) break; // Конец файла, кадров больше нет
    cvShowImage( “PlayVideo”, frame ); // Отображение кадра
    char c = cvWaitKey(33); // Ожидание 33 мс, получение ASCII кода клавиши
    if( c == 27 ) break; // Если Esc – выход из цикла
    }
    cvReleaseCapture( &capture ); // Закрытие файла
    cvDestroyWindow( “PlayVideo” ); // Уничтожение окна
    }

    but got this
    main.cpp:(.text.startup+0x1c): undefined reference to `cvCreateFileCapture’
    main.cpp:(.text.startup+0x50): undefined reference to `cvQueryFrame’
    main.cpp:(.text.startup+0x5d): undefined reference to `cvReleaseCapture’
    collect2: error: ld returned 1 exit status
    make: *** [DisplayImage] Ошибка 1

    can u help?

    • Don’t use this code, this uses C API that is no longer being developed and you’ll find no support.

      • Юра Попів

        Thanks, can you recommend some tutorials of c++ programing using opencv(ubuntu)?

      • Sorry, but no. I wish I had more time to do more videos and tutorials. There are a lot of things on stackoverflow.com, where some people (me included) usually help on user’s specific problems. Perhaps, you should give it a try. Don’t forget to use opencv tag (http://stackoverflow.com/questions/tagged/opencv ).

  • Юра Попів

    Description Resource Path Location Type

    Function ‘imread’ could not be resolved main.cpp /DisplayImage line 5 Semantic Error

    Function ‘imshow’ could not be resolved main.cpp /DisplayImage line 6 Semantic Error

    Function ‘waitKey’ could not be resolved main.cpp /DisplayImage line 8 Semantic Error

    Symbol ‘cv’ could not be resolved main.cpp /DisplayImage line 2 Semantic Error

    Type ‘Mat’ could not be resolved main.cpp /DisplayImage line 5 Semantic Error

    help me)

  • Patrick Huie

    Hi Rodrigo,
    Everything worked until I tried to run the file from the terminal. For some reason, when I did a ls of the Release folder, no highlighted folder showed up. I figured that (i called my first file test) test.o would be the one to execute, but it said permissions denied. Do you know how to fix it?

    Anyways, thanks so much for these well written instructions and accompanying video. Should it work, they’ll make my life much easier!

    • I answered your email. I need more information to help.

      • Patrick Huie

        yes, i’m sorry. I sent a follow up email.

  • Haroldo Gomes Carvalho

    Ola Rodrigo,

    Estou utilizando o Ubuntu 14.10 e compilando via terminal. Preciso usar a biblioteca imgcodecs para subrair o fundo de umas imgs. mas essa biblioteca nao se encontra na pasta . Como faco para install essa biblioteca? Ja tentei pelo sudo apt- get install e a seguinte msg aparece: E: Unable to locate package imgcodecs.
    Obrigado.

    • Olá Haroldo, imgcodecs está presente somente no OpenCV 3. Tem certeza que você usa essa versão?

      • Haroldo Carvalho

        Olá Rodrigo, então esse é o problema. Estou usando a versão 2.4. Não instalei a 3.0 pelo fato de alguns colegas relatarem alguns problemas na mesma. Obrigado pela informação!

      • Espero ter ajudado! Abraço.

      • Haroldo Carvalho

        Ajudou bastante. Grato!

  • Im still getting problems with eclipse idk why I have linked the libraries and paths like you said but when I paste it eclipse cant resolve any of the cv functions.

  • Sanman Sabane

    How can I run the same setup with windows ?

  • Cano Ríos Sánchez

    Hola, antes que nada le agradezco por su tiempo, esta guía me ha funcionado mas que cualquier otra.
    he seguido los pasos y todo bien, hasta llegar al paso final, en donde por medio de la consola ejecuto la aplicación ya construida con eclipse.
    mi aplicacion se llama “miPrimerCV” y después de intentar lanzar la aplicación recibo el mensaje de error siguiente:

    canorioss@canorioss:/opt/lampp/htdocs/miPrimerCV/Release$ ./miPrimerCV takumaCano.png

    ./miPrimerCV: error while loading shared libraries: libopencv_core.so.3.0: cannot open shared object file: No such file or directory

    También obtengo el mismo error su doy click al botón “ejecutar” en Eclipse.

    Espero pueda ayudarme usted o alguna de las personas que han logrado utilizar esta libreria tan interesante como es OpenCV.

  • Gabriel Huhn

    Você sabe como criar um tipo de projeto pra openCV no eclipse? No momento em que eu crio esse novo projeto ele já vem com todas essas configuração que você acabou de fazer por padrão.

    • Não, mas eu uso o cmake para gerar os projetos para as IDEs que uso.

  • Gabriel Huhn

    Rodrigo. Por que quando eu não consigo rodar o programa dentro do eclipse? Pra mim fala que o arquivo de programa não existe. Mas ele existe sim. Se você for na pasta release ele vai ta la e você pode rodar ele pelo terminal normalmente…

    • Gabriel Huhn

      O eclipse não havia configurado corretamente o caminho para a pasta release. Por isso o ele não encontrava o executável.

      • Bom saber que você conseguiu resolver o problema! Qualquer dúvida, é só falar…

  • Gabriel Huhn

    no comando “pkg-config –libs opencv” e no anterior seu editor juntou os dois hífens!

  • suleyman sumertas

    hi rodrigo, I’m using windows instead of Ubuntu. Folder paths are different and I can’t defined the libraries for the project and ı got this message :” Function ‘imshow’ could not be resolved”. I suppose that means a library fail. Could you explain for latest opencv for windows in eclipse c++?

  • Veni Rigel Ballesteros

    hi rodrigo, I have this error message:

    OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp, line 269

    terminate called after throwing an instance of ‘cv::Exception’

    what(): /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269: error: (-215) size.width>0 && size.height>0 in function imshow

    and where is the folder location of this line ” ~/Images/lena.jpg” ??
    thanks in advance!

    • Hi Veni, you have to pass the correct path to the image in your case. The tilde “~” points to your “home” directory. The error you’re having is because the image isn’t there. Try to pass another image that you have. Good luck!

      • Veni Rigel Ballesteros

        i have solved the problem with your reply, thank you very much! i’m currently working on machine vision project without any prior experience, your blog helped me a lot!

      • Good to know the blog is helping. Good luck with your project!

      • Raphael Luciano

        Hi Rodrigo,
        First, thank you for the great work on this blog.
        I’m having the same error message, however the source of my problem it’s different. After I call function roi (line bellow):
        x,y,w,h = roi
        dst = dst[y:y+h, x:x+w]
        cv2.imshow(‘dst’,dst)

        my image (dst variable) ir returns nothing (that’s why the cv2.imshow thinks there is no image).
        Do you have any ideia do help me on this issue?

        Thank you since now.

      • Hi Raphael, are you sure x,y,w,h have values? Also, I’m considering dst already contains data.

      • Raphael Luciano

        This is the problem I meant. Roi itself has no value (consequently, x, y, w, h hasn’t as well).
        The dst has the their correct value. And there is a function called before:
        newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
        and that function returns roi = (0, 0, 0, 0)
        But I have still nor figured out the reason.

        Thank you for the answer =)

      • if (x, y, w, h) == (0, 0, 0, 0), then dst[y:y+h; x:x+w] == dst[0:0;0:0] == nothing

  • Pingback: Using OpenCV 3.0.0 with Eclipse – 向右走()

  • Jiang

    Thanks, man! Both for this and the OpenCV installation.
    All the procedures are clear and easy to understand.
    You are gonna be a great teacher : )

  • Maj Id

    Hey Rodrigo,

    Thanks everything was ok. I’ve got a question. where is the equivalent place for run configuration in CodeBlocks IDE?
    The program you’ve provided was compiled correctly by CodeBlocks I just neet to pass the image to the program which I don’t know how as you’ve done in Eclipse by putting the address of image in run configuration.

    • Sorry Maj Id, I don’t know the equivalent of this for CodeBlocks IDE, because I’ve never used this IDE. Really sorry.
      If you figure it out, tell us. Thanks!

  • Maj Id

    Hey Rodrigo,

    After success in running your examples for installing Opencv in Ubuntu I tried it on Eclipse. in Build part I got this message:

    collect2: error: ld returned 1 exit status
    make: *** [tryc++11features] Fehler 1
    15:09:38 Build Finished (took 114ms

    in Terminal I was able to run ./DisplayImage and see the image. however in Eclipse I get this error which I don’t know what the reason is:

    OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/majid/opencv/opencv-3.0.0-alpha/modules/highgui/src/window.cpp, line 274
    terminate called after throwing an instance of ‘cv::Exception’
    what(): /home/majid/opencv/opencv-3.0.0-alpha/modules/highgui/src/window.cpp:274: error: (-215) size.width>0 && size.height>0 in function imshow

    I thank you if you give me some advice how to resolve it .

    • Sameer Kumar Prasad

      I am also getting the same error:

      OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/ubuntu/opencv/opencv-3.0.0/modules/highgui/src/window.cpp, line 279

      terminate called after throwing an instance of ‘cv::Exception’

      what(): /home/ubuntu/opencv/opencv-3.0.0/modules/highgui/src/window.cpp:279: error: (-215) size.width>0 && size.height>0 in function imshow

      Aborted (core dumped)

      were you able to find any solution or @Rodrigo can you help me with this

  • Jose L. Rico

    as much as I try, when I run ./facedetect lena.jpg I get bash: ./facedetect: no such a file or directory. Why is this?

    • Supposing ‘facedetect’ is your {project_name}, are you sure ‘lena.jpg’ is in the same directory?

      • Jose L. Rico

        Lena is not in the same directory, but how then can I test it? I tried with eclipse as you explained but the compiler does not finds cv, or at least it says it does not recognize it.

      • Well, if ‘lena.jpg’ isn’t in the same directory, it won’t work. However, to use ‘./facedetect’ you have to be sure your project name is ‘facedetect’ and the build was successful. Email me with these information so I can help you.

      • Jose L. Rico

        I rerun the whole batch from 0. When testing it I got this error “jose@jose-HP-G61-Notebook-PC:~/opencv/opencv-3.0.0-beta/samples$ ./DisplayImage lena.jpg
        bash: ./DisplayImage: No such file or directory”
        All I did to your syntax was to change the alpha word to beta

      • Did you unzip the provided files inside ‘samples’ directory?
        Did you check if the ‘DisplayImage’ and ‘lena.jpg’ are inside ‘samples’ directory as well?

        Did the OpenCv samples work?

      • Jose L. Rico

        How can I email you? and I did…

      • You can use the form available http://rodrigoberriel.com/contact/ or send the email to rodrigo[dot]berriel[at]gmail[dot]com

      • Jose L. Rico

        😀 Fully completed!!! Thanks dude!

  • wathmal

    hi, great tutorial.
    btw how can know the libraries exactly to use with my project?

    • Well, ‘core’, ‘imgcodecs’ and ‘highgui’ and kind standard when u need to use some GUI. The others you can search for ‘opencv’ + ‘name of the function you need to use’ and then you’ll see the opencv doc with the lib required to use that function

  • Alex

    Dashes are missing on pkg-config options in the “Linking OpenCV to the newly created project” part.

  • Pingback: OpenCV Filters: Smoothing (Blurring) » Rodrigo Berriel()

  • Wei qi

    Great~ Thanks a lot