这里没有内建函数。您最终可以使用repeat来模拟Matlab函数meshgrid
,但在这种情况下会变得更慢。
但是,您可以改善几件事情:
- 得到的指针行的开始了内部循环,因为这将是对各行相同。
- 避免创建临时对象来存储值。
- 我想你换了我和j。
看一看这段代码:
Mat2f src(img_height, img_width);
for (int i = 0; i < img_height; ++i) {
Vec2f* ptr = src.ptr<Vec2f>(i);
for (int j = 0; j < img_width; ++j) {
ptr[j][0] = i;
ptr[j][1] = j;
}
}
这个片段是快一点(毫秒时间):
@MarcoFerro: 1.22755
@Miki: 0.818491
测试代码:
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
int img_height = 480;
int img_width = 640;
{
Mat2f src(img_height, img_width);
double tic = double(getTickCount());
for (int i = 0; i< img_height; ++i){
for (int j = 0; j < img_width; ++j){
src.ptr<Point2f>(i)[j] = Point2f(i, j);
}
}
double toc = (double(getTickCount()) - tic) * 1000.0/getTickFrequency();
cout << "@MarcoFerro: \t" << toc << endl;
}
{
Mat2f src(img_height, img_width);
double tic = double(getTickCount());
for (int i = 0; i < img_height; ++i) {
Vec2f* ptr = src.ptr<Vec2f>(i);
for (int j = 0; j < img_width; ++j) {
ptr[j][0] = i;
ptr[j][1] = j;
}
}
double toc = (double(getTickCount()) - tic) * 1000.0/getTickFrequency();
cout << "@Miki: \t\t" << toc << endl;
}
getchar();
return 0;
}
有没有内置函数来做到这一点。最终你可以[重复播放](http://answers.opencv.org/question/11788/is-there-a-meshgrid-function-in-opencv/)。但是,我认为这个简短的代码段不是瓶颈,即使您可以应用一些改进。你有分析过吗?多久时间?典型的图像宽度和高度? – Miki
图片大小为[320x240],但我将在稍后使用[640x480]。它大约需要0.7ms。当然,这不是我的瓶颈,但每一个最终的小加速都是值得赞赏的。 –
好的。张贴了一个答案。你可以试试你的机器上的代码片段并检查执行时间吗?在我的机器上,这个速度要快一点。 – Miki