# Improve Speed to Convert an RGB Image Stored as a Linear Array to a Matrix

4 visualizaciones (últimos 30 días)
Sonoma Rich el 6 de Abr. de 2011
I have an RGB image stored as a vector 921,000 bytes long (640x480x3 uint8) in a sequence as follows:
[B(1,1) G(1,1) R(1,1) B(1,2) G(1,2) R(1,2) B(1,3) G(1,3) R(1,3) ... B(480,640) G(480,640) R(480,640)]
I used a FOR loop to convert it to a matrix as shown below. I would like to speed-up this conversion. Any suggestions?
r = zeros(480,640,'uint8');
g = r;
b = r;
a = my_image_obj.Bytes.uint8;
for y = 1:480
f = 1920*(y-1);
for x = 1:640
s = 3*x-2+f;
b(y,x) = a(s);
g(y,x) = a(s+1);
r(y,x) = a(s+2);
end
end
my_image(:,:,1) = r;
my_image(:,:,2) = g;
my_image(:,:,3) = b;
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Respuestas (2)

Tim Zaman el 6 de Abr. de 2011
to reshape to [B(11) G(11) B(11) ; ... ] so that it is now [3x307000] the first column is now B, second G, third B.
Now, use reshape again to reshape to a square size. (almost) never use for loops!
##### 2 comentariosMostrar NingunoOcultar Ninguno
Sonoma Rich el 6 de Abr. de 2011
I tried the following and it works. Any further suggestions to improve it?
a = my_image_obj.Bytes.uint8;
b = reshape(a,3,length(a)/3);
my_image(:,:,1) = reshape(b(3,:),640,480)';
my_image(:,:,2) = reshape(b(2,:),640,480)';
my_image(:,:,3) = reshape(b(1,:),640,480)';
Jan el 8 de Abr. de 2011
Improvement: Pre-allocation, e.g. by starting with my_image(:, :, 3).

Iniciar sesión para comentar.

Sean de Wolski el 6 de Abr. de 2011
A one-liner
my_image = reshape(fliplr(reshape(a,3,numel(a)/3).'),[640 480 3])
##### 3 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
Sean de Wolski el 8 de Abr. de 2011
my_image = permute(my_image,[2 1 3]);
Sean de Wolski el 8 de Abr. de 2011
or
doc imrotate
doc rot90

Iniciar sesión para comentar.

### Categorías

Más información sobre Get Started with Image Processing Toolbox en Help Center y File Exchange.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by