初学opencv时习题解答可能参考过不同博客或网页内容,由于时间长久不记得具体网址。
此处标记“原创”,只是为方便其他初学者,忘各位前辈见谅。
我的平台 VS2010 + opencv2.4.3 , 平台不同,头文件会有一定的区别。
3.1 a 选取一个负的浮点数,取它的绝对值,四舍五入后,取它的极值。
#include<opencv2/opencv.hpp> // opencv头文件
#include<iostream> // C++ 头文件
using namespace std;
void main()
{
float value[6]={ -1.4, -2.5,-3.6, 5.4, 7.5, 9.6};
int data[6]={0};
// 分别显示原始数据、绝对值数据、取整数据
for( int i = 0; i< 6; i ++)
{
cout<< "value["<<i<<"] = "<<value[i];
float aa=abs(value[i]);// abs()求取绝对值
cout<< " value_abs["<<i<<"] = "<<aa;
data[i]=cvRound( aa );// 四舍五入取整,很奇怪我的2.5取整后是2
cout<< " data["<<i<<"] = "<<data[i]<<endl;
}
cout<<endl; // 与下面显示换行,隔开
CvMat mat = cvMat(2,3,CV_32S,data);// 矩阵mat 2*3 32位有符号整形变量
for( int col=0;col<mat.cols;col++)
{
for( int row=0;row<mat.rows;row++)
{
int temp=mat.data.i[col+row*mat.cols];// 按行显示
cout<<temp<<" ";// " " 仅仅是为了显示时 数据分开
}
cout<<endl;
}
double min=0.f; // 最小值
double max=0.f; // 最大值
CvPoint min_loc=cvPoint(0,0);// 最小值位置
CvPoint max_loc=cvPoint(0,0);// 最大值位置
cvMinMaxLoc(&mat,&min,&max,&min_loc,&max_loc);
// 输出最小值 及其位置
cout<<"min="<<min<<" min_loc=cvPoint("<<min_loc.x<<","<<min_loc.y<<")"<<endl;
// 输出最大值 及其位置
cout<<"max="<<max<<" max_loc=cvPoint("<<max_loc.x<<","<<max_loc.y<<")"<<endl;
}
运行结果:
data[6]={1, 2, 4, 5, 8, 10};
mat = { 1, 5,
2, 8
4, 10 } ;
min=1, min_loc = cvPoint( 0 , 0 ); // 最小值0 ,第0行第0列
max=10, max_loc = cvPoint( 2, 1 ); // 最大值10,第2行第1列