需要帮助在 Matlab 中矢量化循环

Need help vectorizing a loop in Matlab

我的大脑天生就是 C++ 思维模式。需要帮助矢量化以下循环。

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

仅供参考 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');

最好的起点是认识到 undistortFisheyePoints can accept a matrix of coordinate points, so calling it once with a matrix input will likely be more efficient than calling it repeatedly in a loop. You would just have to create the point matrix (which can be done using repmat and repelem), get your matrix of undistorted points, then subtract imgIntrinsics.PrincipalPoint from each row (either by using implicit expansion, bsxfun, or 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');