LINUX C + + syntax query record

Posted by AlexP on Fri, 24 Dec 2021 08:58:54 +0100

What does OpenCV's cvWaitKey( ) function do? - Stack Overflow
Plain simply, cvWaitKey() sleeps for X miliseconds, waiting for any key to be pressed.
int cvWaitKey(int X);
If a key is pressed, this function returns the ASCII code of key. Or returns -1 if no keys were pressed during that time.

VideoCapture()

cv::VideoCapture::VideoCapture	(	const String & 	filename,
int 	apiPreference = CAP_ANY 
)		
explicit
Python:
<VideoCapture object>	=	cv.VideoCapture(		)
<VideoCapture object>	=	cv.VideoCapture(	filename[, apiPreference]	)
<VideoCapture object>	=	cv.VideoCapture(	index[, apiPreference]	)
Opens a video file or a capturing device or an IP video stream for video capturing with API Preference.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
filename	it can be:
name of video file (eg. video.avi)
or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, ...)
or URL of video stream (eg. protocol://host:port/script_name?script_params|auth)
or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend Note that each video stream or IP camera feed has its own URL scheme. Please refer to the documentation of source stream to know the right URL.
cv::VideoCapture::VideoCapture	(	int 	index,
int 	apiPreference = CAP_ANY 
)		
explicit
Python:
<VideoCapture object>	=	cv.VideoCapture(		)
<VideoCapture object>	=	cv.VideoCapture(	filename[, apiPreference]	)
<VideoCapture object>	=	cv.VideoCapture(	index[, apiPreference]	)
Opens a camera for video capturing.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
index	id of the video capturing device to open. To open default camera using default backend just pass 0. (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY)
apiPreference	preferred Capture API backends to use. Can be used to enforce a specific reader implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L.

opencv octave

KeyPoint::angle
In OpenCV docs was mentioned that angle is computed orientation of the keypoint (-1 if not applicable). I can not imagine that what it is about. So Can anyone say me what it means or bring a small example.

KeyPoint::octave
In OpenCV docs was mentioned that octave is octave (pyramid layer) from which the keypoint has been extracted. I can not imagine that what it is about. So Can anyone say me what it means or bring a small example.

CMake how to turn off warnings
At cmakelists Add to TXT_ definitions(-w)

Callable function between glBegin() and glEnd()

Function meaning
glVertex * () set vertex coordinates
glColor * () sets the current color
glIndex * () sets the current color table
glNormal * () set normal coordinates
glCoord * () generate coordinates
glCallList(),glCallLists() execute display list
glTexCoord * () set texture coordinates
glEdgeFlag * () controls boundary drawing
glMaterial * () set material

Type description
GL_POINTS single vertex set
GL_LINES multiple groups of double vertex segments
GL_POLYGON single simple fill convex polygon
GL_ Trainingles groups of independent filled triangles
GL_QUADS groups of independent filled quadrilateral
GL_LINE_STRIP unclosed polyline
GL_LINE_LOOP closed polyline
GL_TRAINGLE_STRIP linetype continuous fill triangle string
GL_TRAINGLE_FAN sector continuous filled triangle string
GL_QUAD_STRIP continuous filling quadrilateral string

Thread synchronization (use of unique_lock)

unique_ Unique in lock indicates exclusive ownership.
unique_lock is exclusive to mutex objects, which is exclusive to mutex locks.
Usage:
(1) Create a new unique_lock object
(2) Pass an std::mutex object to the object as a parameter;
std::mutex mymutex;
unique_lock lock(mymutex);

Therefore, a new object lock is created when locking
unique_lock lock(mymutex);
The object is automatically unlocked at the end of its life cycle.

C++ Vector to Set and Set to Vector

#include<set>
#include<vector>
#include<iostream>
using namespace std;


int main()
{
    vector<int> vec;
    vec = { 1, 2, 3, 4, 8, 9, 3, 2, 1, 0, 4, 8 };
    set<int> st(vec.begin(), vec.end());
    vec.assign(st.begin(), st.end());

    vector<int>::iterator it;
    for (it = vec.begin(); it != vec.end(); it++)
        cout << *it<<endl;
    
    return 0;
}

This example is to remove and sort the duplicate elements in the vector, first convert the vector to set, and then set to vector
Operation results
0 1 2 3 4 8 9

ORB_SLAM2 has been initialized and cannot create a map

use orb_slam2 When running your own data, you can't create a map after initialization. Need to change two bug

first bug
 take src Under folder Initializer.cc 892 that 's ok

if(cosParallax<0.99998){
	vbGood[vMatches12[i].first]=true;
}
Change to
if(cosParallax<0.99998){
	vbGood[vMatches12[i].first]=true;
	nGood++;
}


the second bug
ORBmatcher.cc File line 478
int bin = round(rot*factor);
Change to
int bin = round(rot/(360.0f*factor));

(1) size_t, ssize_t and int
size_t is some C/C + + standards in stddef As defined in H. This type is sufficient to represent the size of an object. size_ The real type of T is related to the operating system.

In 32-bit architecture, it is generally defined as:

typedef unsigned int size_t;

In 64 bit architecture, it is defined as:

typedef unsigned long size_t;
size_t is 4 bytes on 32-bit architecture and 8 bytes on 64 bit architecture. This problem should be paid attention to when compiling on different architectures. Int is 4 bytes in different architectures, which is the same as size_t different; And int is the signed number, size_t is an unsigned number.
(2)ssize_t
ssize_t is a signed integer, equivalent to int on 32-bit machines and long int on 64 bit machines

(3) size_t and ssize_t function
size_t is generally used to indicate a count, such as how many things have been copied. For example, the result type of sizeof operator is size_t. This type is guaranteed to hold the byte size of the largest object established by the implementation. Its meaning is roughly "an unsigned integer type suitable for measuring the number of data items that can be held in memory". Therefore, it is widely used in places such as array subscripts and memory management functions.

And ssize_t this data type is used to represent the size of data blocks that can be read and written It and size_t is similar, but must be signed It means: it means signed size_ Type T.

In orb_ Use your own video in slam2

%YAML:1.0
 
#--------------------------------------------------------------------------------------------
# Camera Parameters. Adjust them!
#--------------------------------------------------------------------------------------------
 
# Camera calibration and distortion parameters (OpenCV) 
Camera.fx: 500.0
Camera.fy: 500.0
Camera.cx: 320.0
Camera.cy: 240.0
 
Camera.k1: 0
Camera.k2: 0
Camera.p1: 0
Camera.p2: 0
Camera.k3: 0
 
# Camera frames per second 
Camera.fps: 30.0
 
# Color order of the images (0: BGR, 1: RGB. It is ignored if images are grayscale)
Camera.RGB: 0
 
#--------------------------------------------------------------------------------------------
# ORB Parameters
#--------------------------------------------------------------------------------------------
 
# ORB Extractor: Number of features per image
ORBextractor.nFeatures: 1000
 
# ORB Extractor: Scale factor between levels in the scale pyramid     
ORBextractor.scaleFactor: 1.2
 
# ORB Extractor: Number of levels in the scale pyramid    
ORBextractor.nLevels: 8
 
# ORB Extractor: Fast threshold
# Image is divided in a grid. At each cell FAST are extracted imposing a minimum response.
# Firstly we impose iniThFAST. If no corners are detected we impose a lower value minThFAST
# You can lower these values if your images have low contrast            
ORBextractor.iniThFAST: 10
ORBextractor.minThFAST: 5
 
#--------------------------------------------------------------------------------------------
# Viewer Parameters
#--------------------------------------------------------------------------------------------
Viewer.KeyFrameSize: 0.05
Viewer.KeyFrameLineWidth: 1
Viewer.GraphLineWidth: 0.9
Viewer.PointSize: 2
Viewer.CameraSize: 0.08
Viewer.CameraLineWidth: 3
Viewer.ViewpointX: 0
Viewer.ViewpointY: -0.7
Viewer.ViewpointZ: -1.8
Viewer.ViewpointF: 500

#include <opencv2/opencv.hpp>
#include "System.h"
#include <string>
#include <chrono>   // for time stamp
#include <iostream>
using namespace std;
// Parameter file and dictionary file
// If the path on your system is different, please modify it
string parameterFile = "./myvideo.yaml";
string vocFile = "./Vocabulary/ORBvoc.txt";
// video file 
string videoFile = "./myvideo.mp4";
int main(int argc, char **argv) {
 // Declare ORB-SLAM2 system
    ORB_SLAM2::System SLAM(vocFile, parameterFile, ORB_SLAM2::System::MONOCULAR, true);
 // Get video image
  cv::VideoCapture cap(videoFile);    // change to 0 if you want to use USB camera.
  // Record system time
  auto start = chrono::system_clock::now();

while (1) {
        cv::Mat frame;
        cap >> frame;   // Read camera data

        if ( frame.data == nullptr )
            continue;
        // rescale because image is too large
        cv::Mat frame_resized;
        cv::resize(frame, frame_resized, cv::Size(640,360));
        auto now = chrono::system_clock::now();
        auto timestamp = chrono::duration_cast<chrono::milliseconds>(now - start);
        SLAM.TrackMonocular(frame_resized, double(timestamp.count())/1000.0);
        cv::waitKey(30);
    }
    return 0;

}

#Generate call MyVideo Mp4 executable
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR})
add_executable(myvideo myvideo.cpp)
target_link_libraries(myvideo ${PROJECT_NAME})

