Python压缩图像方法



# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 18:05:22 2018
@author: jcy
"""
import numpy as np
from scipy import misc
from sklearn import cluster
import matplotlib.pyplot as plt
class MyCompressImage:
    def __init__(self,Image='d:\\flower_image.jpg',num_bits=4):
        if not 1 <= num_bits <= 8:
             raise TypeError('Number of bits should be between 1 and 8')
        self.ImageFile=Image
        self.num_bits=num_bits
        self.num_clusters=np.power(2, num_bits)
        self.compression_rate = round(100 * (8.0 - num_bits) / 8.0, 2)
    def Image_imread(self):
        self.img = misc.imread(self.ImageFile, True).astype(np.uint8)
    def Image_plot(self,img,title):
        vmin = img.min()
        vmax = img.max()
        plt.figure()
        plt.title(title)
        plt.imshow(img, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)  
    def Image_compress(self):
        # Convert input image into (num_samples, num_features)
        # array to run kmeans clustering algorithm
        X = self.img.reshape((-1, 1))     
        # Run kmeans on input data
        kmeans = cluster.KMeans(n_clusters=self.num_clusters, n_init=4, random_state=5)
        kmeans.fit(X)
        centroids = kmeans.cluster_centers_.squeeze()
        labels = kmeans.labels_   
        # Assign each value to the nearest centroid and
        # reshape it to the original image shape
        self.image_compressed = np.choose(labels, centroids).reshape(self.img.shape)   
    def Details(self):
        print("\nThe size of the image will be reduced by a factor of", 8.0/self.num_bits)
        print("\nCompression rate = " + str(self.compression_rate) + "%")
MycmpImg=MyCompressImage('d:\\flower_image.jpg',2)
MycmpImg.Image_imread()
MycmpImg.Image_plot(MycmpImg.img,"Original image")
MycmpImg.Image_compress()
MycmpImg.Image_plot(MycmpImg.image_compressed,'Compressed image; compression rate = ' + str(compression_rate) + '%')
plt.show()

 大家,加油!

发布了172 篇原创文章 · 获赞 113 · 访问量 34万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览