Saturday 13 February 2016

Basics of image Processing with Python - Jupyter Notebook

In [4]:
The iPython Notebook is here on GITHUB


# Due to challenges with Blogger not able to Update all images inline .....

from matplotlib.image import imread
from matplotlib import pyplot as plt
import numpy as np
import pylab

def show_img(img):
 width = img.shape[1]/75.0
 height = img.shape[0]*width/img.shape[1]
 f = plt.figure(figsize=(width, height))
 plt.imshow(img)
 plt.show()
    #    
image = imread("dna.jpeg")
show_img(image)
#
from skimage import data, io, filter
#
image1 = data.coins() # or any NumPy array!
edges = filter.sobel(image1)
io.imshow(edges)
show_img(image1)
show_img(edges)
io.show()
#
C:\Anaconda2\lib\site-packages\skimage\filter\__init__.py:6: skimage_deprecation: The `skimage.filter` module has been renamed to `skimage.filters`.  This placeholder module will be removed in v0.13.
  warn(skimage_deprecation('The `skimage.filter` module has been renamed '
In [1]:
import skimage.io as io
%matplotlib inline
In [3]:
dna = io.imread('dna.jpeg')

io.imshow(dna)
io.show()
In [21]:
import matplotlib.pyplot as plt
import numpy as np

# Create an image (10 x 10 pixels)
rgb_image = np.zeros(shape=(10,10,3),dtype=np.uint8) 

# Here the -uint8 is an Unsigned Integer - 
# it can take vaues bewteen - 0 to 255
# Source - http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html 

rgb_image[:,:,0] = 0 # Set red value for all pixels
rgb_image[:,:,1] = 255 # Set green value for all pixels
rgb_image[:,:,2] = 255  # Set blue value for all pixels

show_images(images=[rgb_image],titles=["Red - 0 , Green - 255, Blue - 255 "])

#
# Create 2nd image (10 x 10 pixels)
rgb_image1 = np.zeros(shape=(10,10,3),dtype=np.uint8) 

rgb_image1[:,:,0] = 255 # Set red value for all pixels
rgb_image1[:,:,1] = 0 # Set green value for all pixels
rgb_image1[:,:,2] = 255  # Set blue value for all pixels

show_images(images=[rgb_image1],titles=["Red - 255 , Green - 0, Blue - 255 "])
#
#
# Create 3rd image (10 x 10 pixels)
rgb_image2 = np.zeros(shape=(10,10,3),dtype=np.uint8) 

rgb_image2[:,:,0] = 255 # Set red value for all pixels
rgb_image2[:,:,1] = 255 # Set green value for all pixels
rgb_image2[:,:,2] = 0   # Set blue value for all pixels

show_images(images=[rgb_image2],titles=["Red - 255 , Green - 255, Blue - 0 "])
#
In [30]:
# Source - http://sharky93.github.io/docs/gallery/auto_examples/plot_brief.html#example-plot-brief-py
#

from skimage import data
from skimage import transform as tf
from skimage.feature import (match_descriptors, corner_peaks, corner_harris,
                             plot_matches, BRIEF)
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

#
# A Recommended YOUTube Video to understand Affine Transform and Non Uniform Scaling of vectors 
# https://www.youtube.com/watch?v=4I2S5Xhf24o
#
img1 = rgb2gray(data.lena())
tform = tf.AffineTransform(scale=(1.2, 1.2), translation=(0, -100))
img2 = tf.warp(img1, tform)
img3 = tf.rotate(img1, 75)

keypoints1 = corner_peaks(corner_harris(img1), min_distance=5)
keypoints2 = corner_peaks(corner_harris(img2), min_distance=5)
keypoints3 = corner_peaks(corner_harris(img3), min_distance=5)

extractor = BRIEF()

extractor.extract(img1, keypoints1)
keypoints1 = keypoints1[extractor.mask]
descriptors1 = extractor.descriptors

extractor.extract(img2, keypoints2)
keypoints2 = keypoints2[extractor.mask]
descriptors2 = extractor.descriptors

extractor.extract(img3, keypoints3)
keypoints3 = keypoints3[extractor.mask]
descriptors3 = extractor.descriptors

matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True)
matches13 = match_descriptors(descriptors1, descriptors3, cross_check=True)

fig, ax = plt.subplots(nrows=2, ncols=1)

plt.gray()

plot_matches(ax[0], img1, img2, keypoints1, keypoints2, matches12)
ax[0].axis('off')

plot_matches(ax[1], img1, img3, keypoints1, keypoints3, matches13)
ax[1].axis('off')

plt.show()
In [31]:
# Edges and corners are two common types of points of interest. An edge is a boundary
# at which pixel intensity rapidly changes, and a corner is an intersection of two edges.
# Some experimentation with Corners of an Image of the earth - the Blue Marble as seen from the Appolo 
# Image taken from Wikepedia . 


import numpy as np
from skimage.feature import corner_harris,corner_peaks
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
import skimage.io as io
from skimage.exposure import equalize_hist

def show_corners(corners,image):
    fig=plt.figure()
    plt.gray()
    plt.imshow(image)
    y_corner,x_corner = zip(*corners)
    plt.plot(x_corner,y_corner,'or')
    plt.xlim(0,image.shape[1])
    plt.ylim(image.shape[0],0)
    fig.set_size_inches(np.array(fig.get_size_inches())*2.5)
    plt.show()


dna1 = io.imread('dna.jpeg')
dna1=equalize_hist(rgb2gray(dna1))
corners = corner_peaks(corner_harris(dna1),min_distance=2)
show_corners(corners,dna1)
In [32]:
# Edges and corners are two common types of points of interest. An edge is a boundary
# at which pixel intensity rapidly changes, and a corner is an intersection of two edges.
# Some experimentation with Corners of an Image of the earth - the Blue Marble as seen from the Appolo 
# Image taken from Wikepedia . 

import numpy as np
from skimage.feature import corner_harris,corner_peaks
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
import skimage.io as io
from skimage.exposure import equalize_hist

def show_corners(corners,image):
    fig=plt.figure()
    plt.gray()
    plt.imshow(image)
    y_corner,x_corner = zip(*corners)
    plt.plot(x_corner,y_corner,'or')
    plt.xlim(0,image.shape[1])
    plt.ylim(image.shape[0],0)
    fig.set_size_inches(np.array(fig.get_size_inches())*2.5)
    plt.show()


earth = io.imread('Earth.jpg')
earth=equalize_hist(rgb2gray(earth))
corners = corner_peaks(corner_harris(earth),min_distance=2)
show_corners(corners,earth)
#
In [36]:
import numpy as np
from matplotlib import pyplot as plt



#
random_image1 = np.random.random([500, 1500])

plt.imshow(random_image1, cmap='gray', interpolation='nearest');
In [39]:
random_image = np.random.random([2000, 500])

plt.imshow(random_image, cmap='gnuplot2_r', interpolation='nearest');
In [41]:
random_image2 = np.random.random([5000, 2000])

plt.imshow(random_image2, cmap='hot_r', interpolation='nearest');
In [42]:
from skimage import data

coins = data.coins()

print(type(coins), coins.dtype, coins.shape)
plt.imshow(coins, cmap='Accent', interpolation='nearest');
(<type 'numpy.ndarray'>, dtype('uint8'), (303L, 384L))
In [44]:
coins = data.coins()

print(type(coins), coins.dtype, coins.shape)
plt.imshow(coins, cmap='winter_r', interpolation='nearest');
(<type 'numpy.ndarray'>, dtype('uint8'), (303L, 384L))
In [45]:
coins = data.coins()

print(type(coins), coins.dtype, coins.shape)
plt.imshow(coins, cmap='viridis_r', interpolation='nearest');
(<type 'numpy.ndarray'>, dtype('uint8'), (303L, 384L))
In [60]:
cat = data.chelsea()
# cat.shape=(301,452,3)
print("Shape:", cat.shape)
print("Values min/max:", cat.min(), cat.max())

plt.imshow(cat, interpolation='nearest');
#
('Shape:', (300L, 451L, 3L))
('Values min/max:', 0, 231)
Out[60]:
<matplotlib.image.AxesImage at 0x18f58400>
In [68]:
cat[10:50, 10:50, :] = [255, 0, 0]  # [red, green, blue]
plt.imshow(cat);
In [67]:
cat[210:250, 210:250, :] = [0, 255, 0]  # [red, green, blue]
plt.imshow(cat);