Convert 24 bit 2D array to 8 bit 3D (RGB) array

Hello all,
I am reading in data from a camera sensor, and it is stored as a 32-bit 2D array. Here, the first 8 bits correspond to Red, the next 8 bits to Green, and so on. I want to split this 2D array (of size (a,b)) to a 3D array (a,b,3), where each element in the array is 8-bit long. I am currently doing this as follows:
[r c]= size(img);
IMG = zeros(r,c,3);
for i = 1:r
for j = 1:c
temp = dec2bin(img(i,j),24);
IMG(i,j,1) = bin2dec(fliplr(temp(1:8)));
IMG(i,j,2) = bin2dec(fliplr(temp(9:16)));
IMG(i,j,3) = bin2dec(fliplr(temp(17:24)));
end
end
figure, imshow(IMG(:,:,1))
figure, imshow(IMG(:,:,2))
figure, imshow(IMG(:,:,3))
This takes a very long time to compute (~ 20 minutes) for the large images that I am currently using.
Is there a more efficient way of doing this?
Thanks in advance!

2 Kommentare

Jan
Jan am 27 Mär. 2012
What is the 4th channel?
Oshin
Oshin am 27 Mär. 2012
The 4th channel doesn't have any relevant information. It's all zeros.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Walter Roberson
Walter Roberson am 27 Mär. 2012

1 Stimme

IMGB = reshape( typecast(img, 'uint8'), [4, size(img)]);
Then row 1 will correspond to one of the bands, row 2 to another, etc..
You might need to do a bit of work to figure out which row is which.

2 Kommentare

Jan
Jan am 27 Mär. 2012
If speed matters (does it ever?), James' typecast function is recommended: http://www.mathworks.com/matlabcentral/fileexchange/17476-typecast-and-typecastx-c-mex-functions
Geoff
Geoff am 27 Mär. 2012
Good point. I use MatLab for prototyping speed, not execution speed.

Melden Sie sich an, um zu kommentieren.

Geoff
Geoff am 27 Mär. 2012

0 Stimmen

Try using bitwise operators like you would in C. These handily operate on a matrix, so you can split out your components like so:
[r c]= size(img);
IMG = zeros(r,c,3);
IMG(:,:,1) = uint8(bitand(img, 255))
IMG(:,:,2) = uint8(bitand(bitshift(img,-8), 255));
IMG(:,:,3) = uint8(bitand(bitshift(img,-16), 255));

3 Kommentare

Geoff
Geoff am 27 Mär. 2012
Hmmm I edited this to add the uint8 wrapper, but it might not behave quite right. MatLab's type conversion (say from signed to unsigned) doesn't work the way _I_ would expect.
Jan
Jan am 27 Mär. 2012
I assume that a division is faster than the bit-shifting.
Geoff
Geoff am 27 Mär. 2012
Well, I come from a C background so I just assumed that those functions share some kind of parallel. =) If division in MatLab is faster, that doesn't say much about the bitshift function!

Melden Sie sich an, um zu kommentieren.

Kategorien

Gefragt:

am 27 Mär. 2012

Community Treasure Hunt

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

Start Hunting!

Translated by