图片压缩

直接上代码


import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import sklearn.cluster as skcluster


img_path = input('Enter the image path you want to compress: ')
if not os.path.exists(img_path):
   print('Invalid path')
   sys.exit(1)

A = mpimg.imread(img_path)
A = A.astype(float) / 255
img_shape = np.shape(A)
X = np.reshape(A, (img_shape[0] * img_shape[1], 3))
clf = skcluster.KMeans(n_clusters=10, random_state=0).fit(X)
print('Finish training!...')
idx, centroids = clf.labels_, clf.cluster_centers_
X_compressed = centroids[idx, :]
A_compressed = np.reshape(X_compressed, (img_shape[0], img_shape[1], img_shape[2]))
plt.imshow(A_compressed)
plt.show()
原文地址:https://www.cnblogs.com/megachen/p/10037353.html