Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Matlab code to test rotation logic of https://github.com/BVLC/caffe/pull/1386
function test_random_rotation
% Test random rotation logic for BVLC PR #1386
% https://github.com/BVLC/caffe/pull/1386
%
% This code is meant to mirror as closely as possible the image rotation code in Caffe's
% data_transformer.cpp
% Author: Daniel Golden
% Date: 2014-10-31
output_dir = pwd;
% Collect the 8 different transformation parameters
mirror_vec = [false true];
rotation_vec = [0 1 2 3];
[rotation_mat, mirror_mat] = ndgrid(rotation_vec, mirror_vec);
img = imread('peppers.png');
img = img(1:384, 1:384, :); % Make square
img = imresize(img, [100 100]); % Make smaller, otherwise this takes too bloody long
img = permute(img, [2, 1, 3]); % Row major order, like Caffe
height = size(img, 2);
width = size(img, 1);
h_off = 0;
w_off = 0;
for transformation_idx = 1:numel(mirror_mat)
output_img = zeros(size(img), 'uint8');
for c = 0:(size(img, 3) - 1)
for h = 0:(height - 1)
for w = 0:(width - 1)
input_idx = (c * height + h_off + h) * width + w_off + w;
h_idx = h;
w_idx = w;
b_mirror = mirror_mat(transformation_idx);
if b_mirror
w_idx = width - 1 - w;
end
rotation_count = rotation_mat(transformation_idx);
if rotation_count == 1
temp = w_idx;
w_idx = height - 1 - h_idx;
h_idx = temp;
elseif rotation_count == 2
w_idx = width - 1 - w_idx;
h_idx = height - 1 - h_idx;
elseif rotation_count == 3
temp = h_idx;
h_idx = width - 1 - w_idx;
w_idx = temp;
end
output_idx = (c * height + h_idx) * width + w_idx;
output_img(output_idx + 1) = img(input_idx + 1); % + 1 because Matlab is 1-indexed vs C++ 0-indexed
end
end
end
output_filename = fullfile(output_dir, sprintf('image_transform_%02d.jpg', transformation_idx));
output_img = permute(output_img, [2, 1, 3]); % Convert back to Matlab's column-major order
imwrite(output_img, output_filename);
fprintf('Wrote %s (%d of %d)\n', output_filename, transformation_idx, numel(mirror_mat));
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment