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

Linear Contrast Enhancement

The function to perform the enhancement

The coefficient ‘a’ performs the contrast enhancement while the coefficient ‘b’ is for adjusting the brightness.
Let’s start with an example,
MATLAB CODE:
%READ THE INPUT IMAGE
I = imread('vesuvius.png');

a = 1;
b = 60;

y =  a*double(I) + b;
y =  uint8(y);

%HISTOGRAM OF THE INPUT AND OUTPUT IMAGE
hist_I=imhist(I);
hist_y=imhist(y);

figure,stem([0:255],hist_I);hold on; stem([0:255],hist_y);legend Original Enhanced
figure,subplot(1,2,1),imshow(I);title('Original Image');
       subplot(1,2,2);imshow(y);title('After LCE Enhacement');



EXPLANATION:
The function ‘y’ will give an output where the values of the pixels in the input image will be increased by 60.



The behavior of the histogram of the output image is not changed. It retains the shape of the input histogram and also the information but it is shifted to the right by 60 pixels.
If pixels are subtracted then the histogram will be shifted to the left side and the image will look darker.
The table below represents the pixel bins from 0 to 255 and the number of pixels for each bin value in the input and output image.



The total number of pixels in the input image with the value zero is 20809 after the enhancement i.e the addition of 60 to the zero value , the total number of pixels in the output image with the value 60 is 20809. While the pixel value ‘60’ in the input image has the total number of occurrence 17004 , the output image will have the same number of pixel occurrence at the pixel value 120.



EXAMPLE 2:
MATLAB CODE:
%READ THE INPUT IMAGE
I = imread('vesuvius.png');

a = 1.58;
b = 0;

y =  a*double(I) + b;
y =  uint8(y);

%HISTOGRAM OF THE INPUT AND OUTPUT IMAGE
hist_I=imhist(I);
hist_y=imhist(y);

figure,stem([0:255],hist_I);hold on; stem([0:255],hist_y);legend Original Enhanced
figure,subplot(1,2,1),imshow(I);title('Original Image');
       subplot(1,2,2);imshow(y);title('After LCE Enhacement');







The histogram of the output image has the same values as of the histogram of the input image but stretched or expanded.  The coefficients ‘a’ and ‘b’ can be modified based on the visual analysis.
The minimum value of the input image:  0
The maximum value of the input image: 161
The mean of the input image:  87.86

The minimum value of the output image:  0
The maximum value of the output image: 254
The mean of the output image: 138.84

The result of the output image indicates that the pixel values are spread between 0 and 255.






The coefficient a = 1.58

The bin number 1 is multiplied with 1.58.

NEW VALUE = 2( rounding off)

So the number of occurrence of pixel value 1 is now the number of occurrence of pixel value 2 (MARKED in GREEN)



Similarly, the bin number 3 is multiplied with 1.58

NEW VALUE = round(4.74) = 5

The number of occurrence of pixel value 3 before enhancement is 14805 after multiplying with 1.58, the value 14805 is moved to the bin 5. (MARKED in RED)



EXAMPLE 3:



When the values are normalized between 0 and 1, it will be multiplied by 255 to get the pixel values between 0 and 255.


MATLAB CODE:
I = imread('vesuvius.png');
I = double(I);
y = 255*((I-min(I(:)))/range(I(:)));

y = uint8(y);
I = uint8(I);
%HISTOGRAM OF THE INPUT AND OUTPUT IMAGE
hist_I=imhist(I);
hist_y=imhist(y);

figure,stem([0:255],hist_I);hold on; stem([0:255],hist_y);legend Original Enhanced
figure,subplot(1,2,1),imshow(I);title('Original Image');
       subplot(1,2,2);imshow(y);title('After LCE Enhacement');


Contrast Enhancement for RGB image
MATLAB CODE:
clear all
clc
close all
%READ THE INPUT IMAGE
I = imread('Landsat5.png');

%PREALLOCATE THE OUTPUT IMAGE MATRIX
Oimg = zeros(size(I));

R = I(:,:,1); %RED COMPONENT
G = I(:,:,2); %GREEN COMPONENT
B = I(:,:,3); %BLUE COMPONENT

R_hist = imhist(R);%HISTOGRAM OF THE RED COMPONENT
G_hist = imhist(G);%HISTOGRAM OF THE GREEN COMPONENT
B_hist = imhist(B);%HISTOGRAM OF THE BLUE COMPONENT

figure,stem([0:255],R_hist,'r');hold on; stem([0:255],G_hist,'g');hold on; stem([0:255],B_hist,'b');legend Red Green Blue;title('Original Image');




min(R(:)),max(R(:)),mean(R(:))
min(G(:)),max(G(:)),mean(G(:))
min(B(:)),max(B(:)),mean(B(:))


MIN VALUE
MAX VALUE
MEAN VALUE
RED COMPONENT
0
108
43.00
GREEN COMPONENT
0
121
53.54
BLUE COMPONENT
0
111
39.63



R = double(R);
G = double(G);
B = double(B);

%NORMALIZE THE PIXEL VALUES BETWEEN 0 AND 255
R = uint8(255*((R-min(R(:)))/range(R(:))));
G = uint8(255*((G-min(G(:)))/range(G(:))));
B = uint8(255*((B-min(B(:)))/range(B(:))));




min(R(:)),max(R(:)),mean(R(:))
min(G(:)),max(G(:)),mean(G(:))
min(B(:)),max(B(:)),mean(B(:))






MIN VALUE
MAX VALUE
MEAN VALUE
RED COMPONENT
0
255
101.55
GREEN COMPONENT
0
255
112.84
BLUE COMPONENT
0
255
91.0471


R_hist = imhist(R);%HISTOGRAM OF THE RED COMPONENT
G_hist = imhist(G);%HISTOGRAM OF THE GREEN COMPONENT
B_hist = imhist(B);%HISTOGRAM OF THE BLUE COMPONENT

figure,stem([0:255],R_hist,'r');hold on; stem([0:255],G_hist,'g');hold on; stem([0:255],B_hist,'b');legend Red Green Blue; title('After Enhancement');






Oimg(:,:,1)=R; %ENHANCED RED COMPONENT
Oimg(:,:,2)=G; %ENHANCED GREEN COMPONENT
Oimg(:,:,3)=B; %ENHANCED BLUE COMPONENT

Oimg = uint8(Oimg); %RGB IMAGE AFTER ENHANCEMENT


figure,subplot(1,2,1),imshow(I);title('Original Image');
       subplot(1,2,2);imshow(Oimg);title('After LCE Enhacement');


PIC: USGS/NASA Landsat



EXPLANATION:
The RGB image is read into a matrix. The Red, Green and Blue channels are normalized between 0 and 255 separately.



Also check 'Balance Contrast Enhancement Technique'
like button Like "IMAGE PROCESSING" page

Part 3: Median Filter - RGB Image

MATLAB CODE:

clear all

%READ THE RGB IMAGE
I = imread('peppers.png');

A = imnoise(I,'Salt & pepper',0.1);
figure,imshow(A);title('IMAGE WITH SALT AND PEPPER NOISE');


%DEFINE THE WINDOW SIZE MXN
M=3;
N=3;

%PAD THE MATRIX WITH ZEROS ON ALL SIDES
modifyA=padarray(A,[floor(M/2),floor(N/2)]);

B = zeros([size(A,1) size(A,2)]);
med_indx = round((M*N)/2); %MEDIAN INDEX
for i = 1:size(modifyA,1)-(M-1)
    for j = 1:size(modifyA,2)-(N-1)
       
       
        temp = modifyA(i:i+(M-1),j:j+(N-1),:);
        %RED,GREEN AND BLUE CHANNELS ARE TRAVERSED SEPARATELY
        for k = 1:3

          tmp = temp(:,:,k);
          B(i,j,k) = median(tmp(:));

        end
      
       
    end
