Install and use opencv under ubantu

One, opencv installation

1. Opencv download
Official website download: http://sourceforge.net/projects/opencvlibrary/
2. Installation
If opencv downloaded in ubantu
opens the ubantu command line, enter the following command
(decompression)

unzip opencv-3.4.1.zip

Enter the decompressed file

cd opencv-3.4.12

Install cmake

sudo apt-get install cmake  

Install dependent libraries

sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff5.dev libswscale-dev libjasper-dev  

After installing the above items, create a compilation folder

mkdir build

And enter the folder

cd build

camke

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

Execute the command, it takes a little longer

sudo make

Installation, it takes a little longer

sudo make install

Configuration Environment

sudo vi /etc/ld.so.conf.d/opencv.conf 

After opening the file, add directly at the end

/usr/local/lib  

Save the file and exit
Execute the following command to make the previous operation effective

sudo ldconfig 

Configure bash

sudo vi /etc/bash.bashrc  

Add at the end

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

Save and exit, execute the following command to make the configuration take effect

source /etc/bash.bashrc 

Two, opencv use

1. Picture usage

In the installation package folder under the new folder the Test
(: folder where the file you want to test picture on the program note)

mkdir test

Create test.cpp

vi test.cpp

Add the following code in test.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("lena.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;
}

Save, exit and compile

g++ test.cpp -o test `pkg-config --cflags --libs opencv`

I won’t say much about the g++ command in the above command. Under the explanation of the function below, a tool'pkg-config' is used here, the main function is:
check the version number of the library. If the required library version does not meet the requirements, it will print out an error message to avoid linking the wrong version of the library file.
Obtain compilation preprocessing parameters, such as macro definitions, and the location of header files.
Obtain link parameters, such as the location of the library and other dependent libraries, file names, and other link parameters.
Automatically add the settings of other dependent libraries, explained in detail: https://blog.csdn.net/catherine627/article/details/53375620
run

./test

Insert picture description here
So far done

2. Video usage

Create a new file test1.cpp


#include<opencv2/opencv.hpp>
using namespace cv;
int main()
{
    
    
        VideoCapture capture(0);//从摄像头读取视频
        //循环显示每一帧
        while(1)
        {
    
    
                Mat frame;//定义一个Mat变量,用于存储每一帧的图像
                capture >> frame;//读取当前帧
                imshow("read video frame",frame);//显示当前帧
                waitKey(30);//延时30ms
        }
        system("pause");
        return 0;
}


If you want to read a video file, change the line that reads the video file to (note that you need to add the suffix)

VideoCapture capture("视频文件名")

The next step is to compile

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

run

./test1

Mat: Mat is essentially a class composed of two data parts: (contains information such as the size of the matrix, the method used for storage, the address of the matrix storage, etc.) the matrix header and a pointer to the matrix containing the pixel value ( Data can be stored in any dimension according to the method selected for storage). The size of the matrix head is constant. However, the size of the matrix itself varies from image to image, and is usually of a larger order of magnitude. Therefore, when you pass the image in your program and sometimes create a copy of the image, you need to spend a lot of money to generate the image matrix itself, not the head of the image. OpenCV is an image processing library, which contains a large number of image processing functions. To solve the computational challenges, you will eventually use multiple functions in the library most of the time. For this reason, it is a common practice to pass images to functions in the library. We should not forget that we are talking about image processing algorithms that are often quite computationally intensive. The last thing we want to do is to further reduce the speed of your program by making unnecessary copies of potentially large images.

To solve this problem, OpenCV uses a reference counting system. The idea is that each object of Mat has its own head, but it is possible for them to share the matrix between two instances of the same address by letting their matrix pointer point to the same address. In addition, the copy operator will only copy the head of the matrix, and will also copy the pointer to the matrix, but not the matrix itself.
Quote from: Detailed explanation of Mat in OpenCV

waitKey(int delay): Delay function. This function is useful when displaying video. It is used to set the program to wait for "delay"ms after displaying a frame of image before displaying the next frame of video; if cvWaitKey(0) is used, only The first frame of video will be displayed.
If the program wants to respond to a certain key, you can use if(cvWaitKey(1)==Keyvalue);
after test1 runs, it will run in the while loop. If you try to close the image display window with the mouse, you will find that it can’t be turned off. You need to use the keyboard Ctrl+C to forcibly interrupt the program (you can even close the program only by closing the command line window), which is very unfriendly.
Below is the improved code

/*********************************************************************
打开电脑摄像头,空格控制视频录制,ESC退出并保存视频RecordVideo.avi
*********************************************************************/
#include<iostream>
#include <opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;

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

	//获得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();
}

Guess you like

Origin blog.csdn.net/xianyudewo/article/details/109347521