CLion tips

Ctrl + Left arrow fallback
Ctrl + Right arrow forward
ALT + 1 Show and hide project bar
Ctrl + / Add or delete comments
Ctrl + Alt + L formatting code 
Alt + F7 Find Usages
Ctrl + R replace
Ctrl + B Jump between definition and declaration
Ctrl + Shift + Backspace Go back to the last edit

Ctrl + N Find class
Ctrl + O Select the method to override
Ctrl + F12 Quick view of class members
Ctrl + Q Quick view document
Ctrl + P Prompt parameter information
Ctrl + H View inheritance tree
Ctrl + E View recently browsed files
Ctrl + Alt + B View the implementation classes of interfaces and abstract classes

Ctrl + F Search current file note:Press Esc,The search box will disappear
Ctrl + Shift + F Search the entire project or specify a directory note:Press twice in succession Esc,The search box will disappear
Ctrl + Shift + N Find file
Ctrl + F7 Find where a class, variable, function, etc. is used in the text
Shift + Shift global search 
Ctrl + Alt + 7 View where classes, objects and variables are used

Ctrl + Alt + -/+ Expand and collapse the current function and class
Ctrl + Shift + -/+ Expand and collapse all functions and classes

Shift + F6 Rename variable
Alt + insert Add automatic code generation information (insert) set*()/get*()/Constructor equals,hashcode Etc.)
Ctrl + Shift + Space prompt information( new After that, directly type the constructor and provide construction information in the constructor)

emplace_back() and push_ The difference between back

vector in push_back Object, the copy constructor of the object is called.
And in vector When there is not enough space, continue push_back,vector All previous objects will be copied and constructed into a larger space.
In other words, if the object is large, it is best to use it vector Save the pointer to reduce the consumption caused by calling the copy structure,
If vector Save the pointer, then copy the pointer, and the consumption is very small.


c++We often use insert operation pairs in development stl Various containers for operation, such as vector,map,set Wait.
Before introducing R-value reference, transfer constructor and transfer copy operator, it is usually used push_back()Add an R-value element to the container(Temporary object)When,
First, the constructor will be called to construct the temporary object, and then the copy constructor needs to be called to put the temporary object into the container.
The original temporary variable is released. The problem caused by this is the waste of temporary variable application resources. 
After introducing the right value reference and transferring the constructor, push_back()The constructor and transfer constructor are called when the right value,
If you can construct directly during insertion, you only need to construct it once. This is it. c++11 Newly added emplace_back. 
emplace_back Function prototype:
template <class... Args>
  void emplace_back (Args&&... args);
Add an element at the end of the container. This element is constructed in place and does not need to trigger copy construction and transfer construction.
Moreover, the call form is more concise, and the members of the temporary object are initialized directly according to the parameters.

Counting bits set, in parallel

unsigned int v; // count bits set in this (32-bit value)
unsigned int c; // store the total here
static const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};

c = v - ((v >> 1) & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) + c) & B[2];
c = ((c >> S[3]) + c) & B[3];
c = ((c >> S[4]) + c) & B[4];
The B array, expressed as binary, is:
B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111
We can adjust the method for larger integer sizes by continuing with the patterns for the Binary Magic Numbers, B and S. If there are k bits, then we need the arrays S and B to be ceil(lg(k)) elements long, and we must compute the same number of expressions for c as S or B are long. For a 32-bit v, 16 operations are used.
The best method for counting bits in a 32-bit integer v is the following:

v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn't use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0x1010101 and shifting right 24 bits.

A generalization of the best bit counting method to integers of bit-widths upto 128 (parameterized by type T) is this:

v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count
See Ian Ashdown's nice newsgroup post for more information on counting the number of bits set (also known as sideways addition). The best bit counting method was brought to my attention on October 5, 2005 by Andrew Shapira; he found it in pages 187-188 of Software Optimization Guide for AMD Athlon™ 64 and Opteron™ Processors. Charlie Gordon suggested a way to shave off one operation from the purely parallel version on December 14, 2005, and Don Clugston trimmed three more from it on December 30, 2005. I made a typo with Don's suggestion that Eric Cole spotted on January 8, 2006. Eric later suggested the arbitrary bit-width generalization to the best method on November 17, 2006. On April 5, 2007, Al Williams observed that I had a line of dead code at the top of the first method.