Practice Opencv3.4.1 under Ubuntu 18.04 system

1. Install Opencv3.4.1 and configure dependent libraries

  • Download the Sources version from the official website
  • Copy the downloaded file to the main directory
    Insert picture description here
  • Install dependent libraries and cmake
    enter the following command
sudo apt-get install cmake  
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff5.dev libswscale-dev libjasper-dev  
  • After installing cmake, execute the command, create a compilation folder, and enter the folder for configuration
mkdir my_build_dir
cd my_build_dir

input the command

cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..

Execution result:
Insert picture description here
enter the command:

sudo make

Start the installation:
Insert picture description here
After a long wait, it is finally finished.
Insert picture description here
Enter the command:

sudo make install
  • After the execution is completed, you need to configure some OpenCV compilation environment. First add the OpenCV library to the path, so that the system can find the
    input command:
sudo gedit /etc/ld.so.conf.d/opencv.conf 

After opening it is a blank file, enter in it:

/usr/local/lib  

Insert picture description here

  • Save back to the command line interface
  • Execute the following command to make the configuration path just now effective
sudo ldconfig  
  • Configure bash
sudo gedit /etc/bash.bashrc  

Add at the end

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

Insert picture description here
Save, enter the following command:

source /etc/bash.bashrc  
sudo updatedb  

Configuration complete

Two, programming using opencv

  • Create a new test.cpp file under the previously created directory my_build_dir
    Enter the command:
touch test.cpp

Open test.cpp and enter the following code:

#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("abcd.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;
}

Insert picture description here
At the same time, put the picture in the same directory as the test.cpp file

Insert picture description here

  • Save the entered code and compile it:
g++ /test.cpp -o test `pkg-config --cflags --libs opencv`
./test

Execution effect:
Insert picture description here

  • Thinking
    pay attention to the gcc compilation command:
 gcc  test1.cpp  -o  test1  `pkg-config --cflags --libs opencv`

How does it get the path of the opencv header file and link lib library file?
Results of the:
Insert picture description here

Answer: pkg-config --cflags --libs opencv This represents a string, through this address to find this library, –cflags is used to specify the directory where the header files are needed when the program is compiled, and –libs is to specify the program in The directory of the dynamic link library needed for linking.

Three, opencv library to write a program to open the camera compressed video exercise

1. Turn on the camera

  • Create and enter a test1.c file
touch test1.c
vim test1.c

Enter the following code (this code is problematic):

#include<opencv2/opencv.hpp>
using namespace cv;

int main()
{
    
    
	//从摄像头读取视频
	VideoCapture capture(0);
	//循环显示每一帧
	while (1)
	{
    
    
		Mat frame;//定义一个Mat变量,用于存储每一帧的图像
		capture >> frame;//读取当前帧
		imshow("读取视频帧", frame);//显示当前帧
		waitKey(30);//延时30ms
	}

	system("pause");
	return 0;
}
  • Before compiling, we first connect the camera to the virtual machine
    Insert picture description here
    and click Yes
  • Start compiling and running
g++ test1.c -o test1 `pkg-config --cflags --libs opencv`
./test1

Execution result:
Insert picture description here
We can see that the operation was not successful and an error was reported.
Don't panic, after searching on Baidu, I finally found a solution.
Insert picture description here
Insert picture description here
If you are USB 2.0, change to USB 3.0, if it is USB 3.0, change to USB 2.0.

  • Compile and run again, the camera is successfully opened, but because our code is wrong, the code will continue to run in the while loop, so clicking the red × in the upper right corner does not turn off the camera. You can only use Ctrl+x to forcibly interrupt program. Next we modify the program.
    Insert picture description here

2. Modify the program

Add the following code to the while loop on the original code:

if(waitKey(30)==27) //按esc键退出,
                {
    
    
                        break;
                }

In this way, you can press Esc to interrupt the loop and turn off the camera.
Insert picture description here

  • Open a video file on the hard drive to play

3. Camera with opencv

  • Create test2.c
touch test2.c

Enter code:

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

int main()
{
    
    
	//打开电脑摄像头
	VideoCapture cap(0);
	if (!cap.isOpened())
	{
    
    
		cout << "error" << endl;
		waitKey(0);
		return 0;
	}

	//获得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;//记录键盘按键
	char startOrStop = 1;//0  开始录制视频; 1 结束录制视频
	char flag = 0;//正在录制标志 0-不在录制; 1-正在录制

	while (1)
	{
    
    
		cap >> frame;
		key = waitKey(100);
		if (key == 32)//按下空格开始录制、暂停录制   可以来回切换
		{
    
    
			startOrStop = 1 - startOrStop;
			if (startOrStop == 0)
			{
    
    
				flag = 1;
			}
		}
		if (key == 27)//按下ESC退出整个程序,保存视频文件到磁盘
		{
    
    
			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();
}

 g++ test2.c -o test2 `pkg-config --cflags --libs opencv`
./test2

After running, press the space key to record, and Esc ends the record. The
video is saved in the mytest directory
Insert picture description here

Insert picture description here

4. Open a video file on the hard disk with opencv

We only need to modify the previous test1.c code to
Insert picture description here
compile and run:

g++ test1.c -o test1 `pkg-config --cflags --libs opencv`
./test1

result:
Insert picture description here

5. Thinking

  • In the while loop on line 9, what data structure is Mat? Why is it necessary to add a waitKey delay code and delete it?
    (1) Mat is a class. It consists of two parts of data: a matrix header (including matrix size, storage method, storage address and other information) and a pointer to a matrix of all pixel values ​​(depending on the selected storage method, the matrix can have different dimensions).
    (2) If waitKey is not added, the alternate between reading the current frame and displaying the current frame is too fast, the video cannot be displayed, and it will disappear at once, so it cannot be deleted.

Four, summary

This time through this study, I learned to use opencv. Although I encountered many problems during installation and use, every time I encountered a problem, I would feel a sense of frustration and irritability, but the joy of solving the problem is also huge. ; Opencv is a very useful tool. It can be used in image acquisition and face recognition. I am very happy that I can learn how to use it.

Guess you like

Origin blog.csdn.net/qq_42762607/article/details/109371398