In [1]:
from skimage import color
from skimage import io
import numpy as np
import matplotlib.pyplot as plt
import cv2
In [2]:
#function to convertrgb to gray
def to_gray(img_rgb):
red = img_rgb[:,:,0]
green = img_rgb[:,:,1]
blue = img_rgb[:,:,2]
gray = 0.298*red + 0.587*green + 0.114*blue
return(gray)
In [3]:
dolphins = plt.imread("dolphins.jpg")
dolphins_gray = to_gray(dolphins)
plt.imshow(dolphins_gray,cmap="gray")
plt.show()
2.2 Apply Transformations¶
In [4]:
# playing around woth classes
class image_transformer:
def __init__(self,img):
# get image parameters
self.img = img
self.h = img.shape[0]
self.w = img.shape[1]
self.dim = (self.w,self.h)
def rotate(self,angle):
#implement
affine_matrix = (np.array([
[np.cos(angle),-np.sin(angle),0],
[np.sin(angle), np.cos(angle),0]]))
return_img = cv2.warpAffine(self.img,affine_matrix,self.dim)
return(return_img)
def scale(self,factor):
factor = float(factor) # to prevent CV error
affine_matrix = np.array([
[factor,0,0],
[0,factor,0]])
return_img = cv2.warpAffine(self.img,affine_matrix,self.dim)
return(return_img)
def translate(self,x,y):
x = float(x)
y = float(y)
affine_matrix = np.array([
[1,0,x],
[0,1,y]])
return_img = cv2.warpAffine(self.img, affine_matrix, self.dim)
return(return_img)
def shear(self,s,x):
s = float(s)
x = float(x)
affine_matrix = np.array([
[s,x,0],
[0,s,0]])
return_img = cv2.warpAffine(self.img, affine_matrix, self.dim)
return(return_img)
img_trans = image_transformer(dolphins)
In [5]:
plt.figure(figsize=(10,8))
plt.subplot(2,2,1)
plt.imshow(img_trans.scale(0.5))
plt.title("Scaled")
plt.subplot(2,2,2)
plt.imshow(img_trans.rotate(0.3))
plt.title("Rotated")
plt.subplot(2,2,3)
plt.imshow(img_trans.translate(50,50))
plt.title("Translated")
plt.subplot(2,2,4)
plt.imshow(img_trans.shear(1,0.5))
plt.title("Sheared (vertical)")
plt.show()
2.3 NN vs. Bilinear vs Bicubic Interpolation¶
In [7]:
# Downsize original to see differences
scale_percent = 20
width_small = int(dolphins.shape[1] * scale_percent / 100)
height_small = int(dolphins.shape[0] * scale_percent / 100)
dim = (width_small, height_small)
img_small = cv2.resize(dolphins,dim)
In [9]:
# upsampling back to original size
img_nn = cv2.resize(img_small, (dolphins.shape[1],dolphins.shape[0]) , interpolation = cv2.INTER_NEAREST)
img_bil = cv2.resize(img_small, (dolphins.shape[1],dolphins.shape[0]), interpolation = cv2.INTER_LINEAR)
img_bic = cv2.resize(img_small, (dolphins.shape[1],dolphins.shape[0]), interpolation = cv2.INTER_CUBIC)
plt.figure(figsize=(14,10))
plt.subplot(2,2,1)
plt.imshow(img_small)
plt.title('Downsampled')
plt.subplot(2,2,2)
plt.imshow(img_nn)
plt.title('Nearest Neighbor')
plt.subplot(2,2,3)
plt.imshow(img_bil)
plt.title('Bilinear')
plt.subplot(2,2,4)
plt.imshow(img_bic)
plt.title('Bicubic')
plt.show()