How to convert 1D binary data matrix to 2D image matrix?

I have a one-dimensional matrix of size 256X256X8. It has a string of 0 and 1 of the said length. I want to form an 2D Image matrix of size 256x256 from the previous matrix with each eight bits in the original matrix representing an integer in the final matrix. Is there any way to do it?

 Accepted Answer

I think you have to scoot along in chunks of 8 extracting the binary bits, then use bin2dec(), something like (untested)
count = 1;
for index = 1 : 8 : 256*256*8
substring = initialString(index:index+7);
vector1D(count) = bin2dec(substring);
count = count+1;
end
and then you will have a 1D decimal vector of length 256*256.
Then you have to use reshape() to form it into a 2D matrix:
matrix2D = reshape(vector1D, [256, 256]);

4 Comments

This is working but if I use imshow(matrix2D) then only a white image is displayed and this is not what I intented to do.
Initialize:
Vector1D = zeros(256, 256, 'uint8');
and afterwards you will not even need to reshape() the matrix.
Reason being is that if you use imshow() if the class of the array is single or double, it expects the values to be in the range 0-1. If you have floating point values in the range 0-255, almost all of them are > 1 so they show up as pure white. To get around this you either have to pass in a uint8 image, as Walter suggested, or cast it to uint8 upon calling imshow:
imshow(uint8(doubleArray));
or use [] to scale it properly:
imshow(doubleArray, []);
Thnks....I have done the conversion already and now things are perfect....Thnks once again

Sign in to comment.

More Answers (1)

[ii,jj]=find(ones(256,256));
a=randi(2,256,256,8)-1;
b=cell2mat(arrayfun(@(x,y) a(x,y,1:8),ii,jj,'un',0)' );
out=bin2dec(num2str(reshape(b,256*256,8)));
res=zeros(256,256);
res(1:256*256)=out

Categories

Community Treasure Hunt

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

Start Hunting!