Take you through GDB and OpenCV


Preface

Debugging is indispensable in programming, so how to debug in Ubuntu? This article introduces the commonly used GDB debugging commands; the application of cameras in life is also very extensive, this article teaches you how to get started with OpenCV.


One, GDB debugging

First we edit a program (for debugging), the following is aProgram for reversing integer numbers

#include<stdio.h>
void ShowR(int iNum)          //整形数反转子程序
{
    
     
        while(iNum > 10)      //INum大于10时,进入循环
        {
    
     
        printf("%d",iNum%10);
        iNum=iNum/10;
        }
        printf("%d",iNum);
}
int main(void)
{
    
     
        int iNum;
        printf("Please input a numbrt:");
        scanf("%d",&iNum);
        printf("After revert:");
        ShowR(iNum);
}

Start GDB

Start GDBcommand:

gcc -o ShowR -g ShowR.c   //编译
gdb ShowR    //调试

The execution result is shown in the figure below:
GDB start

gcc -g option

The -g option can use the "native format" of operating Xiyong to generate debugging information, GDB can directly use this information, and other debuggers can also use this debugging information.

Note: If you want to use the debugger to execute an executable file, you must add the -g option in GCC compilation

GDB partial debugging commands

GDB view code command

(gdb) l(ist) // (letter l) List the source code starting from the first line, and list 10 lines in total.

The execution result is shown in the following figure:
Insert picture description here
If you want to continue to view the next code, you can directly space or continue to use the l command, and then hit the Enter key, use the space bar to view the next command as shown in the following figure:
Insert picture description here
You can also use number commands, Display a line directly-a line

(gdb) l number, number

As shown below
Insert picture description here
GDB set breakpoint command

Set breakpoints in number of lines:

(gdb) b(reakpoint) number

The number is the number of lines where the breakpoint is set. The example is shown in the figure below, (prompt to set the breakpoint successfully):
Insert picture description here
You can also set the breakpoint by the function name:

(gdb) b function name

An example is shown in the following figure (it prompts that the second breakpoint is successfully set):
Insert picture description here
You can view the breakpoint information through commands:

info b(reakpoint)

An example is shown in the figure below:
Insert picture description here

GDB program run command

GDB run program command

(gdb) run

Run the program to the breakpoint, it will stop running, check the breakpoint line, and then enter c(ontinue), you can continue to run, as shown in the following figure:

(gdb) c

Insert picture description here
During the debugging process, if you need to view the parameter type, you can use the whatis command. An example is shown in the following figure:

whatis parameter

Insert picture description here
During the debugging process, if you need to view the parameter value, you can print the parameter value and use the p(rint) command. An example is shown in the figure below:

(gdb) p (rint)

Insert picture description here

Commonly used GDB commands

Two, OpenCV under Ubuntu

Download and install OpenCV

First, we need to download an OpenCV installation package, which can be downloaded on the official website or in the Linux system. However, the download will be slower. The blogger downloads it directly to the Windows system, then copies it to the Linux system, and then copies it to Linux The compressed package in is shown below.
Insert picture description here
Then enter the path where the compressed package is located, and decompress the compressed package:

unzip opencv-3.4.1.zip

note: The version may be different!

After decompression, there will be two files in the file, one is the compressed package, the other is the decompressed folder, as shown in the following figure:
Insert picture description here
Enter the opencv-3.4.1 folder:

cd opencv-3.4.1

As shown in the figure below:
Insert picture description here
Install dependent libraries and cmake. If you are reminded that you need apt-get update, you need to enter root privileges first, and then execute the following command:

sudo apt-get install cmake

The execution result is shown in the figure below:
Insert picture description here

Then execute the following command:

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

The execution result is shown in the figure below:
Warm reminder: This process also requires patience.
Insert picture description here

After cmake is installed, create a compilation folder, and then enter the folder for configuration:

mkdir hy_by_dir
cd hy_by_dir
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..

Insert picture description here

Execute the command to start the long compilation process:

sudo make 

Insert picture description here
After a long wait (the blogger waited for about two hours):
Insert picture description here
execute the command:

sudo make install

At this point, the download and installation of OpenCV is completed. Next, you need to configure OpenCV and enter the command:

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

After executing the command, a blank file will appear, and you need to enter in the file at this time:

/usr/local/lib 

After saving, return to the command input interface and execute the command:

sudo ldconfig  
sudo gedit /etc/bash.bashrc  

And add at the end of the file that appears:

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

As shown in the figure below: the
Insert picture description here
black box is the added code.
Save and exit, execute the following command, and update:

source /etc/bash.bashrc  
sudo updatedb

Oye, the configuration is complete! Next, let's try to make special effects for pictures.

Picture effects

First create a folder, and go to this folder to edit a special effect image function:

