<reponame>bjlhx15/python-algorithm
# -*- coding: UTF-8 -*-
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.datasets import load_sample_image
from sklearn.utils import shuffle
from time import time

def recreate_image(codebook, labels, w, h):
    # Recreate the (compressed) image from the code book & labels
    d = codebook.shape[1]
    image = np.zeros((w, h, d))
    label_idx = 0
    for i in range(w):
        for j in range(h):
            image[i][j] = codebook[labels[label_idx]]
            label_idx += 1
    return image

def func(imgPath):
    n_colors = 64
    china2 = load_sample_image(imgPath)  # 加载图片

    #转换为浮点数，PLTIMSID行为在浮点数据上很好地工作
    china2 = np.array(china2, dtype=np.float64) / 255

    #将图片转成二维数组
    w, h, d = original_shape = tuple(china2.shape)
    assert d == 3
    image_array = np.reshape(china2, (w * h, d))

    print("一个小样本数据的拟合模型")
    t0 = time()
    image_array_sample = shuffle(image_array, random_state=0)[:1000]
    kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
    print("done in %0.3fs." % (time() - t0))

    # Get labels for all points
    print("Predicting color indices on the full image (k-means)")
    t0 = time()
    labels = kmeans.predict(image_array)
    print("done in %0.3fs." % (time() - t0))

    # codebook_random = shuffle(image_array, random_state=0)[:n_colors + 1]
    # print("Predicting color indices on the full image (random)")
    # t0 = time()
    # labels_random = pairwise_distances_argmin(codebook_random,
                                            # image_array,
                                            # axis=0)
    # print("done in %0.3fs." % (time() - t0))


    # Display all results, alongside original image
    plt.figure(1)
    plt.clf()
    ax = plt.axes([0, 0, 1, 1])
    plt.axis('off')
    plt.title('Original image (96,615 colors)')
    plt.imshow(china2)

    plt.figure(2)
    plt.clf()
    ax = plt.axes([0, 0, 1, 1])
    plt.axis('off')
    plt.title('Quantized image (64 colors, K-Means)')
    plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h))

    # plt.figure(3)
    # plt.clf()
    # ax = plt.axes([0, 0, 1, 1])
    # plt.axis('off')
    # plt.title('Quantized image (64 colors, Random)')
    # plt.imshow(recreate_image(codebook_random, labels_random, w, h))
    plt.show()

if __name__ == '__main__':
    imgPath = 'a.jpg'
    func(imgPath)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
# -*- coding: UTF-8 -*-
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.datasets import load_sample_image
from sklearn.utils import shuffle
from time import time

def recreate_image(codebook, labels, w, h):
    # Recreate the (compressed) image from the code book & labels
    d = codebook.shape[1]
    image = np.zeros((w, h, d))
    label_idx = 0
    for i in range(w):
        for j in range(h):
            image[i][j] = codebook[labels[label_idx]]
            label_idx += 1
    return image

def func(imgPath):
    n_colors = 64
    china2 = load_sample_image(imgPath)  # 加载图片

    #转换为浮点数，PLTIMSID行为在浮点数据上很好地工作
    china2 = np.array(china2, dtype=np.float64) / 255

    #将图片转成二维数组
    w, h, d = original_shape = tuple(china2.shape)
    assert d == 3
    image_array = np.reshape(china2, (w * h, d))

    print("一个小样本数据的拟合模型")
    t0 = time()
    image_array_sample = shuffle(image_array, random_state=0)[:1000]
    kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
    print("done in %0.3fs." % (time() - t0))

    # Get labels for all points
    print("Predicting color indices on the full image (k-means)")
    t0 = time()
    labels = kmeans.predict(image_array)
    print("done in %0.3fs." % (time() - t0))

    # codebook_random = shuffle(image_array, random_state=0)[:n_colors + 1]
    # print("Predicting color indices on the full image (random)")
    # t0 = time()
    # labels_random = pairwise_distances_argmin(codebook_random,
                                            # image_array,
                                            # axis=0)
    # print("done in %0.3fs." % (time() - t0))


    # Display all results, alongside original image
    plt.figure(1)
    plt.clf()
    ax = plt.axes([0, 0, 1, 1])
    plt.axis('off')
    plt.title('Original image (96,615 colors)')
    plt.imshow(china2)

    plt.figure(2)
    plt.clf()
    ax = plt.axes([0, 0, 1, 1])
    plt.axis('off')
    plt.title('Quantized image (64 colors, K-Means)')
    plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h))

    # plt.figure(3)
    # plt.clf()
    # ax = plt.axes([0, 0, 1, 1])
    # plt.axis('off')
    # plt.title('Quantized image (64 colors, Random)')
    # plt.imshow(recreate_image(codebook_random, labels_random, w, h))
    plt.show()

if __name__ == '__main__':
    imgPath = 'a.jpg'
    func(imgPath)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
# -*- coding: UTF-8 -*- # Recreate the (compressed) image from the code book & labels # 加载图片 #转换为浮点数，PLTIMSID行为在浮点数据上很好地工作 #将图片转成二维数组 # Get labels for all points # codebook_random = shuffle(image_array, random_state=0)[:n_colors + 1] # print("Predicting color indices on the full image (random)") # t0 = time() # labels_random = pairwise_distances_argmin(codebook_random, # image_array, # axis=0) # print("done in %0.3fs." % (time() - t0)) # Display all results, alongside original image # plt.figure(3) # plt.clf() # ax = plt.axes([0, 0, 1, 1]) # plt.axis('off') # plt.title('Quantized image (64 colors, Random)') # plt.imshow(recreate_image(codebook_random, labels_random, w, h)) # cv2.waitKey(0) # cv2.destroyAllWindows()