<gh_stars>0
# -*- coding: utf-8 -*-
"""q2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1c6yYj3E4qMpyuxjy2Y5ruQHzRynvBSNT
"""

# from sklearn.cluster import KMeans
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import cv2
from skimage import io
import random

from google.colab import drive
drive.mount('/content/gdrive')

cd 'gdrive/My Drive/Colab Notebooks'

def calc_distance(X1, X2):
    return(sum((X1 - X2)**2))**0.5

def findClosestCentroids(ic, X):
    assigned_centroid = []
    for i in X:
        distance=[]
        for j in ic:
            distance.append(calc_distance(i, j))
        assigned_centroid.append(np.argmin(distance))
    return assigned_centroid

def calc_centroids(clusters, X):
    new_centroids = []
    new_df = pd.concat([pd.DataFrame(X), pd.DataFrame(clusters, columns=['cluster'])],
                      axis=1)
    for c in set(new_df['cluster']):
        current_cluster = new_df[new_df['cluster'] == c][new_df.columns[:-1]]
        cluster_mean = current_cluster.mean(axis=0)
        new_centroids.append(cluster_mean)
    return new_centroids


def KMeans(data,n_clusters, max_iter=100):
    X = np.array(data)
    init_centroids = random.sample(range(0, len(X)), n_clusters)
    centroids = []
    for i in init_centroids:
        centroids.append(X[i])

    centroids = np.array(centroids)
    for i in range(max_iter):
        get_centroids = findClosestCentroids(centroids, X)
        centroids = calc_centroids(get_centroids, X)
        
        
    return centroids

import cv2
img= cv2.imread('sample_img1.png')
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

img.shape
im = (img).reshape(512*512, 3)
im = np.array(im)

K=[2,4,8,16,32,64]

imgs=[]
for n in K:
    centroids = KMeans(im,n_clusters = n,max_iter=10)

    labels = findClosestCentroids(centroids,im)
    
    

    im_recovered = im.copy()
    for i in range(len(im)):
        im_recovered[i] = centroids[labels[i]]
    im_recovered = im_recovered.reshape(512, 512, 3)
    imgs.append(im_recovered)

    
    # import matplotlib.image as mpimg
    # fig,ax = plt.subplots(1,2)
    # ax[0].imshow(img)
    # ax[1].imshow(im_recovered)

fig=plt.figure(figsize=(800/96, 800/96), dpi=96)
#adding the subplot (small images from Efaces) to it
for i in range(len(K)):
    ax=plt.subplot(3,2,i+1)
    ax.grid(False)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_title('K='+str(K[i]))
    img=imgs[i]
    img2 = np.array(img)
    plt.imshow(img2)
plt.savefig("compressedImages.png")
# -*- coding: utf-8 -*-
"""q2.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1c6yYj3E4qMpyuxjy2Y5ruQHzRynvBSNT
"""

# from sklearn.cluster import KMeans
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import cv2
from skimage import io
import random

from google.colab import drive
drive.mount('/content/gdrive')

cd 'gdrive/My Drive/Colab Notebooks'

def calc_distance(X1, X2):
    return(sum((X1 - X2)**2))**0.5

def findClosestCentroids(ic, X):
    assigned_centroid = []
    for i in X:
        distance=[]
        for j in ic:
            distance.append(calc_distance(i, j))
        assigned_centroid.append(np.argmin(distance))
    return assigned_centroid

def calc_centroids(clusters, X):
    new_centroids = []
    new_df = pd.concat([pd.DataFrame(X), pd.DataFrame(clusters, columns=['cluster'])],
                      axis=1)
    for c in set(new_df['cluster']):
        current_cluster = new_df[new_df['cluster'] == c][new_df.columns[:-1]]
        cluster_mean = current_cluster.mean(axis=0)
        new_centroids.append(cluster_mean)
    return new_centroids


def KMeans(data,n_clusters, max_iter=100):
    X = np.array(data)
    init_centroids = random.sample(range(0, len(X)), n_clusters)
    centroids = []
    for i in init_centroids:
        centroids.append(X[i])

    centroids = np.array(centroids)
    for i in range(max_iter):
        get_centroids = findClosestCentroids(centroids, X)
        centroids = calc_centroids(get_centroids, X)
        
        
    return centroids

import cv2
img= cv2.imread('sample_img1.png')
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

img.shape
im = (img).reshape(512*512, 3)
im = np.array(im)

K=[2,4,8,16,32,64]

imgs=[]
for n in K:
    centroids = KMeans(im,n_clusters = n,max_iter=10)

    labels = findClosestCentroids(centroids,im)
    
    

    im_recovered = im.copy()
    for i in range(len(im)):
        im_recovered[i] = centroids[labels[i]]
    im_recovered = im_recovered.reshape(512, 512, 3)
    imgs.append(im_recovered)

    
    # import matplotlib.image as mpimg
    # fig,ax = plt.subplots(1,2)
    # ax[0].imshow(img)
    # ax[1].imshow(im_recovered)

fig=plt.figure(figsize=(800/96, 800/96), dpi=96)
#adding the subplot (small images from Efaces) to it
for i in range(len(K)):
    ax=plt.subplot(3,2,i+1)
    ax.grid(False)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_title('K='+str(K[i]))
    img=imgs[i]
    img2 = np.array(img)
    plt.imshow(img2)
plt.savefig("compressedImages.png")
# -*- coding: utf-8 -*- q2.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1c6yYj3E4qMpyuxjy2Y5ruQHzRynvBSNT # from sklearn.cluster import KMeans # import matplotlib.image as mpimg # fig,ax = plt.subplots(1,2) # ax[0].imshow(img) # ax[1].imshow(im_recovered) #adding the subplot (small images from Efaces) to it