1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| filename = './test.JPG'; img = double(imread(filename));
theta = 0.67*pi;
T1 = [cos(theta) sin(theta) 0; -sin(theta) cos(theta) 0; 0 0 1]; imgsize = size(img); w = imgsize(2); h = imgsize(1);
bound = [1 1+w 1+w 1; 1 1 1+h 1+h; 1 1 1 1];
boundWarp = T1 * bound;
newW = ceil(max(boundWarp(1,:)) - min(boundWarp(1,:))) + 1; newH = ceil(max(boundWarp(2,:)) - min(boundWarp(2,:))) + 1; vex = [min(boundWarp(1,:)) min(boundWarp(2,:))];
T2 = [1 0 -vex(1)+1;0 1 -vex(2)+1;0 0 1];
T = T2*T1;
imgsize2 = imgsize; imgsize2([1 2]) = [newH newW];
img2 = zeros(imgsize2); img3 = img2;
tic
tempTrans = cell(imgsize2([1 2])); for i = 1:imgsize(1) for j = 1:imgsize(2) coord = T*[j;i;1]; x = coord(1); y = coord(2); s = fix(coord(1)); t = fix(coord(2)); k = [s+1-x x-s t+1-y y-t]; p = img(i,j,:); p = p(:); tempTrans{t, s}(:, end+1) = [p;k(1)*k(3)]; tempTrans{t, s+1}(:, end+1) = [p;k(2)*k(3)]; tempTrans{t+1, s}(:, end+1) = [p;k(1)*k(4)]; tempTrans{t+1, s+1}(:, end+1) = [p;k(2)*k(4)]; end end
for i = 1:imgsize2(1) for j = 1:imgsize2(2) temp = tempTrans{i,j}; len = size(temp,2); if len == 0 continue; end sum_w = sum(temp(end,:)); for k = 1:len img2(i,j,:) = img2(i,j,:) + reshape(temp(end, k)/sum_w * temp(1:end-1,k), 1, 1, 3); end end end fprintf("前向映射耗费的总时间:"); toc
figure; subplot(1,2,1); imshow(uint8(img2)); title("Forward Mapping");
tic for i = 1:imgsize2(1) for j = 1:imgsize2(2) coord = T\[j;i;1]; img3(i, j, :) = backward(img, coord); end end fprintf("后向映射耗费的总时间:"); toc
subplot(1,2,2); imshow(uint8(img3)); title("Backward Mapping");
function pixel_value = backward(srcimg, srccoord) x = srccoord(1); y = srccoord(2); pixel_value = 0; [r, c, ~] = size(srcimg); if x > c || y > r || x < 1 || y < 1 return; end if x == c || y == r pixel_value = srcimg(x, y, :); return; end s = fix(srccoord(1)); t = fix(srccoord(2)); k = [s+1-x x-s t+1-y y-t]; pixel_value = k(1)*k(3)*srcimg(t,s,:) + k(2)*k(3)*srcimg(t, s+1,:) + ... k(1)*k(4)*srcimg(t+1,s,:) + k(2)*k(4)*srcimg(t+1,s+1,:); end
|