end


%CONVERT THE IMAGE TO UINT8 FORMAT.
B = uint8(B);
figure,imshow(B);
title('IMAGE AFTER MEDIAN FILTERING');



EXPLANATION:
·        The image is read into the matrix I.  
·        Salt and pepper noise is added to the image.  Learn howto add 'salt and pepper noise to an image'.
·        Define the window size MxN example: 3x3, 7x7, 5x3
·        Pad the image with zeros on all sides. This is done to perform the filtering on the border pixels. Learn howto pad with zeros using MATLAB built_in function padarray.
·        Median is the middle point of the series. The index that is obtained by dividing the total number of elements in a window by 2 gives the position.

·        A sliding window of size M x N is used on each channel (Red, Green and Blue) separately and the elements in the window are sorted and the middle element from the sorted array is chosen.
like button Like "IMAGE PROCESSING" page

Part 2: 2D Median Filter With Different Window Size

MATLAB CODE:

clear all

%READ AN IMAGE
I = imread('zebra.jpg');
display(size(I));

%CONVERT RGB IMAGE INTO GRAYSCALE
A = rgb2gray(I);

%ADD SALT AND PEPPER NOISE TO THE GRAYSCALE IMAGE
A = imnoise(A,'Salt & pepper',0.1);

figure,imshow(A);title('IMAGE WITH SALT AND PEPPER NOISE');

%DEFINE THE WINDOW SIZE MXN
M=5;
N=5;

%PAD THE MATRIX WITH ZEROS ON ALL SIDES
modifyA=padarray(A,[floor(M/2),floor(N/2)]);
figure,imshow(uint8(modifyA)); title('PADDED WITH ZEROS');

B = zeros([size(A,1) size(A,2)]);
med_indx = round((M*N)/2); %MEDIAN INDEX

for i=1:size(modifyA,1)-(M-1)
    for j=1:size(modifyA,2)-(N-1)
       
       
        temp=modifyA(i:i+(M-1),j:j+(N-1),:);
        tmp_sort = sort(temp(:));%tmp(:) converts 2D matrix to 1D matrix
        B(i,j) = tmp_sort(med_indx);
      
      
       
    end
end


 %CONVERT THE IMAGE TO UINT8 FORMAT.
B=uint8(B);
figure,imshow(B);
title('IMAGE AFTER MEDIAN FILTERING');

EXPLANATION:
·        The image is read into the matrix A.  
·        The image is color matrix that contains Red, Green and Blue channels so ‘rgb2gray()’ command is used to convert RGB image to grayscale.
·        Salt and pepper noise is added to the image.  Learn how to add 'salt and pepper noise to an image'.
·        Define the window size MxN example: 3x3, 7x7, 5x3
·        Pad the image with zeros on all sides. This is done to perform the filtering on the border pixels. Learn howto pad with zeros using MATLAB built_in function padarray.
·        Median is the middle point of the series. The index that is obtained by dividing the total number of elements in a window by 2 gives the position.
·        A sliding window of size M x N is used and the elements in the window are sorted and the middle element from the sorted array is chosen.





EXPLANATION:

·        The image filtered with 3x3 window still contains salt and pepper noise but the edges are still sharp.
·        The image filtered with 5x5 window  contains less noise compared to 3x3 window filter and edges are smoothed a bit
·        The image filtered with 7x7 window is free of noise but the edges are smoothed to certain extent.
like button Like "IMAGE PROCESSING" page

Read Image using skimage Module

Scikit-image contains image processing algorithms and is available free of cost. It can be accessed at
Let’s use skimage module for the read operation and display the image using matplotlib module.

Python Script:
from skimage import data
from skimage.color import colorconv
import matplotlib.pyplot as plt


img = data.imread('poppies.jpg');
plt.imshow(img);

plt.show();


#RGB to Grayscale Image
GrayC = colorconv.rgb2gray(img);
plt.imshow(GrayC,cmap='gray');
cbar = plt.colorbar();
plt.show();

#RGB to GrayScale Image without using the modules
GrayC1 = 0.30*img[:,:,0]+0.59*img[:,:,1]+0.11*img[:,:,2];
plt.imshow(GrayC1,cmap='gray');
cbar = plt.colorbar();
plt.show();


#Display Red, Green and Blue Channels separately

Red = 1*img;
Red[:,:,1:3]=0
#Red[:,:,1]=0;
#Red[:,:,2]=0;
plt.imshow(Red);
plt.show();


Green = 1*img;
Green[:,:,0]=0;
Green[:,:,2]=0;
plt.imshow(Green);
plt.show();


Blue = 1*img;
Blue[:,:,:-1]=0;
plt.imshow(Blue);
plt.show();

EXPLANATION:

GrayC = colorconv.rgb2gray(img);
The grayscale image values are between 0.0 and 1.0. The normalization of the image is done by dividing each pixel values by 255.  
GrayC1 = 0.30*img[:,:,0]+0.59*img[:,:,1]+0.11*img[:,:,2];
img[:,:,0] denotes the 2D array of rows and columns for the red channel
img[:,:,1] denotes the green channel of 2D array
img[:,:,2] denotes the blue channel of 2D array

Red = 1*img;
The variable ‘Red’ is assigned with the image ‘img’ which has RGB components.
Red[:,:,1:3]=0 indicates that all the rows and columns in the multidimensional array and the Green and blue Channels are assigned with zeros. ‘1:3’ indicates that 1st and the 2nd indices excluding the 3rd index.

Assigning Operation in Python
Python Script:
A = [ 1,2,3,4,5]
B = A
C = 1*A

print('Values in A before modification:',A);
print('Values in B before modification:',B);
print('Values in C before modification:',C);

#Assign Value 10 to the 4th position in the list(Remember the positioning starts from zero)
A[3] = 10

print('Values in A after modification:',A);
print('Values in B after modification:',B);
print('Values in C after modification:',C);

#Print address of the variables
print('Address of A:',hex(id(A)));
print('Address of B:',hex(id(B)));
print('Address of C:',hex(id(C)));


Output:

Values in A before modification: [1, 2, 3, 4, 5]
Values in B before modification: [1, 2, 3, 4, 5]
Values in C before modification: [1, 2, 3, 4, 5]
Values in A after modification: [1, 2, 3, 10, 5]
Values in B after modification: [1, 2, 3, 10, 5]
Values in C after modification: [1, 2, 3, 4, 5]
Address of A: 0xb454f08
Address of B: 0xb454f08
Address of C: 0xb454f88


EXPLANATION:

The memory address of A is assigned to B. So any changes undergone by B will be automatically reflected in A. In C, a small mathematical operation is performed that forces the variable to have different memory address which is unaffected. The addresses of the variables A and B are same while C has different address. 





like button Like "IMAGE PROCESSING" page

Read Image using Python Imaging Library

Python Imaging Library(PIL) is an open source package  for image processing that performs read, write and simple mathematical and logical manipulations on the image. In this post, let’s demonstrate the uses of PIL library in performing various operations on images. For plotting the image alone, matplotlib will be used.

Python script:
from PIL import Image,ImageChops
import matplotlib.pyplot as plt

img = Image.open("poppies.jpg");
plt.imshow(img);

plt.show();



#Grayscale Image
Gimg = img.convert('L');
plt.imshow(Gimg,cmap='gray');
plt.show();


#Display Red channel, Green channel and Blue Channel
r,g,b = img.split()
c1 = ImageChops.constant(r,0);

Red = Image.merge("RGB",(r,c1,c1));
plt.imshow(Red);
plt.show();






Green = Image.merge("RGB",(c1,g,c1));
plt.imshow(Green);
plt.show();


Blue = Image.merge("RGB",(c1,c1,b));
plt.imshow(Blue);
plt.show();



EXPLANATION:

img = Image.open("poppies.jpg");
The Image module from PIL is used to read the image ‘poppies.jpg’ into the variable ‘img’ as RGB image.
Gimg = img.convert('L');
The above syntax converts the RGB image into grayscale.
plt.imshow(Gimg,cmap='gray');
The command mentioned displays the monochromatic image with the colormap ‘gray’.
r,g,b = img.split();
This splits the RGB image ‘img’ and stores the Red component in ‘r’, green component in ‘g’and blue component in ‘b’
Let’s keep the Red channel undisturbed and replace other channels with zeros.
c1 = ImageChops.constant(r,0);
Create an image of same size of ‘img’ filled with zeros.
The above syntax will replace all the values in the image ‘r’ with the constant value ‘0’
Red = Image.merge("RGB",(r,c1,c1));
plt.imshow(Red);
plt.show();
Merge the three components to create RGB image. For red component, image ‘r’ is used and for green and blue component, the zero filled image ‘c1’ is used.
Similarly, the other channels are displayed as RGB components.
Yellow = Image.merge("RGB",(r,g,c1));
plt.imshow(Yellow);
plt.show();
Red and Green channels are used while the blue channel is filled with zeros.


The Variable explorer shows the list of variables used in the python script. The type of the variable is Image and it contains 640 rows by 353 columns.
The Mode ‘RGB’ indicates that the image is color image with Red, Green and Blue components. The Mode ‘L’ indicates that the image is grayscale or monochrome.


Let’s explore the pixel values of the image ‘img’. In the Variable explorer window, right click on the corresponding variable and click Edit.  The pixel values with respect to the position will be displayed in a table format.





NOTE:
Use the help() syntax to learn more about the modules.
EXAMPLE:  help(Image)
This displays all the available functions in the module ‘Image’ from the PIL library

like button Like "IMAGE PROCESSING" page

Image Processing with Python

 Python is a high level programming language which has easy to code syntax and offers packages for wide range of applications including numerical computing and graphics designing.
Anaconda is a python distribution which is freely downloadable. You can download and install the anaconda package in your node from the below mentioned link:




Anaconda includes most of the important packages such as matplotlib, Numpy, Jupyter, Scipy,pandas, scikits-image. You can check all available packages from the anaconda command prompt:
Type :   conda list

These packages will be of great help for plotting figures, mathematical and statistical processing, image processing and machine learning and so on and so forth.


Spyder is an interactive development environment for python. 



You can write your python scripts in the editor and click on the run icon. The result can be viewed on the ipython console.  The variable explorer contains the details /information about the variables initialized and available.


The size of the image is 100 x 200 i.e 100 columns and 200 rows. The image is RGB. i.e it contains Red, Green and Blue component. The positioning starts from 0.
At [0,0] the Red component has the value 254 , Green and Blue component are zero
At [99,0] the Red component is zero , Green component is 255 and the Blue component is zero
At [0,199], all the components are zero
At [99,199], Blue component is 255 , Red and Green components are zero 

Python Script:

import matplotlib.pyplot as plt

img = plt.imread('color.jpg')
plt.imshow(img);
plt.show();
print('Size of the Image:',img.shape);
print('At [0,0] the RGB components are:',img[0,0,:]);
print('At [99,0] the RGB components are:',img[99,0,:]);
print('At [0,199] the RGB components are:',img[0,199,:]);
print('At [99,199] the RGB components are:',img[99,199,:]);

Explanation:

Matplotlib functions are similar to the MATLAB syntax which will be quiet easy for people who are already familiar with MATLAB.
img.shape gives the size of the image. Ie. 100 x 200 x 3

img[0,0,:] indicates the (0,0) position in the image and ‘:’ fetches all the three components from that particular position.

NOTE:
Syntax to clear the console: clear
Syntax to clear the variables: reset





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