2

我正在尝试编写一些代码来在MATLAB中旋转图像,即相当于imrotate。我使用矩阵乘法来执行新图像到输入图像的逆映射。但是,这比明确写出等效方程要花费更长的时间。有没有更好的方法来执行这个乘法?

我更喜欢使用矩阵乘法,因为我可以通过替换转换矩阵将相同的代码用于其他转换,RT.

im1 = imread('file.jpg');
[h, w, p] = size(im1);
theta = -pi/6;
hh = round( h*cos(theta) + w*abs(sin(theta)));
ww = round( w*cos(theta) + h*abs(sin(theta)));

R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
T = [w/2; h/2];
RT = [inv(R) T; 0 0 1];
for z = 1:p
    for x = 1:ww
        for y = 1:hh
            % Using matrix multiplication
            i = zeros(3,1);
            i = RT*[x-ww/2; y-hh/2; 1];

            %Using explicit equations
            %i(1) = ( (x-ww/2)*cos(theta)+(y-hh/2)*sin(theta)+w/2);
            %i(2) = (-(x-ww/2)*sin(theta)+(y-hh/2)*cos(theta)+h/2);

            %% Nearest Neighbour
            i = round(i);
            if i(1)>0 && i(2)>0 && i(1)<=w && i(2)<=h
                im2(y,x,z) = im1(i(2),i(1),z);
            end
        end
    end
end

%Revised code
im1 = imread('file.jpg');
[h, w, p] = size(im1);
theta = (pi)/3;
hh = round(h*abs(cos(theta)) + w*abs(sin(theta)));
ww = round(w*abs(cos(theta)) + h*abs(sin(theta)));
im2 = zeros([hh,ww,p], class(im1));

R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
T = [w/2; h/2];
RT = [inv(R) T; 0 0 1];

x=1:ww;
y=1:hh;

[X, Y] = meshgrid(x,y);
orig_pos = [X(:)' ; Y(:)' ; ones(1,numel(X))];
orig_pos_2 = [X(:)'-(ww/2) ; Y(:)'-(hh/2) ; ones(1,numel(X))];

new_pos = round(RT*orig_pos_2); % Round to nearest neighbour

% Check if new positions fall from map:
valid_pos = new_pos(1,:)>=1 & new_pos(1,:)<=w & new_pos(2,:)>=1 & new_pos(2,:)<=h;

orig_pos = orig_pos(:,valid_pos);
new_pos = new_pos(:,valid_pos);

siz = size(im1);
siz2 = size(im2);

% Expand the 2D indices to include the third dimension.
ind_orig_pos = sub2ind(siz2,orig_pos(2*ones(p,1),:),orig_pos(ones(p,1),:), (1:p)'*ones(1,length(orig_pos)));
ind_new_pos  = sub2ind(siz, new_pos(2*ones(p,1),:), new_pos(ones(p,1),:), (1:p)'*ones(1,length(new_pos)));

im2(ind_orig_pos) = im1(ind_new_pos);
imshow(im2);
4

1 回答 1

1

您应该对 for 循环进行矢量化,这似乎并不难。它会让你收获很多。最棘手的是位置计算并忽略旋转后从图像上掉下来的位置。

解决方案:

x=1:ww
y=1:hh

[X, Y] = meshgrid(x,y);
orig_pos = [X(:)' ; Y(:)' ; ones(1,numel(X))];

new_pos = round(RT*orig_pos); % round to nearest neighbour

% check if new positions fall from map:
valid_pos = new_pos(1,:)>=1 & new_pos(1,:)<=w & new_pos(2,:)>=1 & new_pos(2,:)<=h;

您可以在 for 循环中对结果矩阵进行分配以处理要忽略的位置,或者只是将它们从源矩阵中删除并一次性完成分配:

orig_pos = orig_pos(:,valid_pos);
new_pos = new_pos(:,valid_pos);

siz = size(im1);
im2 = zeros(siz,class(im1));

% expand the 2d indices to include the third dimension
ind_orig_pos = sub2ind(siz,orig_pos(2*ones(siz(3),1),:),orig_pos(ones(siz(3),1),:), (1:siz(3))'*ones(1,N));
ind_new_pos  = sub2ind(siz, new_pos(2*ones(siz(3),1),:), new_pos(ones(siz(3),1),:), (1:siz(3))'*ones(1,N));

im2(ind_orig_pos) = im1(ind_new_pos);

您的代码可能也很慢,因为您没有初始化im2,因此它会根据需要在运行时进行扩展。

作为参考:使用“peppers.png”作为源图像,整个代码块在我的电脑上花费了 0.12 秒,您的代码花费了几分钟......最终结果是一样的。

于 2012-10-10T08:21:48.717 回答