You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
How to convert an image into a binary stream of data?
23 views (last 30 days)
Show older comments
How to convert an image into a binary stream of data? Is there any Built in function to do that? Thanks in Advance
1 Comment
Jan
on 25 May 2011
Please describe the input ("an image") and the wanted output ("binary stream") exactly: The dimensions and class are necessary to understand your problem.
Accepted Answer
Walter Roberson
on 25 May 2011
No, there is no built in function to do it. That's partly because "binary stream of data" is not well defined: do you mean an array of 0's and 1's, or do you mean an array of the characters '0' and '1' ?
If you are thinking in terms of sending a stream of bits across a serial port or wifi connection or ethernet connection, then you need to be aware that fwrite() to devices does not support the 'bitN' specification that is supported for files. You also need to be aware that none of those three media support raw bit transport, and that it is not easy to find interface devices that allow you to specify the exact stream of bits for any of those three media.
Anyhow, if you have a numeric array X, you can convert it to an equivalent array of 0's and 1's as follows:
reshape((dec2bin(typecast(X(:),'uint8'),8)-'0').',1,[])
This technique as written will not work for arrays of char or objects or structs or cell arrays -- only numeric arrays.
Converting the stream of bits back to an image is left as an exercise to the reader ;-)
34 Comments
Ubaid Ullah
on 25 May 2011
I am working on DVB-S2. For modulation I require the image to be converted in binary stream to transmit. So that's why I need to have a function which can do it.
Thanks for your help
Jan
on 25 May 2011
@Ubaid: What exactly is a "binary stream" in your problem? Actually *all* data are represented as binary streams inside a (usual) computer. So TYPECAST to UINT8 could be enough already. "For modulation" does not contain any details also.
Ubaid Ullah
on 25 May 2011
I was working on random data i.e binary data. But my supervisor advised me to work on image. So I can't change the whole code at that time. 8 days remaining for the submission. please help me.
Jan
on 25 May 2011
It is your turn to avoid wasting of time: As long, as you do not exlain what "image" and "binary stream" exactly mean, valuable answers will be more or less random.
Walter Roberson
on 25 May 2011
Pass the value calculated by the reshape() in as the first argument to your Modulation() function.
I advise, though, that you give more thought to what will be needed to reconstruct the image at the receiver.
Ubaid Ullah
on 25 May 2011
I passed the value by using reshape, but still there is an error.
Undefined variable or function typecast.
Walter Roberson
on 25 May 2011
What MATLAB version are you using? typecast() has been a basic built-in function since MATLAB 7.1, R14SP3 . If you are using an older version than that, we need to know which version in order to construct a suitable answer.
Ubaid Ullah
on 26 May 2011
reshape((dec2bin(typecast(X(:),'uint8'),8)-'0').',1,[])
As you described. I gave the output of this command as an input to modulation()
Mohammad Ali Kawser
on 28 Apr 2020
Walter Roberson, what a wonderful solution!!
The following code works just perfect:
reshape((dec2bin(typecast(X(:),'uint8'),8)-'0').',1,[])
would you please tell how to convert the stream of bits back to an image?
Thanks!
Walter Roberson
on 29 Apr 2020
reshape(typecast(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), 'ORIGINALTYPE'), SIZEOFIMAGE)
The location doing the reconstruction needs to know original datatype of the image, and the original size of the image. For example,
reshape(typecast(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), 'double'), [640 480 3])
Most of the time, ORIGINALTYPE would be uint8, and if it is, then the original construction of the stream simplifies to
stream = reshape((dec2bin(X,8)-'0').',1,[]);
SIZEOFIMAGE = size(X);
and the reconstruction would simplify to
reconstructed = reshape(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), SIZEOFIMAGE);
However if you are transmitting to a remote system, it often would not know the size of the image being transferred, so you have to think of a way to get the size to the remote end. (This is not difficult to do if you are willing to put in size restrictions, but consider for example the possibility that the user might want to send a map that is more than 4 gigapixels on one edge...)
Walter Roberson
on 24 Mar 2021
Edited: Walter Roberson
on 24 Mar 2021
bit_text = reshape((dec2bin(X,8)).',1,[]);
fid = fopen('name_of_file.txt', 'w');
fwrite(fid, bit_text, 'char');
fclose(fid);
Baghdadi Aya
on 8 May 2021
In case of how to convert the stream of bits back to an image
i tried your solution that is :
reshape(typecast(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), 'double'), [640 480 3]);
and by definition the ORIGINALTYPE is : double
and the SIZEOFIMAGE is :683x1000x3
but it show me this error : Error using reshape
Product of known dimensions, 8, not divisible into total number of elements, 1.
any solution please !
Walter Roberson
on 8 May 2021
How did you create stream ? The error message indicates that whatever it is only has a single element.
Baghdadi Aya
on 9 May 2021
image = imread('test imag.jpg');
B = image(:);
binary_sequence = reshape(dec2bin(typecast(B,'uint8'), 8) - '0', 1, []);
fileID = fopen('fichier_binaire3.txt','w');
nbytes =fprintf(fileID,'%5d\n',binary_sequence)
- so the stream is that variable called binary_sequence
Walter Roberson
on 9 May 2021
Avoid naming a variable image because image is the name of an important MATLAB function. And if you were not careful with it, image could accidentally give you back a scalar object that was a graphics object .
Walter Roberson
on 9 May 2021
Using test.png as a variable name is confusing; it may give people the impression that you can work with PNG files directly in MATLAB instead of having to read them in. I do not recommend using test.png as a variable name.
Are you sure that your original image is 683x1000x3 double precision? Unfortunately I cannot demonstrate with that size at the moment; the facility I am using is limiting me to less than 1 gigabyte.
In your real code, you would not imresize(); I needed to do that in order to keep the memory requirements down for demonstration purposes.
test.png = im2double(imresize(imread('flamingos.jpg'),[683 550]));
B = test.png(:);
binary_sequence = reshape((dec2bin(typecast(B,'uint8'), 8) - '0').', 1, []);
stream = binary_sequence;
reconstructed = reshape(typecast(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), 'double'), size(test.png));
image(test.png)
title('original')
image(reconstructed)
title('reconstructed')
Walter Roberson
on 9 May 2021
reshape(typecast(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), 'double'), [640 480 3]);
and the SIZEOFIMAGE is :683x1000x3
I made it clear in my post that the reshape() should be to the size of the image. The 640 x 480 x 3 was just a concrete example, but I specifically showed
SIZEOFIMAGE = size(X);
reconstructed = reshape(uint8(bin2dec(char(reshape(stream,8, [])+'0').')), SIZEOFIMAGE);
Baghdadi Aya
on 10 May 2021
Ok , my fault was i thought that the size(X) ,must be written manually, however it was a MATLAB function
thanks a lot Sir.
Baghdadi Aya
on 21 May 2021
Edited: Baghdadi Aya
on 21 May 2021
Another question please,
what is the sampling frequency used in when we convert the image to binary stream ?
Because what's i know that the stream is a group of samples , so i need to know this information in your trick
Walter Roberson
on 21 May 2021
"Sampling frequency" does not apply in converting an image to a bit stream. If you had a large enough number of gates, it could be done in a single clock cycle if the size of the image was fixed.
Sampling frequency can apply:
- in the case in which you have a continuous signal, and you are extracting readings of the signal at regular intervals; or
- in cases where you are transmitting a discrete data signal and you want to talk about how quickly it is being transmitted. However in such cases it would be more properly a "clock frequency" rather than a "sampling frequency". Unless you were talking about the reception side, in which case it would be back to sampling a continuous signal (radio, light, electrical, whatever)
Baghdadi Aya
on 25 May 2021
in my case I tried to transmit an image from one side to another, through the air interface so normally there must be the notion of sampling frequency ?
Walter Roberson
on 25 May 2021
Suppose you have a 10 Terabyte hard drive full of images. You need to transmit them to your next door neighbor. What is the sampling frequency?
You might know how much capacity you have rented from your fibre or cable internet company, but do you have any idea what the sampling frequency is on the physical connection to the internet? About a year ago my cable internet company literally doubled my rated speed for no price increase... which tells you that either they were rate-limiting me, or else that they had an available encoding that they were not using. For example they might have switched to QAM-128 instead of QAM-64 at the same carrier frequency. Carrier frequency does not tell you transmission rate.
... Now you can transfer the terabytes over the internet to your neighbor... or you can just pick up the hard drive and take it next door. What is the sampling frequency of taking the hard drive next door?
When the images were being created (scanned, rendered, captured from camera, whatever), they are converted to binary on the disk. Is the sampling frequency involved there, at that time? If it takes half a day to render a particularly complex animation frame at 4k resolution, and if it takes 1/3000 of a second to take a 4k resolution photograph, do the resulting images have the same sampling frequency since they are the same size, or do they have different sampling frequency because it took different amounts of time to create them?
I would suggest to you that if you have a complete image for transmission, that the sampling frequency that is relevant is not a property of the image.
Also as I discussed earlier, on the transmission side, you would not typically talk about sampling frequency. You might have carrier frequency, you might have modulation frequency, you might have clock frequency, you might transmit sine, you might transmit square wave... but you do not talk about sampling frequency.
Sampling frequency is the rate at which a receiver measures the signal. Nyquist gives us a lower bound on the sampling frequency needed to detect changes of state reliably. More reliable systems tend to over-sample to validate that the reading was accurate.
Sampling frequency is not the same as data transmission rate. Consider for example frequency modulation. You might be allocated a 100 Mhz wide channel in a 2.4 GHz base frequency, but you need to ask about signal encoding and about how much error correction and detection has been added. Images transmitted back from distant space probes transmitted at relatively low frequencies with lots of error correction. The same image transmitted back from Mars would be transmitted at higher frequency. The sampling rate of the receiver is not a property of the image.
Baghdadi Aya
on 16 Jun 2021
Edited: Baghdadi Aya
on 16 Jun 2021
thanks a lot for your explication,
what about if i want ton transmit a video in a 400 MHZ of bandewidth, recently i tried to convert this vid into many pictures and then i convert every picture to a binary sequence and i had save it in text file,, but i notice a problem that this way is too slow for exemple the conversion of one image takes 6 secondes and the video has 1000 images so the conversion of all the pictures of the video take so much time ,
- So my question here , is there another quick way to convert the video into a binary data ?
- by the way i need this binary data to use it like an input to a turbo encoder(i used a simulink turbo encoder model), so is the turbo encoder model is good for coding a video (in terms of time) else any idea for another encoding a video ?
Thank you in advance .
Walter Roberson
on 17 Jun 2021
It is not recommended to take a binary stream expressed as a vector of bits, and save it to a text file.
It is more efficient to leave the binary stream as bytes (uint8) and save the uint8 as binary.
... In the case of processing a video file (as opposed to the video content only) then the easiest approach is to
fid = fopen('NameOfVideoFile.mp4', 'r');
byte_stream = fread(fid, [1 inf], '*uint8');
fclose(fid)
and now byte_stream is a copy of the file content.
When you save the video as a file, you are limited by the speed of the file system and hard drive, rather than by the speed of transmission. A 5400 rpm hard drive has a maximum write speed of about 100 megabytes per second in theory, but you are more likely to get about 80 megabytes per second. That is already less than the 400 MHz bandwidth that you hope to transmit at, and you would have had to read it back from the file system as well, so you have no realistic hope if you go through that process.
If you have a stream of uint8 and you need to convert it to binary (one bit per entry), then often the most efficient method is table lookup:
lookup_table = de2bin(0:255, 8);
bit_stream = reshape(lookup_table(uint16(byte_stream)+1,:).', 1, []);
The uint16() part is because if you added 1 to a uint8 value that was 255, then the addition would "saturatate" giving you back 255 instead of 256. You are adding 1 because your lowest value is 0 and 0 is not a valid index in MATLAB. (However, if you were working in Simulink you could configure 0 to be a valid index and you would not need to add 1.)
Baghdadi Aya
on 21 Jun 2021
"It is more efficient to leave the binary stream as bytes (uint8) and save the uint8 as binary."
what if i told you that the hardware project can support 400 MO per second, so what advice would you tell me ?
1) what about instead of conversion into a binary_stream , i will convert it into an octal stream, is that can work ?
2) have you any idea, how can i put those pictures of video in a table which can read by picture and save the stream .. means at the end i will get the stream of all the video ?
Walter Roberson
on 22 Jun 2021
what if i told you that the hardware project can support 400 MO per second, so what advice would you tell me ?
If MO is "million operations", then that would mean 400 million instructions per second. That is not enough to create a 400 MHz signal, unless there is some serious hardware parallelism such as an FPGA processing many different things at (literally) the same time.
The minimum unit of data transfer for all systems that MATLAB is supported on, is the 8-bit byte. In order to address individual bits, you need to split the bits out into individual bytes -- or you need to use mathematical instructions to access the bits at-need. For performance, it is far better if your algorithms can work on entire bytes at a time.
Yes, you could use octal mathematically, but extracting three bits at a time is not as efficient as working with 4 bits at a time or 8 bits at a time.
I do not think I understand about the table ? Is the idea that you have a number of different videos to transmit, any of which might be transmitted multiple times (such as a video on demand service), and that rather encoding them "on the fly" that it might be more efficient to encode each one and store the encoded version and then afterwards recall the encoded version? If so, then Yes, that can potentially be effective, but videos tend to be large, and retrieving them from storage might take a while.
Baghdadi Aya
on 22 Jun 2021
Edited: Baghdadi Aya
on 22 Jun 2021
Yes y're right the extracting to 3 bits is not working if i have the length of vector is not divisible on 3 at that time i will face a problem.
- NO i want to transfer one video.
- I will explain to you : so our step is the video, then i divided the video to multiple image then i asked you how can i get a stream of bits for one image ,and you given me a code which i must put the image manually,So i want to use the table to put all the pictures of the video in a table and the code will read from the table and do the conversion, so in your code, haw can i put those pictures in one table for conversion ?
- I don't know if the idea is received to you or not ?
Walter Roberson
on 22 Jun 2021
Why would you need to put in each image manually ?
movfile = 'rhinos.avi';
obj = videoreader(movfile);
TransmissionState = YourFunctionToInitializeTransmissionState();
while(hasFrame(obj))
B = readFrame(obj);
binary_sequence = reshape((dec2bin(typecast(B,'uint8'), 8) - '0').', 1, []);
stream = binary_sequence;
TransmissionState = YourFunctionToTransmit(TransmissionState, stream);
end
YourFunctionToEndTransmission(TransmissionState);
where you would need to write YourFunctionToInitializeTransmissionState() and YourFunctionToTransmit() and YourFunctionToEndTransmission()
The idea of keeping TransmissionState and updating it as you go, is that you might be transmitting by frame but bitstream might not happen to exactly match a full frame so you might want to have some "left over" to be sent with the next set of data. Or you might be wanting to encode sequence identifiers with the frames; or you might be using a block cypher, or so on. YourFunctionToEndTransmission() would be responsible for flushing out any left-over data in the buffers.
One thing that is not shown here is that the remote end will not know what size the images are unless you force a fixed size (with imresize(B)), so you should probably start by transmitting image size information.
Baghdadi Aya
on 16 Nov 2021
Edited: Baghdadi Aya
on 16 Nov 2021
i want to refer from binary sequence to a video sequence, haw can i do that ?
vid = VideoReader('Countdown 5 seconds timer.mp4');%read the video
numberFrames = vid.NumberOfFrames; %read frames in the video
n= numberFrames ;
totBit=0;
for i=1:10:n
image = read(vid,i);%read frames in the video
B = image(:);%convert the binary matrix to vector
%Conversion frames to binary sequence.
binary_sequence = reshape(dec2bin(typecast(B,'uint8'), 8) - '0', 1, []);
totBit=[totBit,binary_sequence];
end
The variable named totBit is a an array corresponding for all the stream of video this stream will pass through a transmit function and received function, in the reception I will got a stream of binary data, that stream I want to reconvert to video, How can I do that ?
More Answers (0)
See Also
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)