Guest User

Untitled

a guest
Jun 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.41 KB | None | 0 0
  1. # coding: utf-8
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. get_ipython().run_line_magic('matplotlib', 'inline')
  5. import cv2
  6. from sklearn.cluster import KMeans
  7. import os
  8.  
  9. file_name_with_path = './im.jpg' # replace your image path here
  10. file_size = os.path.getsize(file_name_with_path)
  11. print('Original File Size: ', file_size, 'bytes')
  12.  
  13. file_size_dict = {}
  14. file_size_dict[0] = file_size
  15.  
  16. im = cv2.imread(file_name_with_path)
  17. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  18.  
  19. out_r = 100
  20. print('Original Shape: ', im.shape)
  21. # r=row, c=column, ch=channel
  22. r,c,ch = im.shape
  23.  
  24. im = cv2.resize(im, (int(out_r*float(c)/r), out_r))
  25. r_new,c_new,ch_new = im.shape
  26.  
  27. #print('Resized Image Shape: ', im.shape)
  28.  
  29. pixels = im.reshape((-1, 3))
  30. #print(pixels.shape)
  31.  
  32. plt.imshow(im)
  33. plt.show()
  34.  
  35. km = KMeans(n_clusters=8)
  36. km.fit(pixels)
  37. labels = km.fit_predict(pixels)
  38.  
  39. centr_colors = np.array(km.cluster_centers_, dtype='uint8')
  40. labels = np.array(labels)
  41. quantized = centr_colors[labels]
  42.  
  43. # print(centr_colors.dtype)
  44. # print(centr_colors.shape)
  45.  
  46. quant_image = quantized.reshape((r_new, c_new, 3))
  47. quant_image = cv2.cvtColor(quant_image, cv2.COLOR_RGB2BGR)
  48.  
  49. # plt.imshow(im)
  50. # plt.show()
  51. # plt.imshow(quant_image)
  52. # plt.show()
  53.  
  54. fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
  55. ax1.imshow(im)
  56. ax2.imshow(quant_image)
  57. plt.show()
  58.  
  59. # cv2.imshow("image", np.hstack([im, quant_image]))
  60.  
  61. def compress_image(K):
  62. km = KMeans(n_clusters=K)
  63. km.fit(pixels)
  64. labels = km.fit_predict(pixels)
  65.  
  66. centr_colors = np.array(km.cluster_centers_, dtype='uint8')
  67. labels = np.array(labels)
  68. quantized = centr_colors[labels]
  69.  
  70. # print(labels.shape)
  71. # print(quantized.shape)
  72.  
  73. quant_image = quantized.reshape((r_new, c_new, 3))
  74. quant_image = cv2.cvtColor(quant_image, cv2.COLOR_RGB2BGR)
  75.  
  76. ## Display image inline below
  77. # fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
  78. # fig.suptitle('K=' + str(K))
  79. # ax1.imshow(im)
  80. # ax2.imshow(quant_image)
  81. # plt.show()
  82.  
  83. ## write images to disk
  84. img_name = './images/' + str(K) + '.png'
  85. cv2.imwrite(img_name, quant_image)
  86. file_size_dict[K] = os.path.getsize(img_name)
  87.  
  88. def generate_power_list(base, pwr_from, pwr_to):
  89. return [base**j for j in range(pwr_from, pwr_to + 1)]
  90.  
  91. # for values of K to be between 16 to 2048
  92. for i in range(4, 12):
  93. K=2**i
  94. compress_image(K)
  95. print('Compression Ratio percent for K=', K, ' is ', (float(file_size_dict[K])/file_size_dict[0]) * 100)
  96.  
  97. freq = np.array(np.unique(km.labels_, return_counts=True)[1], dtype='float32')
  98. print(freq)
  99. print(freq.sum())
  100. freq = freq/pixels.shape[0]
  101. print(freq)
  102. print(freq.sum())
  103.  
  104. dom = [[freq[ix], centr_colors[ix]] for ix in range(km.n_clusters)]
  105.  
  106. DOM = sorted(dom, key=lambda z:z[0], reverse=True)
  107. #DOM = np.array(DOM)
  108. print(DOM[0][1])
  109. #print DOM.shape
  110.  
  111. for ix in DOM:
  112. print(ix)
  113. print("----------")
  114.  
  115.  
  116. patch = np.zeros((50, 500, 3))
  117. start = 0
  118. for ix in range(km.n_clusters):
  119. width = int(DOM[ix][0]*patch.shape[1])
  120. end = start+width
  121. patch[:,start:end,:] = 255 - DOM[ix][1]
  122. start = end
  123. plt.axis("off")
  124. # plt.imshow(patch)
  125.  
  126. cv2.imwrite('color_img.jpg', patch)
  127.  
  128. # cv2.imshow('Color image', patch)
  129. # print(patch)
  130. # plt.show()
  131.  
  132. # calculate compression ratio percent
  133. for i in range(4, 12):
  134. K=2**i
  135. img_name = './images/' + str(K) + '.png'
  136. new_file_size = (float(os.path.getsize(img_name))/file_size) * 100
  137.  
  138. print('Compression Ratio percent for K=', K, ' is ', ("%.2f" % new_file_size), '%')
Add Comment
Please, Sign In to add comment