您的位置:首页 > 运维架构

opencv 矩阵操作

2014-04-10 23:14 260 查看
Mat img=imread("cat.jpg",0);

/*(1)返回某一行向量 相当于matlab mat(i,:)*/
Mat vrow=img.row(2);

/*(2)相当于matlab的mat(a:b,:),不包括b,到b-1.*/
Mat vrange=img.rowRange(2,3);

//或者使用 Range类:
//【class Range】: Range(a,b) is basically the same as a:b in Matlab ,左闭右开
Mat vrange2=img.rowRange(Range(2,3));

/*(3)转化矩阵数据类型The method converts source pixel values to the target data type
不要改变通道数,就改变数据类型*/
Mat dst;
img.convertTo(dst,CV_32F);//dst的每个元素都是float

/*(4)复制,屡试不爽 ;*/
Mat dst2;
img.copyTo(dst2);

//【at】遍历元素:mat.at<type>(i,j),注意,当mat为三通道时,mat.at<Vec3b>(i,j)[k]
for (int i=0;i<img.rows;i++)
{
for (int j=0;j<img.cols;j++)
{
int value=img.at<uchar>(i,j);
}
}

/*【ptr】遍历元素:比at函数更快。
template<typename _Tp> _Tp* Mat::ptr(int i=0)
返回某一行的指针。之后可以使用 ptr[j]:第i行第j列*/
for (int i=0;i<img.rows;i++)
{
uchar *pval=img.ptr<uchar>(i);
for (int j = 0; j < img.cols; j++)
int value=pval[j];
}

/*【Mat_】遍历元素.当经常对元素操作,并且在编译过程中知道矩阵元素类型时,
可以通过Mat_<_Tp>::operator ()(int y, int x),此操作符和Mat::at<_Tp>(int y, int x)的速度一样
直接用下表操作符(i,j)哦!*/

Mat_<double> M(20,20);
for(int i = 0; i < M.rows; i++)
for(int j = 0; j < M.cols; j++)
M(i,j) = 1./(i+j+1);

//构造矩阵

/*取原矩阵部分区域作为新矩阵。Mat::Mat(const Mat& m, const Range& rowRange, const Range& colRange)
example:实现类似matlab中的mat(a:b,m:n)*/
Mat mat=Mat(img,Range(1,2),Range(3,4));

//通过数组构造matMat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
uchar array[]={1,2,3,4,5,6};
Mat mat2=Mat(3,2,CV_8U,array);

//容器->矩阵
//通过容器构造template<typename T, int n> explicit Mat::Mat(const Vec<T, n>& vec, bool copyData=true)
//这里声明把构造函数声明为显示的explicit,因此不允许通过默认转化,把容器转化为矩阵,这样会导致阅读代码有歧义
//得到的矩阵为列向量
float array2[6]={1,2,3,4,5,6};
vector<float>va(array2,array2+6);
Mat mat3(va);

//矩阵->容器
//行矩阵或者列矩阵可以转化为vector
vector<float> vb=mat3.reshape(1,1);//1 通道数,1行数

/*【把多个矩阵放到一个矩阵上。memcpy】

Mat xP1f(numP, FILTER_SZ, CV_32F), xN1f(numN, FILTER_SZ, CV_32F);
for (int i = 0; i < NUM_TRAIN; i++)	{
vector<Mat> &xP = xTrainP[i], &xN = xTrainN[i];
for (size_t j = 0; j < xP.size(); j++)
memcpy(xP1f.ptr(iP++), xP[j].data, FILTER_SZ*sizeof(float));
for (size_t j = 0; j < xN.size(); j++)
memcpy(xN1f.ptr(iN++), xN[j].data, FILTER_SZ*sizeof(float));
}*/

//【数据不多时采用】
/*typedef Vec<uchar, 2> Vec2b;
typedef Vec<uchar, 3> Vec3b;
typedef Vec<uchar, 4> Vec4b;

typedef Vec<short, 2> Vec2s;
typedef Vec<short, 3> Vec3s;
typedef Vec<short, 4> Vec4s;

typedef Vec<int, 2> Vec2i;
typedef Vec<int, 3> Vec3i;
typedef Vec<int, 4> Vec4i;

typedef Vec<float, 2> Vec2f;
typedef Vec<float, 3> Vec3f;
typedef Vec<float, 4> Vec4f;
typedef Vec<float, 6> Vec6f;

typedef Vec<double, 2> Vec2d;
typedef Vec<double, 3> Vec3d;
typedef Vec<double, 4> Vec4d;
typedef Vec<double, 6> Vec6d;
使用[]操作符进行元素的操作*/

/*ps:vector 操作:
使用pushback可以不用事先resize.
使用[]下标操作符要事先resize,否则越界。
resverse事先告诉编译器vector需要多少的内存(capasity)。*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: