Clear Filters
Clear Filters

How to show an image from a textfile?

12 views (last 30 days)
I have turned the image using dlmwrite function to a text file.
No I want to turn the textfile to image again, but it doesn't work correctly.
I'm using the following code:
Code to turn an image to text file:
a= imread('ut.jpg');
dlmwrite ( 'FileName23.txt', a);
Code to turn a text file to an image:
a = dlmread('FileName23.txt');
imshow(a);

Accepted Answer

Guillaume
Guillaume on 18 Oct 2018
jpg images are typically colour images. Colour images are stored as 3D arrays in matlab. dlmread and dlmwrite can only read 2D arrays so your serialisation to text loses that third dimension. All three pages are concatenated horizontally. In addition, jpg images are typically of type uint8, these values get cast to double without rescaling when you serialise them.
You can get back your original array by reshaping it back to 3D and casting it back to uint8:
readimage = dlmread('FileName23.txt');
readimage = uint8(reshape(readimage, size(readimage, 1), [], 3));
imshow(readimage);
Note that this applies to 8-bit colour jpg, which is the majority of jpg files. If the original jpg was 16-bit then you'd have to cast to uint16. If the original jpg was greyscale, you don't need the reshape.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!