how to compile opencv c++ in ubuntu
To compile OpenCV C++ in Ubuntu, follow these steps:
Step 1: Update your system
Before installing OpenCV, it's a good idea to update your system to ensure you have the latest packages and dependencies. Open a terminal and run the following commands:
sudo apt update
sudo apt upgrade
Step 2: Install required dependencies
OpenCV requires several dependencies to be installed on your system. Run the following command to install the necessary packages:
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
Step 3: Clone the OpenCV repository
Next, you need to clone the OpenCV repository from GitHub. Run the following command to clone the repository:
git clone https://github.com/opencv/opencv.git
Step 4: Build OpenCV
Navigate to the cloned repository directory:
cd opencv
Create a build directory and navigate into it:
mkdir build
cd build
Generate the Makefile using CMake:
cmake ..
Build OpenCV:
make
Step 5: Install OpenCV
After the build process is complete, you can install OpenCV on your system. Run the following command:
sudo make install
Step 6: Configure the dynamic linker
To ensure that the OpenCV libraries can be found by your programs, you need to configure the dynamic linker. Run the following command:
sudo ldconfig
Step 7: Test your installation
To verify that OpenCV is installed correctly, you can compile and run a simple program. Create a new C++ file, for example test.cpp
, and add the following code:
#include <opencv2/opencv.hpp>
int main() {
cv::Mat image;
image = cv::imread("path_to_your_image.jpg");
if (image.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
cv::namedWindow("Display window", cv::WINDOW_AUTOSIZE);
cv::imshow("Display window", image);
cv::waitKey(0);
return 0;
}
Compile the program using the following command:
g++ test.cpp -o test `pkg-config --cflags --libs opencv4`
Run the compiled program:
./test
If you see a window displaying the image you provided the path to, then OpenCV has been successfully compiled and installed.
That's it! You have now successfully compiled OpenCV C++ in Ubuntu.