【问题标题】:Need help vectorizing a loop in Matlab需要帮助矢量化 Matlab 中的循环
【发布时间】:2019-08-08 18:14:52
【问题描述】:

我的大脑与 C++ 思维紧密相连。需要帮助矢量化以下循环。

此代码试图生成一个 C++ 标头,其中包含一个数组,该数组将失真图像的每个像素位置映射到未失真坐标。

仅供参考 cameraParamsimgIntrinsics 之前已经由 estimateFisheyeParameters 函数和 undistortFisheyeImage 图像生成。

fileID = fopen('undistorted.h', 'w');

fprintf(fileID, '#ifndef UNDISTORTED_H\n#define UNDISTORTED_H\n\n');
fprintf(fileID, 'const float distortionFix[%d][%d][2] = {', mrows, ncols);
for y = 1:mrows
    fprintf(fileID, '{');
    for x = 1:ncols
        undistortedPoint = undistortFisheyePoints([x y], cameraParams.Intrinsics);
        undistortedPoint = undistortedPoint - imgIntrinsics.PrincipalPoint;
        fprintf(fileID, '{%f, %f}', undistortedPoint);
        if x < ncols
            fprintf(fileID, ', ');
        end
    end
    if (y < mrows)
        fprintf(fileID, '},\n');
    end
end
fprintf(fileID, '}};\n\n#endif');

【问题讨论】:

  • 这里为什么需要矢量化?这段代码的执行时间是否比编译生成的头文件要长得多?
  • @CrisLuengo 进入 matlab 思维模式只是一个很好的练习,而且我只是讨厌等待。任务本身确实不是时间敏感的

标签: matlab vectorization


【解决方案1】:

最好的起点是认识到undistortFisheyePoints 可以接受坐标点矩阵,因此使用矩阵输入调用它一次可能比在循环中重复调用它更有效。您只需要创建点矩阵(可以使用repmatrepelem 完成),获取未失真点的矩阵,然后从每一行中减去imgIntrinsics.PrincipalPoint(使用implicit expansionbsxfun ,或explicitly replicating it)。这一切都可以在循环外完成,然后只需要一个循环就可以全部打印出来:

fileID = fopen('undistorted.h', 'w');

fprintf(fileID, '#ifndef UNDISTORTED_H\n#define UNDISTORTED_H\n\n');
fprintf(fileID, 'const float distortionFix[%d][%d][2] = {', mrows, ncols);

points = [repmat((1:ncols).', mrows, 1) repelem((1:mrows).', ncols, 1)];
undistortedPoints = undistortFisheyePoints(points, cameraParams.Intrinsics);
undistortedPoints = bsxfun(@minus, undistortedPoints, imgIntrinsics.PrincipalPoint);

for y = 1:mrows
    fprintf(fileID, '{');
    index = ((y-1)*ncols+1):(y*ncols-1);
    fprintf(fileID, '{%f, %f},', undistortedPoints(index, :).');
    fprintf(fileID, '{%f, %f}', undistortedPoints(y*ncols, :));
    if (y < mrows)
        fprintf(fileID, '},\n');
    end
end
fprintf(fileID, '}};\n\n#endif');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2018-06-21
    • 2021-05-14
    相关资源
    最近更新 更多