Install OpenCV under Ubuntu and use

1 what is Opencv OpenCV is a cross platform computer vision and machine learning software library based on BSD license (...
2.1 download Opencv
2.2 configuration environment of opencv
3.1 code file creation
3.2 compiled files
3.2 picture effect
4.1 playing video
4.2 call the camera to collect video

1 what is Opencv
  • OpenCV is a cross platform computer vision and machine learning software library based on BSD license (open source), which can run on Linux, Windows, Android and Mac OS operating systems.
  • It is lightweight and efficient - it is composed of a series of C functions and a small number of C + + classes. At the same time, it provides interfaces with Python, Ruby, MATLAB and other languages, and realizes many general algorithms in image processing and computer vision.
  • Applications include:
    Human computer interaction, object recognition, image segmentation, face recognition, motion recognition, motion tracking, robot, motion analysis, machine vision, structure analysis, vehicle safe driving
2. Install Opencv

2.1 download Opencv

(1) Download Opencv 3.4.11 package

  • Download directly in the virtual machine using the browser.

Domestic fast download address: https://www.bzblog.online/wordpress/index.php/2020/03/09/opencvdownload/

Note: it can also be downloaded from the official website https://opencv.org , but the download is too slow!


(2) Decompress package

  • Before unpacking the package, copy opencv-3.4.11.zip to the home folder (the Chinese version I use, the Chinese version is the main directory)
  • Type the command unzip opencv-3.4.11.zip in the terminal to complete the decompression.


(3) Installing OpencV using dependency libraries and cmake

  • First enter the extracted folder: opencv – 3.4.11
cd opencv-3.4.11

  • Enter the root permission and update it.
sudo su sudo apt-get update

  • Then execute the next command to install cmake
sudo apt-get install cmake

  • Then execute the next command to install the dependent library
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff5.dev libswscale-dev libjasper-dev

  • Execute the next command to create the build folder
mkdir build

  • Then execute the next command to enter the folder we created: build
cd build

  • Use the first command below to compile parameters with cmake, or use the default parameters of the second command
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local .. cmake ..

(4) Create a compilation using make

  • In the build folder
sudo make

Note: single thread compilation: sudo make, which will take a long time. If you want to compile faster, you can use the command: sudo make -j4, and - j4 means to compile with four threads.

Complete compilation:

(5) Execute the next command to install

sudo make install


When displayed here, the installation is completed.

2.2 configuration environment of opencv

  • Add the opencv library to the path so that the system can find it
    Type the next command to modify the opencv.conf file, and the open file is empty.
sudo gedit /etc/ld.so.conf.d/opencv.conf

Then add the installation path of opencv Library: / usr/local/lib in the folder, click save and close. (if it cannot be saved, please confirm your identity as root, and there is a warning message that can be ignored after closing)


  • Return to the command line interface, execute the next command to make the path just configured effective, and update the system shared link library
sudo ldconfig

  • Configure Bash and modify bash.bashrc file
sudo gedit /etc/bash.bashrc


Add at the end of the document:

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH


Click save and exit (warnings can be ignored)

  • Then execute the following command to make the configuration effective
source /etc/bash.bashrc

  • Update it
sudo updatedb

Note: when sudo updatedb reports an error: command not found, first execute the command apt get install mlocate, Download mlocate, and then execute sudo updatedb. Other questions can be queried on Baidu.

  • The configuration has been completed here. Verify whether the configuration is successful. Next, check the version information of opencv
pkg-config --modversion opencv


At this point, you can confirm that OpencV is installed successfully!

3 Opencv processes pictures

3.1 code file creation

  • First, create a code storage folder code in the home directory, and then enter the folder
mkdir code cd code

  • Create another test1.cpp file
gedit test1.cpp

Copy and paste the following code
test1.cpp:

#include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main(int argc, char** argv) { CvPoint center; double scale = -3; IplImage* image = cvLoadImage("luhan.jpg"); argc == 2? cvLoadImage(argv[1]) : 0; cvShowImage("Image", image); if (!image) return -1; center = cvPoint(image->width / 2, image->height / 2); for (int i = 0;i<image->height;i++) for (int j = 0;j<image->width;j++) { double dx = (double)(j - center.x) / center.x; double dy = (double)(i - center.y) / center.y; double weight = exp((dx*dx + dy*dy)*scale); uchar* ptr = &CV_IMAGE_ELEM(image, uchar, i, j * 3); ptr[0] = cvRound(ptr[0] * weight); ptr[1] = cvRound(ptr[1] * weight); ptr[2] = cvRound(ptr[2] * weight); } Mat src;Mat dst; src = cvarrToMat(image); cv::imwrite("test.png", src); cvNamedWindow("test",1); imshow("test", src); cvWaitKey(); return 0; }

3.2 compiled files

Execute the following command:

gcc test1.cpp -o test1 `pkg-config --cflags --libs opencv`

gcc compiler: gcc + file name + - o + output file stream name + ` support package

Found compilation error! Here you need to compile your interface module with a C + + compiler. After changing gcc to g + +, it is correct. It can be seen that there is an executable file test1

3.2 picture effect

  • Save a picture in this code folder. The file name is luhan.jpg

Note: the file name should be consistent with the file name in the above file test1.cpp code!

  • Execute command output results
./test1

It can be seen that luhan.jpg generates a test.png in the code folder, which presents different effects.

4. Special effect processing of video with OpenCV

4.1 playing video

  • Create a test2.cpp file
gedit test2.cpp

Copy and paste the following code
test2.cpp:

#include <opencv2/opencv.hpp> using namespace cv; int main() { //Read video from camera VideoCapture capture("luhanSuperChampion.mp4"); //Cycle through each frame while(1){ Mat frame;//Define a Mat variable to store the image of each frame capture >> frame;//Read current frame if(frame.empty())//Play finished, exit break; imshow("Read video frame",frame);//Displays the current frame waitKey(30);//Cover up 30ms } system("pause"); return 0; }

Code comments:
① If the statement is videocapture (0) and the subsequent parameter is set to 0, the video will be read from the camera and each frame will be displayed circularly; If it is set to the file name of a video, such as luhanSuperChampion.mp4, the video will be read and displayed in a circular manner.
So if you want to open a video file on your hard disk to play, you can replace the video file name in the seventh line of the code.
② The Mat data structure in the while loop is actually a dot matrix, which corresponds to each point on the image. The set of points forms a frame image. For a detailed explanation of Mat, please see the Mat data structure in OpenCV.
③ Statement: waitKey(30). The parameter unit in the statement is MS, that is, the interval of each frame is 30 ms. this statement cannot be deleted. Otherwise, an error will be executed and the video cannot be played or recorded.
④ To terminate the video playback, you can refer to line 45 in test3.cpp below and use ESC key to control exit.

  • Save a video in this code folder. The file name is luhanSuperChampion.mp4.

Note: the file name should be consistent with the file name in the above file test2.cpp code!

  • You are now ready to compile the test2.cpp file
g++ test2.cpp -o test2 `pkg-config --cflags --libs opencv`

Note: g is also used here++

  • Operation results
./test2


Visible code has played out the video file!

4.2 call the camera to collect video

4.2.1 virtual machine obtaining camera permission

  • Use the shortcut key Win + R in Windows system, type services.msc, and press enter to confirm
  • Locate the VMware USB Arbitration S... Service and make sure it is starting

  • In the virtual machine environment, click "virtual machine", and then click "settings (S)...";
    Select "USB controller", set "USB compatibility" to "USB 3.1", and click "OK"

Note: when setting USB compatibility, some computers may be "USB 3.0", which is also OK!

  • Select "virtual machine", then "removable device", then "Quanta USB2.0 VGA UVC WebCam", finally click "connect", and then click "OK" in the pop-up window


It can be seen that the camera icon in the lower right corner of the virtual machine has a small green dot, that is, the connection is successful!

4.2.2 recording video

  • Create a test3.cpp file
gedit test3.cpp

Copy and paste the following code
test3.cpp:

/********************************************************************* Turn on the computer camera, control the video recording with a blank space, and ESC exits and saves the video RecordVideo.avi *********************************************************************/ #include<iostream> #include <opencv2/opencv.hpp> #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; int main() { //Turn on the computer camera VideoCapture cap(0); if (!cap.isOpened()) { cout << "error" << endl; waitKey(0); return 0; } //Get the resolution of cap int w = static_cast<int>(cap.get(CV_CAP_PROP_FRAME_WIDTH)); int h = static_cast<int>(cap.get(CV_CAP_PROP_FRAME_HEIGHT)); Size videoSize(w, h); VideoWriter writer("RecordVideo.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, videoSize); Mat frame; int key;//Record keyboard keys char startOrStop = 1;//0 starts recording video; 1 end recording video char flag = 0;//Recording flag 0 - not recording; 1 - recording while (1) { cap >> frame; key = waitKey(100); if (key == 32)//Press the space to start recording and pause recording to switch back and forth { startOrStop = 1 - startOrStop; if (startOrStop == 0) { flag = 1; } } if (key == 27)//Press ESC to exit the whole program and save the video file to disk { break; } if (startOrStop == 0 && flag==1) { writer << frame; cout << "recording" << endl; } else if (startOrStop == 1) { flag = 0; cout << "end recording" << endl; } imshow("picture", frame); } cap.release(); writer.release(); destroyAllWindows(); return 0; }

  • You are now ready to compile the test3.cpp file
g++ test3.cpp -o test3 `pkg-config --cflags --libs opencv`

  • Operation results
./test3

An. avi file is generated in the code folder, and frames are generated continuously


Press the space bar to start recording and pause recording, and you can switch back and forth;
When the ESC key is pressed, the video acquisition screen will close and the acquisition and recording process will end.

5 Summary

Installing Opencv under Ubuntu is indeed very long and tortuous, but don't worry and don't give up when you encounter problems. There are solutions to any problems, especially you can find information on the Internet. In the application of Opencv, there are many in-depth and interesting uses. You can also explore it yourself. I hope this blog is useful to you.

6 references

1,Baidu Encyclopedia: opencv
2,[embedded] opencv tutorial for windows10 & ubantu16.04 & Raspberry pie 3B + installation
3,Installation and use example of OpenCV3.4.11 under Ubuntu 18.04
4,Ubuntu 16.04 sudo updatedb reports an error: command not found solution

8 October 2021, 21:05 | Views: 8790

Add new comment

For adding a comment, please log in
or create account

0 comments