Reputation: 507
I am working in MATLAB.
I have a an array of M x N and I fill it with 1 or 0 to represent a binary pattern. I have 24 of these "bit planes", so my array is M x N x 24.
I want to convert this array into a 24 bit M x N pixel bitmap.
Attempts like:
test = image(1:256,1:256,1:24);
imwrite(test,'C:\test.bmp','bmp')
Produce errors.
Any help and suggestions would be appreciated.
Upvotes: 3
Views: 785
Reputation: 221534
Let's assume A
is the input M x N x 24
sized array. I am also assuming that those 24 bits
in each of its 3D "slices" have the first one-third elements for the red-channel
, next one-third
for the green-channel
and rest one-third as blue-channel
elements. So, with these assumptions in mind, one efficient approach using the fast matrix multiplication in MATLAB could be this -
%// Parameters
M = 256;
N = 256;
ch = 24;
A = rand(M,N,ch)>0.5; %// random binary input array
%// Create a 3D array with the last dimension as 3 for the 3 channel data (24-bit)
Ar = reshape(A,[],ch/3,3);
%// Concatenate along dim-3 and then reshape to have 8 columns,
%// for the 8-bit information in each of R, G and B channels
Ar1 = reshape(permute(Ar,[1 3 2]),M*N*3,[]);
%// Multiply each bit with corresponding multiplying factor, which would
%// be powers of 2, to create a [0,255] data from the binary data
img = reshape(Ar1*(2.^[7:-1:0]'),M,N,3); %//'
%// Finally convert to UINT8 format and write the image data to disk
imwrite(uint8(img), 'sample.bmp')
Output -
Upvotes: 2
Reputation: 36710
%some example data
I=randi([0,1],256,256,24);
%value of each bit
bitvalue=permute(2.^[23:-1:0],[3,1,2])
%For each pixel, the first bit get's multiplied wih 2^23, the second with 2^22 and so on, finally summarize these values.
sum(bsxfun(@times,I,bitvalue),3);
To understand this code, try debugging it with input I=randi([0,1],1,1,24);
Upvotes: 1