Ubuntu18.04 uses the opencv library to write and open the camera to compress the video

1. Install opencv

1. Installation environment

Ubuntu 18.04 system
OpenCV version installed on VMware virtual machine: 3.4.12

2. Download OpenCV3.4.11

Domestic fast download website: click to jump,
you can directly use the browser in the virtual machine (download, foreign official website download address: click to jump , it is not recommended to download on foreign websites, it is very slow.
insert image description here
After downloading, directly extract it to the main directory:
insert image description here

3. Use cmake to install opencv

First enter the decompressed folder: opencv-3.4.12
insert image description here
Enter the root user, and update:
insert image description here
Then install cmake:
insert image description here
key point: install dependent libraries:
command:
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff5.dev libswscale-dev libjasper-dev
But the last library requires libjasper-dev to be installed separately:
insert image description here
insert image description here
insert image description here
first install this library, and then enter the above command to install other libraries uniformly.

Create the build folder again, and then enter the folder we created: build
insert image description here
uses cmake compilation parameters:
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local …
insert image description here

4. Use make to create and compile

It is still carried out under the build folder:
sudo make
This step will take a long time, just wait patiently.
insert image description here

5. Install

sudo make install
insert image description here

6. Configure the environment

Use the command sudo gedit /etc/ld.so.conf.d/opencv.conf to modify the opencv.conf file, the opened file is empty, add the installation path of the opencv library: /usr/local/lib
insert image description here

After saving, you will see a warning message, don't worry, it's normal.
insert image description here
Update system shared link library: sudo ldconfig
configure bash, modify bash.bashrc file: sudo gedit /etc/bash.bashrc
insert image description here
Add at the end of the file:
PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH
insert image description here
Save and exit, then Execute the following command to make the configuration take effect: source /etc/bash.bashrc
Update: sudo updatedb
Next check the version information of opencv: pkg-config --modversion opencv
insert image description here

2. Example: picture

Create a folder to store code files:
mkdir code
cd code
insert image description here
Create a test1.cpp file.
nano test1.cpp
and enter the 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("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;
}

Compilation file:
c++ file Compilation instruction: g++ test1.cpp -o test1 pkg-config --cflags --libs opencv
If it is a built .c file, use: gcc test1.cpp -o test1pkg-config --cflags --libs opencv

In the above compilation command, we actually used a tool "pkg-config", which mainly has the following functions:
1. Check the version number of the library. If the version of the required library does not meet the requirements, it will print an error message to avoid linking the wrong version of the library file.
2. Obtain compilation preprocessing parameters, such as macro definition and header file location.
3. Obtain link parameters, such as the location of the library and other dependent libraries, the file name and some other connection parameters.
4. Automatically add the settings of other libraries that depend on it.
With this tool, our compilation will be very convenient (but before that, you must make sure that there is a pkgconfig folder in the directory of the OpenCV installation link library file you installed. There is an opencv.pc file in this folder, in fact, this is the OpenCV configuration file under pkg-config).
When using pkg-config, the option –cflags is used to specify the directory where the header files required by the program are compiled, and the option –libs is to specify the directory of the dynamic link library required by the program when linking.
insert image description here
insert image description here
Output result: ./test1
insert image description here
generates a test.png from lena.jpg, and the rendering effect is different.

3. Example: video

1. The virtual machine obtains camera permission

Under Windows, use win+R to open the command window, and enter services.msc.
insert image description here
insert image description here
Find vmware usb arbitration and make sure it is opened normally.
In VMware click on "Virtual Machine" and then click on "Settings(S)...". Select "USB Controller", set "USB Compatibility" to "USB 3.0", and click OK.
Select "Virtual Machine", then select "Removable Devices", then select "IMC Networks USB2.0 VGA UVC WebCam", and finally click "Connect", and then click "OK" in the pop-up window.
If there is a small green dot on the camera icon in the lower right corner of the virtual machine, the connection is successful.
If he said that the connection failed, then you should turn on the camera on your host computer first, then use the camera to turn it on, and then the connection will be successful.

2. Play video

Create a test2.cpp file:
nano test2.cpp

#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
    
    
	//读取视频
	VideoCapture capture("MH.mp4");
	//循环显示每一帧
	while(1){
    
    
		Mat frame;//定义一个Mat变量,用于存储每一帧的图像
		capture >> frame;//读取当前帧
		if(frame.empty())//播放完毕,退出
			break;
		imshow("读取视频帧",frame);//显示当前帧
		waitKey(30);//掩饰30ms
	}
	system("pause");
	return 0;
}


1. If the statement: VideoCapture capture(0), the following parameters are set to 0, then read the video from the camera and display each frame in a loop; if it is set to a video file name, such as: MH.mp4, the video will be captured Read and loop through each frame.
2. The Mat data structure in the while loop body is actually a dot matrix, corresponding to each point on the image. The collection of points forms a frame of image. For details about Mat, please refer to: Mat data structure in OpenCV 3. Statement: waitKey
( 30) , the parameter unit in is ms milliseconds, that is, the interval between each frame is 30 ms, this statement cannot be deleted, otherwise it will execute an error, and the video cannot be played or recorded.
This code will keep running in the while loop. If you try to close the image display window with the mouse, you will find that it cannot be closed. You need to use the keyboard Ctrl+C to forcibly interrupt the program, which is very unfriendly.

Compile the test2.cpp file: g++ test2.cpp -o test2 pkg-config --cflags --libs opencv
insert image description here
output:
./test2
insert image description here

3. Turn on the camera to record video

Create a test3.cpp file.
nano test3.cpp

/*********************************************************************
打开电脑摄像头,空格控制视频录制,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;

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();
	return 0;
}

Create file: nano test3.cpp
insert image description here
compile test3.cpp file: g++ test3.cpp -o test3 pkg-config --cflags --libs opencv
insert image description here
output:
./test3
insert image description here
end record means the recording has not started yet.
insert image description here
Press the space, recording means start recording.
Press esc to save and exit.

References

click to jump

Guess you like

Origin blog.csdn.net/asdhnkhn/article/details/127034636