<jupyter_start><jupyter_text><jupyter_code>import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.image as img 
import sys
# from scipy.io import loadmat 
from scipy import misc 
import imageio

def read_image(): 
	# loading as 3d matrix 
	img = imageio.imread('/content/drive/MyDrive/Colab Notebooks/ImageCompressionKmeans/Kroko.jpg') 
	img = img / 255
	return img 

def initialize_means(img, clusters): 
	
	# reshaping it or flattening it into a 2d matrix 
	points = np.reshape(img, (img.shape[0] * img.shape[1], 
											img.shape[2]))
	m, n = points.shape 
  
	# means is the array of assumed means or centroids. 
	means = np.zeros((clusters, n)) 

	# random initialization of means. 
	for i in range(clusters): 
		rand1 = int(np.random.random(1)*10) 
		rand2 = int(np.random.random(1)*8) 
		means[i, 0] = points[rand1, 0] 
		means[i, 1] = points[rand2, 1]
		means[i, 2] = points[rand2, 2]
	#print(means)
	return points, means 


# Function to measure the euclidean 
def distance(x1, y1, x2, y2): 
	dist = np.square(x1 - x2) + np.square(y1 - y2) 
	dist = np.sqrt(dist) 
	return dist 


def k_means(points, means, clusters): 
	iterations = 10 # the number of iterations 
	m, n = points.shape 
	# these are the index values that 
	# correspond to the cluster to 
	# which each pixel belongs to. 
	index = np.zeros(m) 

	# k-means algorithm. 
	while(iterations > 0): 
		for j in range(len(points)): 
			if 100*j/len(points) % 5 < 10/len(points): print('Current Iteration ',iterations,' is at ',100*j/len(points),'%')
   
			# initialize minimum value to a large value 
			minv = 1000
			temp = None
			
			for k in range(clusters): 
				
				x1 = points[j, 0] 
				y1 = points[j, 1] 
				x2 = means[k, 0] 
				y2 = means[k, 1] 
				
				if(distance(x1, y1, x2, y2) < minv):		 
					minv = distance(x1, y1, x2, y2) 
					temp = k 
					index[j] = k 
		
		for k in range(clusters): 
			
			sumx = 0
			sumy = 0
			count = 0
			
			for j in range(len(points)): 
				
				if(index[j] == k): 
					sumx += points[j, 0] 
					sumy += points[j, 1] 
					count += 1
			
			if(count == 0): 
				count = 1	
			
			means[k, 0] = float(sumx / count) 
			means[k, 1] = float(sumy / count)	 
			
		iterations -= 1

	return means, index 


def compress_image(means, index, img): 

	# recovering the compressed image by 
	# assigning each pixel to its corresponding centroid. 
	centroid = np.array(means) 
	recovered = centroid[index.astype(int), :] 
	
	# getting back the 3d matrix (row, col, rgb(3)) 
	recovered = np.reshape(recovered, (img.shape[0], img.shape[1], 
													img.shape[2])) 

	# plotting the compressed image. 
	plt.imshow(recovered) 
	plt.show() 

	# saving the compressed image. 
#	misc.imsave('compressed_' + str(clusters) +
#						'_colors.png', recovered) 



img = read_image() 

clusters = 16 

points, means = initialize_means(img, clusters) 
means, index = k_means(points, means, clusters) 
compress_image(means, index, img)<jupyter_output>Current Iteration  10  is at  0.0 %
Current Iteration  10  is at  5.0 %
Current Iteration  10  is at  10.0 %
Current Iteration  10  is at  15.0 %
Current Iteration  10  is at  20.0 %
Current Iteration  10  is at  25.0 %
Current Iteration  10  is at  30.0 %
Current Iteration  10  is at  35.0 %
Current Iteration  10  is at  40.0 %
Current Iteration  10  is at  45.0 %
Current Iteration  10  is at  50.0 %
Current Iteration  10  is at  55.0 %
Current Iteration  10  is at  60.0 %
Current Iteration  10  is at  65.0 %
Current Iteration  10  is at  70.0 %
Current Iteration  10  is at  75.0 %
Current Iteration  10  is at  80.0 %
Current Iteration  10  is at  85.0 %
Current Iteration  10  is at  90.0 %
Current Iteration  10  is at  95.0 %
Current Iteration  9  is at  0.0 %
Current Iteration  9  is at  5.0 %
Current Iteration  9  is at  10.0 %
Current Iteration  9  is at  15.0 %
Current Iteration  9  is at  20.0 %
Current Iteration  9  is at  25.0 %
Current Iteration  9  is at  30.0 %
Current Iter[...]
{'fraction_non_alphanumeric': 0.10854271356783919, 'fraction_numerical': 0.05175879396984925, 'mean_word_length': 2.745061147695202, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '561361', 'license': 'MIT', 'n_tokens_mistral': 1790, 'n_tokens_neox': 1477, 'n_words': 474, 'path': 'ImageCompressionKmeans.ipynb', 'repo_name': 'RihaChri/ImageCompressionKmeans', 'size': '3980'}