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 use different images and color maps on a same figure in MATLAB

  • Display different images on same figure
  • Display stack of images with same colormap
  • Display Stack of Images with different colormap


Display different images on same figure


Consider two different images. For instance, let us consider the picture of the cathedral in Milan and the logo of image processing blog. 


The image processing logo will be placed on the cathedral image using matlab command ‘imagesc’
MATLAB CODE:
I = imread('duomo.jpg');
L = imread('logo.jpg');
display(size(I));
display(size(L));
figure,imagesc(1,1,I);hold on;
imagesc(3400,1150,imresize(L,[900 900]));
hold off; axis off;


Explanation:
The size of ‘duomo.jpg’ is 2053  x     4320   x         3
i.e 2053 rows and 4320 columns
The size of ‘logo.jpg’ is 328 rows and 328 columns
First the image of the cathedral is displayed using ‘imagesc’ command then on the same figure the logo is placed by mentioning the position.
imagesc(3400,1150,imresize(L,[900 900]));

Here 3920,1650 represents the position to place the logo.
And the logo is resized to 900x900
Since we want to display the images on the same figure, ‘hold on’ command is used.
Display stack of images with single colormap
MATLAB CODE:
I = imread('cameraman.tif');
T = I;
Numimg = 5;
rng = [1,1];
for in=1:numimg 
 
  hold on;
  imagesc(rng(1),rng(2),T);colormap(gray);axis ij;
  rng = round(size(I)/(numimg*2)*in);

  fsz = size(I)-(rng*2);
  if fsz==0
      break;
  else
      T = imresize(T,fsz)+1;
  end   
end

hold off; axis off;


Explanation:
Same image with different size and different starting position is placed on the same figure.
The colormap gray is used for all the images.



Fig. Colormap(jet)


Display Stack of Images with different colormap
MATLAB CODE:
I1 = imread('peppers.png');

I1 = imresize(I1,[400,400]);
I = rgb2gray(I1);

T = I+1;
%Predefined colormaps
Cname = {'hsv(256)','jet(256)','hot(256)','spring(256)','summer(256)','cool(256)','summer(256)','lines(256)'};
RGB = zeros([size(I,1) size(I,2) 3]);
Numimg = 7; %Number of Images to display
rng = [1 1];

for in=1:numimg-1

    %Define the colormap
    map1 = im2uint8(colormap(cname{in}));
    m = map1(:,1);
    RGB(:,:,1) = m(T);
     m = map1(:,2);
    RGB(:,:,2) = m(T);
     m = map1(:,3);
    RGB(:,:,3) = m(T);
   
    RGB = uint8(RGB);
 
hold on;
imagesc(rng(1),rng(2),RGB);axis ij;
rng = round(size(I)/(numimg*2)*in);

fsz = size(I)-(rng*2);
if fsz==0
    break;
else
T = imresize(T,fsz)+1;
clear RGB
end   
end
I2 = imresize(I1,size(T));
imagesc(rng(1),rng(2),I2); %Actual Image
hold off;axis off;


Explanation:
Here same image with different size and different colormap is displayed on the same figure.
To increase or decrease the number of images, first try to resize the image accordingly and then modify the number of images to display.
The above method can also be used for different images and different color maps can be applied to those images on a single figure.



STACK OF IMAGES:




For More Images and code:
Check : Create Stack of Images notes in Facebook
                 
                             or
            Create Stack of Images in Google Collections




like button Like "IMAGE PROCESSING" page

K-means Clustering


       Clustering can be defined as the grouping of data points based on some commonality or similarity between the points.

                                                                              
         One of the simplest methods is K-means clustering. In this method, the number of clusters is initialized and the center of each of the cluster is randomly chosen. The Euclidean distance between each data point and all the center of the clusters is computed and based on the minimum distance each data point is assigned to certain cluster. The new center for the cluster is defined and the Euclidean distance is calculated. This procedure iterates till convergence is reached.
Let’s see how to generate some random data points and some random cluster points


%Generate sample data points and assign random centre for each cluster
%Number of data points
sz=100;
sz1=250;

X = random('unid',sz1,[sz 1]); %Value
Xp = random('unid',sz1,[sz 1]); %Position

%Number of clusters
c=6;
V=random('unid',sz1,[c 1]); %Value
Vp=random('unid',sz1,[c 1]); %Position


figure,plot(Xp,X,'*',Vp,V,'r+');title('Data points and the initial Cluster centers');


Explanation:
100 data points are generated and the number of clusters are assumed to be 6 and 6 random cluster points are generated.

Group the data points:
MATLAB CODE:

%Preallocate the vectors
V1=zeros(size(V));
Vp1=zeros(size(Vp));
flag=1;
while flag==1
%Find the euclidean distance between the data points and all the center of
%the clusters
J=sqrt(abs(repmat(Xp,[1 c])-repmat(Vp,[1 sz])').^2+abs(repmat(X,[1 c])-repmat(V,[1 sz])').^2);

%Find the minimum distance between the data point and the cluster
[mv,Gpos]=min(J,[],2);
CGroup=zeros([sz c]);
colr=colormap(jet(c));
figure(3),
for i = 1:c
    Temp = find(Gpos==i);
    CGroup(1:numel(Temp),i)=Temp;
   
    V1(i,:)=mean(X(Temp));
    Vp1(i,:)=mean(Xp(Temp));
    Pos=ones(numel(Temp)*2,1)*Vp1(i);
    Pos(2:2:end)=Xp(Temp);
    Value=ones(numel(Temp)*2,1)*V1(i);
    Value(2:2:end)=X(Temp);
    %Define the new centre for each cluster
    plot(Pos,Value,'Color',colr(i,:),'LineStyle','-','Marker','o');hold on;
    plot(Vp1(i),V1(i),'k+');
end
hold off;
Diffv=abs(V-V1);
DiffVp=abs(Vp-Vp1);

%Iterate the process till there is no change in the cluster position
if(Diffv < 1)
    flag=0;
else
    V=V1;
    Vp=Vp1;
end
end

figure,plot(Xp,X,'*',Vp,V,'g+');title('Data points and the Final Cluster centers');


Fig. The new position(red circle) of the clusters after the final iteration.

Explanation:


In the above figure, the data points are represented in blue color stars and the cluster centers are represented in red color cross shape.

Let’s consider one particular data point and all the cluster centers.



Data point position X = 13, Y = 20
Cluster 1 position  X = 8,  Y = 19
Cluster 2 position  X = 13, Y = 15
Step 1: Find the Euclidean Distance:
Find the Euclidean distance(D1) between data point and the cluster 1 similarly, find the Euclidean distance(D2) between data point and the cluster 2

Distance D1 = sqrt((13-8).^2+(20-19).^2)) = 5.0990
Distance D2 = sqrt((13-13).^2+(20-15).^2))= 5.0000

Step 2: Find the minimum and assign the data point to a cluster

Now the minimum distance among the two results is for the cluster 2.
So the data point with (X,Y)=(13,20) is assigned to the cluster/group 2.

Step 3: Perform the step 1 and step 2 for all the data points and assign group accordingly.

Step 4: Assign a new position for the clusters based on the clustering done.
       
        Find the average position of the newly assigned data points to a particular cluster and use that average as the new position for the cluster.       

Step 5: Iterate this procedure till the position of the clusters are unchanged.

Number of clusters = 3

 Number of clusters = 6

Number of clusters = 15


like button Like "IMAGE PROCESSING" page

Multilook Technique for speckle reduction




Consider a stack of images  affected by speckle noise of a same scene. 

In order to reduce the speckle, the availability of the stack of images can be utilized to obtain speckle reduced image.
In order to understand the multilook technique, let’s first generate noisy images and then apply speckle reduction.




Generate stack of noisy images:
1.      Read a noise free image
2.      Generate exponential noise with mean 1 and multiply it with the noise free image

3.      Repeat the process of generating exponential noise and multiplying  it with the noise free image to create stack of ‘n’ images

MATLAB code:
%Multilook - Speckle reduction

%Read a noisy free Image
I = imread('cameraman.tif');
I = double(I);
figure,imagesc(I);colormap(gray);title('Original Image');

[m, n] = size(I);
numofimg = 9;
Stack = zeros([m n numofimg]);

for i = 1:numofimg
    %Generate exponential noise
    noise=random('exp',1,m,n);
   
    %Multiply Noise free Image with noise
    Stack(:,:,i)=I.*noise;
   
end

Explanation:

Random noise with exponential distribution is multiplied with the noise free image to generate image affected by speckle.





Fig: Probability Density Function (PDF) of the noise generated for ‘n’ images that follows exponential distribution.

Multilook(ML) Technique:
Multilook image is the average of the stack of images. This technique is used widely in the field of Synthetic Aperture Radar(SAR) to reduce speckle on the same scene but different acquisition periods.
The stack of data is created for the same scene but with different time of acquisition and ML is applied to reduce the speckle considerably since the noise on the single image will be quite high.

MATLAB code:
ML_image = mean(Stack,3);
figure,imagesc(Stack(:,:,1));colormap(gray);title('Single Noisy Image');
figure,imagesc(ML_image);colormap(gray);title('Multilook Image');



Explanation:


For instance, in the above shown image, consider the red dot as the pixel value of the first pixel position of each image in the stack. Add all the pixel values represented in red dot and divide by the number of images in the stack. Similarly, perform the average for the second pixel position (green dot) and so on and so forth for the whole image.

Matlab code ‘mean(Stack,3) ‘ finds the mean of the image in 3rd dimension and the final result is the Multilooked Image with reduced speckle.


Moving Average Filter:
In order to reduce speckle further, a moving average filter can be used.
Moving average filter of window size 3x3 and 5x5 is applied on the multilook image and window of size 3x3 on a single speckled image in order to appreciate the multilook technique performance.

MATLAB code:

box = ones(3)/9;
ML_avg3 = conv2(ML_image,box,'same');
figure,imagesc(ML_avg3);colormap(gray);title('Moving Average - Window 3 x 3');
box = ones(5)/25;
ML_avg5 = conv2(ML_image,box,'same');
figure,imagesc(ML_avg5);colormap(gray);title('Moving Average - Window 5 x 5');
box = ones(3)/9;
avg_flt = conv2(Stack(:,:,1),box,'same');
figure,imagesc(avg_flt);colormap(gray);title('Moving Average - Single Image');







like button Like "IMAGE PROCESSING" page

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
Previous Post Next Post Home
Google ping Hypersmash.com