Lets Learn together... Happy Reading

" Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference "-Robert Frost

How to read image file or a complex image file in MATLAB


       Read images that have different file extensions and formats:

  • Reading a grayscale or intensity format image
  • Reading a RGB or color image
  • Reading a complex Image
  • Image Format and Machine Format is important


Reading an intensity format Image:
Let’s consider the image extension to be .bin or.img or .dat etc which we can’t read using the MATLAB function imread. Let’s try to read the file and save it in a matrix and use the image for further processing.
Here’s the short procedure:
1. Open the file in read mode
2. Read the data into a matrix
3. Close the file
4. Display the image

MATLAB code:
%Read intensity format Image
fp = fopen('Vesuvius.dat','r');
Imgsize = [746 3680];
Img = fread(fp,Imgsize,'float32');
fclose(fp);
figure,imagesc(Img);



Download link: Vesuvius.dat
EXPLANATION:
In the above example, in order to read and view the image successfully we need two parameters. They are image size and data type.
Normally, for these types of image files there will be a header or information file which contains details about the image or there will be a metadata inside the image file.

For instance, the header file for the above example may look like:


<image xsize="3680" ysize="746"> <info datatype="float32"> <description>Vesuvius.hdr</description> <filename>Vesuvius.dat</filename> </info> </image>
From this file, we can understand the size of the image will be 3680 x 746 and the data type is ‘float32’


Reading a color image:
The RGB image that I use here is of size 497 x 248 and the format is ‘uint8’.
MATLAB code:
fp=fopen('color_image.img','r');
data=fread(fp,[248 497*3]);
fclose(fp);
RGB=zeros([248 497 3]);
Pt=497;
RGB(:,:,1)=data(:,1:Pt);
RGB(:,:,2)=data(:,Pt+1:2*Pt);
RGB(:,:,3)=data(:,2*Pt+1:end);

RGB=uint8(RGB);
figure,imshow(RGB);


Download link: color_image.img

EXPLANATION:
The file content is read into a matrix of size [248 497*3]. The matrix ‘data’ contains Red component, Green component and the blue component. The file format used here is ‘uint8’.
Now let’s see how the data is stored in the file and how it will be retrieved to view in MATLAB.
Consider an RGB matrix of size 5x5. This means that the total pixels in the file will be 5x5x3.So we need to read the 5x5 pixels of Red component, 5x5 pixels of Green component and 5x5 Blue component. All the components are stored in a single matrix and then it is separated as R,G and B components.

In the above image, I1 represents the Red, Green and Blue components separately. And ‘data’ is the contents stored inside the file. All the 3 components are stored adjacent to each other in the file.
Reading Complex Image:
In a complex image, the real and imaginary part of the pixel will be stored adjacent to each other.
All the coherent systems generate complex data such as Synthetic Aperture Radar images, Ultrasound images etc.
MATLAB code:
%Read complex data
fp=fopen('vesuvius_cmplx.img','r');
full_data=fread(fp,[746*2 3680],'double');
fclose(fp);

Real_data=full_data(1:2:end,:);
Imag_data=full_data(2:2:end,:);
complex_data=complex(Real_data,Imag_data);
figure,imagesc(abs(complex_data));colormap(gray);
Download Link: Vesuvius_cmplx.img
NOTE:
The above example image (View of Mount Vesuvius) is an incoherent image which is captured from the illumination of sun. This image does not contain imaginary part or phase. So I manually added a constant phase just for the purpose of making it complex image.
EXPLANATION:
In general, the first row will be real part and the next row will be imaginary part in the complex data file i.e. Real and Imaginary parts will be alternating in each row. This format may differ based on the method of storing the file.
The matrix full_data contains the real and imaginary parts in alternate rows. The ‘complex_data’ which is the final matrix contains the complex data.


Image Format is important!
The data type of the content stored in the file is important as it may misinterpret the data if not mentioned correctly.
For instance, Intensity format SAR images are usually in the double format ie the maximum pixel value can exceed 255.
Consider a matrix A of type ‘double’ if the matrix is converted into unsigned integer of 8 bit format then the value greater than 255 will be rounded up to 255.

After the Matrix A of data type ‘double’ converted to Matrix B of ‘uint8’, the values such as 300,150000 and 89999 are converted to the highest range limit of uint8 ie 255. And the decimal point, 4.44 is rounded up to 4.
Machine Format also need to be considered!
Based on the platform the machine format changes.


Big Endian format:
MATLAB code:
fp = fopen('Vesuvius.dat','r','b');
Imgsize = [746 3680];
Img = fread(fp,Imgsize,'float32');
fclose(fp);
figure,imagesc(Img);


Little Endian format:
fp = fopen('Vesuvius.dat','r','l');
Imgsize = [746 3680];
Img = fread(fp,Imgsize,'float32');
fclose(fp);
figure,imagesc(Img);
EXPLANATION
If the machine format is mentioned explicitly then the file is read in the mentioned order. For instance, consider a file stored in 'Little endian format' but if it is opened in 'Big endian format' then file will be not be read correct. It is also based on the format the local machine supports.

Example for an Image opened with different machine format: 

like button Like "IMAGE PROCESSING" page

Read words in a file in reverse order


Consider a file that contains the following text,
            Brand New World
The result after reading the words in the reverse order
         World New Brand





Steps to be performed:
1.      Open a file and move the pointer to the end of the file.
2.      Move the pointer to the current-1 position
3.      Read the character and store it in an array.
4.      Move the pointer to the current-2 position and read the character and store it in an array.
5.      If the character is a blank space, then reverse the array. To reverse array use 'fliplr'.
6.      Append the array to a string and initialize the array to zero.
7.      Repeat this procedure till the pointer reaches the beginning of the file.




MATLAB CODE:

%Open a file to read
fp=fopen('rev.txt');

%Move the pointer to the end of the file
fseek(fp,0,'eof');

%Find the position
fsz=ftell(fp);

n=1;
%Move the pointer to the current-1 position
fseek(fp,-1,'cof');

%Read a character
c=fread(fp,1,'*char');

%Store in the matrix
M(1,n)=c;
Words=0;

%Check whether the file pointer has reached the beginning of the file
    while(fseek(fp,-2,'cof')~=-1)
       
        c=fread(fp,1,'*char');
        %When a space is encountered reverse the character array and append
        %it to a string
        if(isspace(c))
              if(Words==0)
                  %Intially, the string is empty.
                  %Append the array in the reverse order with a blank space
                   Words=[fliplr(M) blanks(1)];
              else
                  %Append the reversed character array to the string
                   Words=[Words fliplr(M)];
              end
           n=1;
           M='';
        else
            %The array is updated with the characters until blank space is
            %encountered
           n=n+1;
           M(1,n)=c;
          
        end


    end
   
Words=[Words fliplr(M)];
display(Words);

fclose(fp);








Result:

Words =

World New Brand 





like button Like "IMAGE PROCESSING" page

Read a file in reverse -from end of file to Beginning of the file


Consider a file that contains the following text,
            Brand New World
After reading the file in the reverse order the result will be
             dlroW weN dnarB









MATLAB CODE:

%Open a text file
fp=fopen('rev.txt');
%Move to the End Of the File
fseek(fp,0,'eof');
%Get the position
fsz=ftell(fp);
%Preallocate the character matrix
M=char(zeros([1 fsz]));
n=1;
%Move one position backward
fseek(fp,-1,'cof');
Here ‘cof’ is Current position of the file
%Read the character
c=fread(fp,1,'*char');
Here the ‘fread’ function reads one data in character format
%Store the character in the matrix
M(1,n)=c;
%Check whether the file pointer has reached the beginning of the file
    while(fseek(fp,-2,'cof')~=-1)
        n=n+1;
        c=fread(fp,1,'*char');
        M(1,n)=c;
    end

fclose(fp);


display(M);



Result:

M =

dlroW weN dnarB





like button Like "IMAGE PROCESSING" page
Next Post Home
Google ping Hypersmash.com