Converting image to bits and vice versa

86 views (last 30 days)
Hi all. I am designing convolutional encoder by using Matlab. To see the result clearly, I will use some pictures. I need to convert the picture pixels into binary code and after I encode it, I need to convert these binary codes into pixels and plot it. Can you help me for convertion part?
  1 Comment
Rik
Rik on 20 May 2020
If you are planning to store them in 8 bit bytes you can use the uint8 data type and use the normal image displaying tools.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 May 2020
bits = reshape((dec2bin(typecast(YourImage, 'uint8'), 8) - '0').', 1, []);
orig_class = class(YourImage);
orig_size = size(YourImage);
reconstructed = reshape(typecast(uint8(bin2dec(char(reshape(bits, 8, [])+'0').')), orig_class), orig_size);
In the special case that you are willing to restrict your images to be uint8, you can simplify these steps.
Unless you are willing to restrict yourself to one fixed image size, you need to convey the original image size to the remote end somehow.
  2 Comments
Andy Paulo Ureña
Andy Paulo Ureña on 18 Jan 2022
Hello Walter, can you help me with the error that im having with your code ? I just put the variable that store the image that i want to convert. Thanks
Error using typecast
The first input argument must be a vector.
Error in imageprocessing (line 37)
bits = reshape((dec2bin(typecast(img, 'uint8'), 8) - '0').', 1, []);
Walter Roberson
Walter Roberson on 18 Jan 2022
Edited: Walter Roberson on 19 Jan 2022
YourImage = imread('peppers.png');
imshow(YourImage); title('original');
bits = reshape((dec2bin(typecast(YourImage(:), 'uint8'), 8) - '0').', 1, []);
orig_class = class(YourImage);
orig_size = size(YourImage);
reconstructed = reshape(typecast(uint8(bin2dec(char(reshape(bits, 8, [])+'0').')), orig_class), orig_size);
imshow(reconstructed); title('reconstructed')
max(abs(double(YourImage(:)) - double(reconstructed(:))))
ans = 0

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!