2016-10-16 114 views
0

我是計算機視覺的初學者。我正在嘗試使用matlab進行旋轉轉換。我的代碼是matlab圖像旋轉代碼

I = imread('Koala.jpg'); 

rows = size(I, 1); 
cols = size(I, 2); 

deg = 45; 
deg = deg * pi/180; 

C = uint8(zeros(size(I))); 

mid = ceil([rows+1 cols+1]/2); 

[x1, x2] = meshgrid(1:rows, 1:cols); 
M = [cos(deg) sin(deg); -sin(deg) cos(deg)]; 

X = bsxfun(@minus, [x1(:) x2(:)], mid) * M; 
X = round(bsxfun(@plus, X, mid)); 

x1 = X(:, 1); 
x2 = X(:, 2); 
x1(x1<1) = 1; 
x2(x2<1) = 1; 
x1(x1>rows) = rows; 
x2(x2>cols) = cols; 
X = [x1(:) x2(:)]; 

m = 1; 
for i=1:rows 
    for j=1:cols 
     C(X(m, 1), X(m, 2), :) = I(i, j, :); 
     m = m + 1; 
    end 
end 

這工作,但在結果有沒有值的許多pixeles。我想,當我做「X2 = X * M」時,轉換時圖像的範圍與源不一樣,丟失的值很多

+0

會[作弊](https://www.mathworks.com/help/images/ref/imrotate.html)會作弊嗎? –

回答

0

如果您有圖像處理工具箱,我只需要使用imrotate爲你做旋轉。

out = imrotate(I, 45); 

否則,我會嘗試向量化您的方法並使用interp2。您可以按指定的角度旋轉所有像素中心,然後在這些旋轉的點處進行採樣。

% Compute the coordinates of all pixel centers 
[x, y] = meshgrid(1:size(I, 2), 1:size(I, 1)); 

% Compute the rotation matrix 
R = [ cos(deg) sin(deg); 
    -sin(deg) cos(deg)]; 

xy = [x(:), y(:)]; 

% Compute the middle point 
mid = mean(xy, 1); 

% Subtract off the middle point 
xy = bsxfun(@minus, xy, mid); 

% Rotate all of these coordinates by the desired angle 
xyrot = xy * R; 

% Reshape the coordinate matrices 
xy = reshape(xy, [size(x), 2]); 
xyrot = reshape(xyrot, [size(x), 2]); 

% Interpolate the image data at the rotated coordinates 
out = interp2(xy(:,:,1), xy(:,:,2), I, xyrot(:,:,1), xyrot(:,:,2));