1、先验知识
对灰度图像来说,img.step[0]代表图像一行的的长度:img.step[0]=img.cols;
img.step[1]代表图像一个元素的数据大小:img.step[0]=img.channels() ;
img.data: uchar的指针,指向Mat数据矩阵的首地址。
2、验证:通过地址访问元素
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include<vector>
#include<Eigen/Core>
#include <corecrt_math_defines.h>
using namespace std;
using namespace cv;
int main()
{
//生成一个3*4的矩阵
Mat M = Mat::eye(3,4,CV_8UC1);
cout << "M=\n" << M << endl;
//访问第1行第1列的元素
double sample11 = *(M.data+M.step[0]*0+M.step[1]*0);
cout << "(1,1)=" << sample11 << endl;
//访问第2行第2列的元素
double sample22 = *(M.data+M.step[0]*1+M.step[1]*1);
cout << "(2,2)=" << sample22 << endl;
cout << "M.step[0]="<<M.step[0] << endl;
cout << "M.step[1]="<<M.step[1] << endl;
cv::waitKey(0);
return 0;
}
3、隔点采样
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include<vector>
#include<Eigen/Core>
#include <corecrt_math_defines.h>
using namespace std;
using namespace cv;
#include "sift.h";
Mat downSample(Mat src)
{
Mat dst;
if (src.channels() != 1)
return src;
if (src.cols <= 1 || src.rows <= 1)
{
src.copyTo(dst);
return dst;
}
dst.create((int)(src.rows / 2), (int)(src.cols / 2), src.type());
cout << "-- " << dst.rows << " " << dst.cols << " --" << endl;
int m = 0, n = 0;
for (int i = 0; i < src.rows; i += 2, m++)
{
n = 0;
for (int j = 0; j < src.cols; j += 2, n++)
{
//地址=首地址+cols*i+1*j
double sample = *(src.data + src.step[0] * i + src.step[1] * j);
//防止当图像长宽不一致时,长宽为奇数时,m,n越界
if (m < dst.rows && n < dst.cols)
{
*(dst.data + dst.step[0] * m + dst.step[1] * n) = sample;
}
}
}
return dst;
}
int main()
{
double time0 = static_cast<double>(getTickCount());//记录起始时间
Mat img = imread("D:\\VC\\c++\\opencv源码\\opencv源码\\Stereo_Sample\\ImageL1.jpg", IMREAD_GRAYSCALE);
if (img.empty())
{
cout << "读取图像错误!" << endl;
return 0;
}
siftLou k;
Mat dst;
dst = downSample(img);
dst = downSample(dst);
dst = downSample(dst);
namedWindow("dst", WINDOW_FREERATIO);
namedWindow("src", WINDOW_FREERATIO);
imshow("dst", dst);
imshow("src", img);
cout << img.size() << endl;
cout << dst.size() << endl;
cout << "img.step[0]="<<img.step[0] << endl;
cout << "img.step[1]=" << img.step[1] << endl;
cout << "此方法运行时间:" << time0 << "秒" << endl;//输出运行时间
cv::waitKey(0);
return 0;
}