C++编程常用代码

计时:

#include
chrono::steady_clock::time_point t1=chrono::steady_clock::now();
//do something
chrono::steady_clock::time_point t2=chrono::steady_clock::now();
chrono::duration time_used=chrono::duration_cast>(t2-t1);

double time0=static_cast(getTickCount());
//do something
time0=((double)getTickCount()-time0)/getTickFrequency();

clock_t start = clock();
//do something
clock_t finish = clock();
double totaltime = (double)(finish - start) / CLOCKS_PER_SEC;

睡眠:

ros::Duration(0.5).sleep(); // sleep for half a second

#include 
sleep(n)//n秒

随机数生成:

DUtils::Random::RandomInt(0,n);//随机生成0~n间的整数

std::random_device rd;
int x = rd() % 100;

int x = std::rand() % 100;
float b = 255 * float(rand()) / RAND_MAX;

RNG rng;
//产生64位整数
int N1 = rng;
//产生[0,1)范围内均匀分布的double类型数据。
double N1d = rng.uniform(0.,1.);
 
//产生符合均值为1,标准差为0.5的高斯分布的随机数
double N1g = 1 + rng.gaussian(0.5);	

高斯噪声生成: 

cv::RNG rng;
double w_sigma=1.0;
rng.gaussian(w_sigma)

常量

M_PI (math.h)
CV_PI (opencv)
DBL_MAX (float.h)(内置宏定义,double最大值)

进度条

printf("\r bar: %m.nf %% \r", value * 100);
fflush(stdout);

 类的智能指针

#include 
// 定义
class Image {
public:
    using Ptr = std::shared_ptr; // 使用别名
}
// 使用
Image::Ptr image_pointer = Image::Ptr(new Image());
Image image;
Image::Ptr image_pointer = std::make_shared(image);

使用智能指针记得初始化:

#include 

pcl::PointCloud::Ptr point_cloud_xyzrgb_ = boost::make_shared>();

注:
typedef boost::shared_ptr > Ptr;

不然会报错:Assertion `px != 0' failed 

 编程习惯:

//用宏定义(不要写死)
#define IMG_WIDTH 640
#define IMG_HIGHT 480 //宏定义换行用'\'

//调试宏
#define DEBUG
#ifdef DEBUG
//do something
#endif

//注释代码块
#if 0
//do something
#endif

//函数入口进行参数检查
assert(条件/表达式);

遵循doxygen注释规范

小数后面加f
2.1(double,8字节)
2.1f(flaot,4字节)

浮点定点化
(float*2^n)>>n

for循环并行处理:
包含OpenMP的头文件:#include
在for循环前面加上一行:#pragma omp parallel for

C/C++编译器内置宏 __DATA__,__TIME__,__FILE__,__LINE__,可直接使用(如:std::cout << __DATA__ << std::endl; )

__DATE__:在源文件中插入当前的编译日期
__TIME__:在源文件中插入当前编译时间
__FILE__:在源文件中插入当前源文件路径及文件名
__LINE__:在源代码中插入当前源代码行号

标准库STL常用:

//数学
std::cos(theta)
std::sin(theta)
std::atan2(y,x);//弧度

//字符串相关
string::c_str    //返回 C 型字符串
std::stoi    //将字符串转化成带符号(Signed)整数
std::stoll    //将字符串转化成带符号整数
std::to_string    //将一个整数或浮点数转化成字符串
std::remove_if    //删除容器中所有满足条件的元素
std::find_if    //找到容器中满足条件的第一个元素的指针

//输出流格式控制
std::cout << std::fixed;    //用一般的方式输出浮点型,例如C++程序在控制台显示大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示
std::cout.precision(2);    //设置精确度为2,即小数点后保留的位数

//排序
std::nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last) //该函数的作用为将迭代器指向的从_First 到 _last 之间的元素进行二分排序,以_Nth 为分界,前面都比 _Nth 小(大),后面都比之大(小);但是两段内并不有序。特别适用于找出前k个最大(最小)的元素。
std::sort() //默认从小到大排序

使用单例模型来进行不同文件间的变量传递:

//a.h文件
//为了避免同一个文件被include多次,C/C++中有两种方式,一种是#ifndef方式,一种是#pragma once方式
#pragma once
#ifndef _A_H_
#define _A_H_

class Singleton 
{
public:
    Singleton(){};
    static Singleton* instance;

    static Singleton* get_instance()
    {
        if (instance == null) 
        {
            instance = new Singleton();
        }
        return instance;
    }

    int b;
    void set_b(int c){b=c;}
    int get_b(){return b;]
}
#endif

//1.cpp
#include "a.h"
Singleton *ptr=Singleton::get_instance();
ptr->set_b(c);

//2.cpp
#include "a.h"
Singleton *ptr=Singleton::get_instance();
int d=ptr->get_b();

boost 分隔字符串:

#include 


string line("test\ttest2\ttest3");
vector strs;
boost::split(strs,line,boost::is_any_of("\t"));

 opencv常用:

Mat1d转换为Mat3b(为了彩色显示)

cv::Mat1d mat1d;
cv::Mat1b mat1b;
mat1d.convertTo(mat1b, CV_8UC1);
cv::Mat3b mat3b;
cv::cvtColor(mat1b, mat3b, CV_GRAY2BGR);
cv::imshow("image of 3 channels", mat3b);

opencv默认用CV_64F(double)类型,为了减少不必要的转换,尽量使用double型

cvRound(5.5);//返回跟参数最接近的整数值(四舍五入)
cvFloor(5.9) 返回不大于参数的最大整数值
cvCeil(5.1);// 返回不小于参数的最小整数值
cv::reduce(_input_mat,_result_mat,1,CV_REDUCE_SUM);//将输入的矩阵按行/列形式进行特定操作
cv::pow(_src_mat,_n,_dst_mat);//将矩阵的每个元素n次方
cv::eigen(_symmetry_mat,_eigenvalues,_eigenvectors);//计算对称矩阵的特征值和特征向量

旋转矩阵近似:

Mat r;//近似旋转矩阵,行列式接近1
Vec3d tmp;
Mat rotation;
Rodrigues(r,tmp);//罗德里格斯公式(旋转矩阵与旋转向量转换)
Rodrigues(tmp,rotation);

 SVD解线性方程:

(a)解齐次线性方程AX=0
Mat w,u,vt;
cv::SVDecomp(A,w,u,vt,cv::SVD::MODIFY_A|cv::SVD::FULL_UV);//u*w*vt*x=0
//FULL_UV表示把U和VT补充成单位正交方阵
x=vt.row(最后一行);//A`A最小特征值对应的特征向量

(b)解非齐次线性方程AX=b
Mat w,u,vt;
cv::SVDecomp(A,w,u,vt,cv::SVD::MODIFY_A|cv::SVD::FULL_UV);//u*w*vt*x=b
Mat w_inv=Mat::diag(w);
for(int i=0;i<3;i++)
{
    w_inv.at(i)=1./w_inv.at(i);
}
x=vt.t()*w_inv*u.t()*b;

Mat类常用: 

初始化
Mat M = (Mat_(3, 4) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0);
double buff[3][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 } };
Mat M(Size(4, 3), CV_64F, buff);
Mat mat,mat2;
void Mat::create(int _rows, int _cols, int _type)
void Mat::create(Size _sz, int _type)
void Mat::create(int ndims, const int* sizes, int type)
mat2 = k * mat; //直接乘以一个系数
mat.t();//转置
mat.inv();//求逆
mat.clone();//拷贝
mat.row(n);//第n行
mat.reshape(0,3);//单通道,3行(9x1->3x3)
mat.type();//CV_32F(float)为5,CV_64F(double)为6
mat.convertTo(mat2,CV_32F);
determinant(mat);//行列式

Mat R=Mat::eye(3,3,CV_32F);
Mat t=Mat::zeros(3,1,CV_32F);
Mat T=Mat::eye(4,4,CV_32F);
R.copyTo(T.rowRange(0,3).colRange(0,3));
t.copyTo(T.rowRange(0,3).col(3));

特征点提取匹配:

//FAST特征提取
Mat img;
vector keypoints;
FAST(img,keypoints,60);
vector points;
for(auto kp:keypoints)
{
    points.push_back(kp.pt);
}

//光流跟踪
vector keypoints1(给定),keypoints2(待求)
vector status;
vector error;
calcOpticalFlowPyrLK(img1,img2,keypoints1,keypoints2,status,error,Size(21,21),3);

//ORB特征提取
Mat img1,img2;
Ptr orb=ORB::create(500);
vector keypoint1,keypoint2;
Mat descriptor1,descriptor2;
orb->detecAndCompute(img1,Mat(),keypoint1,descriptor1);
orb->detecAndCompute(img2,Mat(),keypoint2,descriptor2);

//暴力匹配
BFMatcher matcher;
vector matches;
matcher.match(descriptor1,descriptor2,matches);

//计算单应矩阵
vector vp1,vp2;
Mat H=findHomography(vp1,vp2);
//分解单应矩阵
vector vR,vt,vn;
Mat k=(Mat_(3,3)< first_keypoints,vector second_keypoints,vector status)
{
    if(first_frame.type()==CV_8UC1)
    {
        cvtColor(first_frame,first_frame,CV_GRAY2BGR);
    }
    if(second_frame.type()==CV_8UC1)
    {
        cvtColor(second_frame,second_frame,CV_GRAY2BGR);
    }
    Mat img_show(first_frame.rows,first_frame.cols*2,CV_8UC3);
    first_frame.copyTo(img_show(Rect(0,0,first_frame.rows,first_frame.cols)));
    second_frame.copyTo(img_show(Rect(first_frame.cols,0,second_frame.rows,second_frame.cols)));
    for(int i=0;i

 问题:在visual studio编程时使用fopen等CRT函数,会出现一些警告信息,如下:

warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

解决:在预处理器中添加 _CRT_SECURE_NO_WARNINGS

 

你可能感兴趣的:(alan)