mkdir hytest
cd hytest
touch hyimage.cpp
nano hyimage.cpp

The content of hyimage.cpp is as follows:

#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("iu.jpg");      //注意对应图像的名称及后缀
        argc == 2? cvLoadImage(argv[1]) : 0;
        
        cvShowImage("Image", image);
        
        
        if (!image) return -1;  center = cvPoint(image->width / 2, image->heigh$
        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("hyimage.png", src);     //生成图像的名称及后缀
    	cvNamedWindow("hyimage",1);
        imshow("hyimage", src);
        cvWaitKey();
        return 0;
}

Execute the command to generate an executable .exe file from the .cpp file (if gcc is unsuccessful, you can replace it with g++ and try):

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

The execution result is shown in the figure below:
Insert picture description here

Copy the image from the Windows system to the Linux system:
Insert picture description here
pay attention to change the name of the image!The image name in the program must be consistent with the image name in the folder.
Run the executable file:

./hyimage

The execution result is shown in the figure below:
Insert picture description here

The left is the original image, and the right is the image after special effects; the red box is the original image file, and the yellow box is the generated image file. The image effects are complete!

note:
① The location of the image must be in the same folder as the location of the .cpp, otherwise compilation errors may occur;
② You can also change IplImage* image = cvLoadImage("iu.jpg"); to absolute path.

Video playback

Still under the folder we created, create a .cpp file with the following content:

#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
    
    
  VideoCapture capture("Clouds.mp4");
  while(1)
  {
    
    
     Mat frame;
     capture >> frame; 
     imshow("读取视频帧",frame);
     waitKey(30);
   }
     system("pause");
     return 0;
}

Add another video to this directory, and you can copy it directly from the Windows system to the Linux system. The played video supports .mp4 and .avi formats:
Insert picture description here

note: The function parameters in the fifth line are the video name and suffix, which are guaranteed to correspond to the video name and suffix in the folder.

If your video file and the created .cpp file are not in the same directory, you need to add an absolute path to the fifth line of function parameters.

Once the video file is added, you can try to see if the video can be played. Double-click the video, if it can be played, no operation is required; if it cannot be played, just download the plug-in according to the system prompts.
At this point, if you compile and run the program directly, the following error will appear:
Insert picture description here

The reason is you do not have your camera settings in Ubuntu system, this time, you need to run Win + R in the Windows system, then execute the statement services.msc:
Insert picture description here
Check this option is active, if not start, then click the Start:
Insert picture description here
The Change the USB compatibility in the virtual machine settings to USB 3.0:
Insert picture description here
Click on the virtual machine to connect the camera to the virtual machine:
Insert picture description here
Warm reminder: If the compatibility change to USB 3.0 is still unsuccessful, try changing to USB 2.0 or USB 1.1 , There will always be one that is compatible.

How can I check whether my camera is enabled? input the commandcheeseIf there is an image display, it means that the camera has been enabled in the virtual machine. An example is shown in the following figure:
Insert picture description here
At this time, you can compile and run the program:

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

The running result is shown in the figure below:
Insert picture description here

Intractable diseases

①If you are required to open a video file on your hard disk for playback, how to modify the VideoCapture capture(0) line of code?
Modify the directory and name and suffix of the image file you store; if it is already in the same folder as .cpp, you only need to add the name and suffix parameters.

②In the while loop, what data structure is Mat? Why is it necessary to add a waitKey delay code and delete it?
Mat is essentially a class composed of two data parts: a matrix header (containing information such as the size of the matrix, the storage method, the address of the matrix storage, etc.) and a pointer to the matrix containing the pixel value (according to The storage method selected uses any dimension to store data).
The first thing about Mat is that you no longer need to manually allocate its size and when you don't need it, you no longer need to manually release it (automatic memory management).
The video can only be played after the waitKey delay code is added; if the delay code is deleted, the video playback will not be observed.
Special: When the parameter of waitKey is 0, that is, waitKey(0), the program will wait for the user to press the button without limitation.

③This code will always run 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. How to improve?
Add a conditional statement in the loop code:
if (!cvGetWindowHandle ("window name"))
{ break; } At this point, you can directly click the "×" sign on the upper left to directly end Cheng Xun's operation.


Video recording and saving

There is also an upgraded version of the code, which can record video and save it to a local folder. The program example is as follows:

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

Press the space bar to record video and pause recording:

Insert picture description here
The recorded video will be stored in this directory: the
Insert picture description here
red box is the recorded video.

Three, summary

In Linux, we can use GDB to debug the program; after learning OpenCV this time, we have a preliminary understanding of it. The ocean of OpenCV is very deep, waiting for us to travel.
Come on, scholar!

Guess you like

Origin blog.csdn.net/guyuewangyue/article/details/109328010