C++ vector和Mat 转换

1. vector及数组

1.1 一维vector

//定义一维vector
vector<float> channel_data; 

//向vector中添加元素,用push_back
for (int j = 0; j < numMic; j++){
    channel_data.push_back(*m_dataMic);
}

//求vector长度
int Len_data = vector.size(); 

//索引数据
channel_data[i]

//求vector中的最大值及位置
auto maxPosition = max_element(channel_data.begin(), channel_data.end());
cout << *maxPosition << " at the postion of " << maxPosition - channel_data.begin

1.2 二维vector

vector<vector<float>> power;  //定义二维vector
vector<float> add_power;  //定义一维vector
//std::vector> power;  //定义二维vector
//std::vector add_power;  //定义一维vector
for (int i=0; i<Len1; i++)
{
    //给1维vector添加元素
    for (int j=0; j<Len2; j++)
    {
        add_power.push_back(amplite_planes1[j]);
    }
    power.push_back(add_power) //给2维vector添加元素
}

int n = power.size();       //Len1的长度
int m = power[0].size();   //Len2的长度

//求2维vector中的最大值及位置
float max_power = 0.0;
int pos[2];
for (int p = 0; p < power.size(); p++)//求2维Vector的最大值
{
	auto maxPosition = max_element(power[p].begin(), power[p].end());
	if (max_power <= *maxPosition){
		max_power = *maxPosition;
                pos[0] = p;//第几行
                pos[1] = maxPosition-power[p].begin();//第几列
	}
}

1.3 数组

//一维数据维度计算
int num=0;
num=sizeof(Array)/sizeof(Array[0]);

//二维数组维度计算
int Array[5][5];
int numberOfRow,numberOfCol,len;
numberOfCol=sizeof(Array[0])/sizeof(int);
len=sizeof(Array)/sizeof(int);
numberOfRow=len/numberOfCol;

2. 类型转换

1维vector转数组

vector<float> channel_data3; //定义一维vector;假定channel_data3已添加了元素
float *singleChannel_data = new float[Len];
for (int i = 0; i < Len; i++)
{
    singleChannel_data[i] = channel_data3[i];
}

1维Mat转1维数组

//转8位一维数组
uchar *array = new unsigned char[mat.rows*mat.cols];
if (mat.isContinuous())
    array = mat.data;

2维vector转Mat

std::vector<std::vector<float>> power;  //定义二维vector

// 二维Vector转换为Mat类型的mat_power
// Create a new, _empty_ cv::Mat with the row size of OrigSamples
cv::Mat mat_power(0, power[0].size(), cv::DataType<float>::type);
for (unsigned int i = 0; i < power.size(); ++i)
{
	// Make a temporary cv::Mat row and add to NewSamples _without_ data copy
	cv::Mat Sample(1, power[0].size(), cv::DataType<float>::type, power[i].data());
	mat_power.push_back(Sample);
}

//查看二维Mat元素
power.ptr<float>(0),32 //查看第0行0-31列的32个元素

2维Mat转Vector

//初始化二维vector维度
vector<vector<float>> R_vec;
R_vec.resize(num_row);//行
for (int c = 0; c < R_vec.size(); c++){
	R_vec[c].resize(num_col);//列
}
//R为2维Mat
for (int x = 0; x < R.rows; x++) {
	for (int y = 0; y < R.cols; y++) {
		//R_vec[x][y] = R.at(x, y);
		R_vec[x][y] = R.ptr<float>(x)[y];
		//std::cout << boxPts.at(x, y) << std::endl;
	}
}

resize参考:vector中resize() 用法排坑

3. 其他

数据运算

#include
float E_cd0 = pow(4, 0.5); //对4开根号
float E_cd0  = sqrt(4) //对4开根号
float E_cd1 = pow(4, 2); //对4平方
float E_cd0 = exp(4); /

生成(min max]范围内的随机数

std::srand(std::time(nullptr));
rand_array = min + rand() % (max - min);

参考: C++实用基础语法总结1(适合小白)

你可能感兴趣的:(C++,opencv,c++,开发语言,算法)