Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- import matplotlib.pyplot as plt
- def runKmeans(img, p, C):
- y , x = img.shape
- number_of_patches = int((y * x)/(p ** 2))
- data = []
- i = 0
- for i in range(0, y - 1, p):
- for j in range(0, x - 1, p):
- patch = img[i:i+p, j:j+p]
- data.append(patch)
- criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.1)
- R = (np.log2(C)*number_of_patches)/(y * x)
- compactness, labels, centers = cv2.kmeans(np.asarray(data).astype('float32'),C,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
- i = 0
- data_point = 0
- for i in range(0, y - 1, p):
- for j in range(0, x - 1, p):
- img[i:i+p, j:j+p] = centers[labels[data_point][0]].reshape(p,p)
- data_point += 1
- return [R, compactness**0.5, img]
- imgC = cv2.imread('suzdal.jpg', 0)[373:885,100:612]
- cv2.imshow('original', imgC)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
- p = 4
- C = 16
- RD = runKmeans(imgC.copy(), p, C)
- error = np.mean(((imgC.astype('float32') - RD[2].astype('float32')).astype('float32') * (imgC.astype('float32') - RD[2].astype('float32')).astype('float32')).flatten())
- print(error)
- cv2.imshow('compressed',RD[2])
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement