<jupyter_start><jupyter_text>DLVC 2017 Tutorial 1 : Python for Visual Computing *Reference: Programming Computer Vision with Python by <NAME>*  Exercise 1: Basic Image Handling and Processing Python Image Library (PIL) [http://www.pythonware.com/products/pil/]<jupyter_code>%matplotlib inline
from PIL import Image
import matplotlib.pyplot as plt
import os
import numpy as np

if not os.path.exists('tut01-results'):
    os.makedirs('tut01-results')

#Loading an image
img = Image.open('data/iitkgp.jpg')
plt.imshow(img) # display the image
print('Image size: '+str(img.size)) # image dimensions
#Converting an image to grayscale
img_gray = img.convert('L') 
plt.imshow(np.asarray(img_gray),cmap='gray')

#Saving an image
img_gray.save('tut01-results/iitkgp_gray.png') 
#Cropping an image
box = (250,10,450,250) # top-left and bottom right co-ordinates of the region to be cropped
img_crop = img.crop(box)
plt.imshow(img_crop)
#Resizing an image
img_resz = img.resize((200,200))
plt.figure()
plt.imshow(np.asarray(img))
plt.figure()
plt.imshow(np.asarray(img_resz))
#Rotating an image
img_rot = img_resz.rotate(45) # anti-clockwise rotation
plt.subplot(1,2,1)
plt.imshow(img_resz)
plt.subplot(1,2,2)
plt.imshow(img_rot)
#Read all the images from a folder
import os
    # Function that returns a list containing the names of image files in a folder
def get_imlist(path):
    return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]

img_list = get_imlist('data/images') # list containing filenames
print(img_list)
    # Displaying the images
for fileNum in range(len(img_list)):
    im = Image.open(img_list[fileNum])
    plt.subplot(1,len(img_list),fileNum+1)
    plt.imshow(im)
from matplotlib.pyplot import bar
#Histogram of images
img_hist = img_gray.histogram()
bar(range(256),img_hist)<jupyter_output><empty_output><jupyter_text>For more examples on matplotlib visit https://matplotlib.org/2.0.2/examples/index.html NumPy [doc: http://docs.scipy.org/doc/numpy/]<jupyter_code>import numpy as np
# Converting to numpy array and properties
img_arr = np.array(img)
print img_arr.shape, img_arr.dtype
img_grayarr = np.array(img.convert('L'),'f') # 'f' => floating point
print img_grayarr.shape, img_grayarr.dtype
# Acessing an element in an array
px1 = img_arr[100,100,2]
print('px1: '+ str(px1))

# Accessing multiple elements by slicing
px2 = img_grayarr[100,:] # all the elemts in a row
print('px2: '+ str(px2))

px3 = img_grayarr[100,30:40] # range of elements in a row
print('px3: '+ str(px3))

px4 = img_grayarr[:,-1] # last column
print('px4: '+ str(px4))
import matplotlib.pyplot as plt

# Graylevel transformations
img_grayinv = 255-img_grayarr
plt.figure()
plt.subplot(121)
plt.imshow(img_grayarr,'gray')
plt.subplot(122)
plt.imshow(img_grayinv,'gray')

img_clamp = (100.0/255) * img_grayarr + 100 #clamp to interval 100...200
plt.figure()
plt.imshow(img_clamp)
plt.colorbar()

# Minimum and maximum values
print(img_grayarr.min(),img_grayarr.max())
print(img_clamp.min(),img_clamp.max())

img_clamp_hist,_ = np.histogram(img_clamp, range=(0,255), bins=256)
plt.figure()
bar(range(256),img_clamp_hist)
# Array to image
pil_img = Image.fromarray(np.uint8(img_clamp))
plt.imshow(np.asarray(pil_img),'gray')
# pil_img.show() 
# Histogram equivalization
img_clamp_hist,bins = np.histogram(img_clamp.flatten(),range=(0,255),bins=256)
cdf = img_clamp_hist.cumsum() # cumulative distribution function
cdf = 255 * cdf / cdf[-1] # normalize
# use linear interpolation of cdf to find new pixel values
img_clampeq = np.interp(img_clamp.flatten(),bins[:-1],cdf).reshape(img_grayarr.shape)
img_clampeq_hist,_ = np.histogram(img_clampeq.flatten(),range=(0,255),bins=256)
plt.subplot(2,2,1)
plt.imshow(np.uint8(img_clamp),'gray')
plt.subplot(2,2,2)
plt.imshow(np.uint8(img_clampeq),'gray')
plt.figure()
plt.subplot(2,2,3)
bar(range(256),img_clamp_hist)
plt.subplot(2,2,4)
bar(range(256),img_clampeq_hist)

Image.fromarray(np.uint8(img_clamp)).save('tut01-results/iitkgp_clamp.png') 
Image.fromarray(np.uint8(img_clampeq)).save('tut01-results/iitkgp_clampEq.png')<jupyter_output><empty_output><jupyter_text>Using pickle module for saving data<jupyter_code>import pickle
# Saving data
with open('tut01-results/image_array.pkl','wb') as f:  # 'with' automatically handles opening and closing of files
    pickle.dump(img_grayarr,f)    

# Loading data
with open('tut01-results/image_array.pkl','rb') as f:
    img_ar = pickle.load(f)

plt.imshow(img_ar,'gray')<jupyter_output><empty_output><jupyter_text>SciPy [doc: https://docs.scipy.org/doc/scipy/reference/]<jupyter_code># Blurring images
from scipy.ndimage import filters

img_blur1 = filters.gaussian_filter(img_gray,2) # sigma(sd) = 2
img_blur2 = filters.gaussian_filter(img_gray,5) # sigma = 5
img_blur3 = filters.gaussian_filter(img_gray,10) # sigma = 10
plt.subplot(2,2,1)
plt.imshow(np.array(img_gray),'gray')
plt.subplot(2,2,2)
plt.imshow(img_blur1,'gray')
plt.subplot(2,2,3)
plt.imshow(img_blur2,'gray')
plt.subplot(2,2,4)
plt.imshow(img_blur3,'gray')
# Image gradients

#Sobel derivative filters
imx = np.zeros(img_grayarr.shape) 
filters.sobel(img_grayarr,1,imx) # operates on arrays!
imy = np.zeros(img_grayarr.shape)
filters.sobel(img_grayarr,0,imy)
img_grad = np.sqrt(imx**2+imy**2) # ** ==> squaring

plt.subplot(2,2,1)
plt.imshow(np.array(img_gray),'gray')
plt.subplot(2,2,2)
plt.imshow(imx,'gray')
plt.subplot(2,2,3)
plt.imshow(imy,'gray')
plt.subplot(2,2,4)
plt.imshow(img_grad,'gray')<jupyter_output><empty_output><jupyter_text>Excercise 2: Feature Extraction Using skimgae [doc: http://scikit-image.org/docs/stable/]<jupyter_code>from skimage import feature
# Co-ocurance matrix
coMatFeat = feature.greycomatrix(np.uint8(img_grayarr), [1], [np.pi/4],normed=True,levels=256) 
print(coMatFeat.shape)

# Properties of GLCM
coPropFeat = feature.greycoprops(coMatFeat, prop= 'homogeneity')
print(coPropFeat)


# Histogram of Oriented Gradients
hogFeat = feature.hog(img_grayarr, orientations=4, pixels_per_cell=(50,50),block_norm='L2-Hys')
print(hogFeat.shape)
# Local binary pattern
lbpFeat = feature.local_binary_pattern(img_grayarr, 35, 15)
plt.imshow(lbpFeat,'gray')
print(lbpFeat.shape)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.145436955820703, 'fraction_numerical': 0.03531118993872944, 'mean_word_length': 6.686493184634449, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 24, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '405168', 'license': 'MIT', 'n_tokens_mistral': 2628, 'n_tokens_neox': 2447, 'n_words': 452, 'path': 'Notebooks/1_Python for Visual Computing.ipynb', 'repo_name': 'Sonal10/Deep-Learning-Workbooks', 'size': '6210'}