Advertisement
akariya

[ECE592] Project 4 P1_3 Rate vs Distortion

Nov 12th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. def runKmeans(img, p, C):
  5.  
  6.     y , x = img.shape
  7.     number_of_patches = int((y * x)/(p ** 2))
  8.     data = []
  9.     i = 0
  10.     for i in range(0, y - 1, p):
  11.         for j in range(0, x - 1, p):
  12.             patch = img[i:i+p, j:j+p]
  13.             data.append(patch)
  14.     criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.1)
  15.     R = (np.log2(C)*number_of_patches)/(y * x)
  16.     compactness, labels, centers = cv2.kmeans(np.asarray(data).astype('float32'),C,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
  17.     i = 0
  18.     data_point = 0
  19.     for i in range(0, y - 1, p):
  20.         for j in range(0, x - 1, p):
  21.             img[i:i+p, j:j+p] = centers[labels[data_point][0]].reshape(p,p).astype('uint8')
  22.             data_point += 1
  23.     return [R, compactness**0.5, img]
  24.  
  25. imgC =  cv2.imread('wolves.png', 0)[27:, 460:972]
  26. p = 2
  27. R = []
  28. D = []
  29. for i in range(0, 7):
  30.     C = (2**i)
  31.     print(C)
  32.     RD = runKmeans(imgC.copy(), p, C)
  33.     cv2.imshow('img',imgC - RD[2])
  34.     cv2.waitKey(0)
  35.     cv2.destroyAllWindows()
  36.     error = np.mean(((imgC.astype('float32') - RD[2].astype('float32')).astype('float32') * (imgC.astype('float32') - RD[2].astype('float32')).astype('float32')).flatten())
  37.     R.append(RD[0])
  38.     D.append(error)
  39.  
  40. print(R)
  41. print(D)
  42. plt.ylabel('D')
  43. plt.xlabel('R')
  44. plt.plot(R, D)
  45. plt.xticks(range(1, 3))
  46. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement