Reputation: 159
Say you have an image with 200 pixels. It will be a 10 x 20 x 3 array where the pages are layer of colors (Red, green and blue). How do I convert that, into a 3 (row) x N (columns eg. 2000) so that each row represents the color (row 1 is red, row 2 is green etc.) and the columns represent pixels
I've tried reshaping but I get a 3 by N matrix that fills the rows downwards and not horizontally (so each row is a mixture of colors and not a specific color).
Upvotes: 0
Views: 422
Reputation: 18895
Your idea using reshape
is correct, but as you found out yourself, the order of the array dimensions is important. Luckily, you can manipulate this using permute
. So, in your case, the "color information", i.e. the third dimension, should be set to the first dimension, so that reshape
works as intended.
Let's have look at this code snippet:
% Set up dimensions
rows = 10;
cols = 20;
% Generate artificial image
img = uint8(255 * rand(rows, cols, 3));
% Get color independently for each channel
r = reshape(img(:, :, 1), 1, rows * cols);
g = reshape(img(:, :, 2), 1, rows * cols);
b = reshape(img(:, :, 3), 1, rows * cols);
% Reshape image with previous dimension permuting
img2 = reshape(permute(img, [3 1 2]), 3, rows * cols);
% Compare results
rOK = (sum(r == img2(1, :)) == rows * cols)
gOK = (sum(g == img2(2, :)) == rows * cols)
bOK = (sum(b == img2(3, :)) == rows * cols)
For a simple comparison, I fetched the "color information" separately, cf. the vectors r
, g
, and b
. Then I permuted the original img
as described above, reshaped it to a 3 x N
matrix as desired, and compared each row with r
, g
, and b
.
Hope that helps!
Upvotes: 2