Advertisement
akariya

[ECE592] Project 4 P1_4 Patch size

Nov 12th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 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)
  22.             data_point += 1
  23.     return [R, compactness**0.5, img]
  24.  
  25. imgC =  cv2.imread('wolves.png', 0)[27:, 460:972]
  26. R = []
  27. D = []
  28. for i in range(0, 7):
  29.     for j in range(0, 4):
  30.         C = (2**i)
  31.         p = (2**j)
  32.         RD = runKmeans(imgC.copy(), p, C)
  33.         error = np.mean(((imgC.astype('float32') - RD[2].astype('float32')).astype('float32') * (imgC.astype('float32') - RD[2].astype('float32')).astype('float32')).flatten())
  34.         R.append(RD[0])
  35.         D.append(error)
  36.  
  37. RD = sorted(zip(R,D))
  38. R, D = map(list,zip(*RD))  
  39. plt.ylabel('D')
  40. plt.xlabel('R')
  41. plt.plot(R, D)
  42. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement