Convert pixel values stored in text file to image

55 views (last 30 days)
I have a text file which is a matrix 48*48 pixels (pixel's values are between 0-255).
This is the text file
I want to convert these pixels to a gray-scale image 48*48 and save it to png format.
How can i do that ?

Accepted Answer

Image Analyst
Image Analyst on 14 Apr 2017
Edited: Image Analyst on 14 Apr 2017
Read the data into an array with whatever method works, like importdata() or dlmread() or whatever...
Then just cast to uint8 and save with imwrite.
grayImage = uint8(importdata(filename));
imwrite(grayImage, 'myimage.png');

More Answers (1)

Shashwat Khandelwal
Shashwat Khandelwal on 9 Nov 2020
Edited: Shashwat Khandelwal on 9 Nov 2020
I was also facing this problem. The below code works for me. The values in 'Lena.txt' are between 0-255 and contains 256x256 values. You can set the parameter in the 2nd line accordig to the number of values in your file and the image size that you prefer.
fid = fopen('Lena.txt', 'r');
img = fscanf(fid, '%d', [256, 256]);
img = img/256;
img = transpose(img);
imshow(img)
imwrite(img,'a.png'); //Writes img to 'a.png'
** If the values in the text file are between 0 and 1. Then you can do it with the below code,
fid = fopen('Lenaf.txt', 'r');//File contains values between 0 and 1.
img = fscanf(fid, '%f', [256, 256]);
img = transpose(img);
imshow(img)
imwrite(img,'a.png'); //Writes img to 'a.png'
Hope this helps.

Categories

Find more on Convert Image Type in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!