K-means 寻找图像主体颜色
        【摘要】 几个月前,我写了篇文章“纯python编写K-means算法,提取图片中的主体颜色”,找到图片中的显著颜色。今天突发奇想,能不能把k-means用于图片压缩呢?对图像rgb三个通道进行聚类,得到中心点像素,并填充对应的类别区域,我找来了一张上海的图片进行压缩。
    
    
    
    几个月前,我写了篇文章“纯python编写K-means算法,提取图片中的主体颜色”,找到图片中的显著颜色。
今天突发奇想,能不能把k-means用于图片压缩呢?对图像rgb三个通道进行聚类,得到中心点像素,并填充对应的类别区域,我找来了一张上海的图片进行压缩。

我的代码如下,由于在jupyte编辑器上写的代码,因此显示图片使用的matplotlib模块
numpy np
matplotlib.pyplot plt
skimage io
cv2 cv
os
sklearn.cluster KMeans
img = io.imread()
img = np.array(img=np.float64) / plt.axis()
plt.imshow(img)
outImgPath = os.path.exists(outImgPath):
    os.makedirs(outImgPath)
(imgk):
    whc = img.shape
    dd = np.reshape(img(w * hc))
    km = KMeans(=k)
    km.fit(dd)
    labels = km.predict(dd)
    centers = km.cluster_centers_
    new_img = img.copy()
    i (w):
        j (h):
            ij = i * h + j
            new_img[i][j] = centers[labels[ij]]
    {: new_img: centers}
plt.figure(=())
plt.imshow(d)
plt.axis()
plt.show()
i ():
    (i)
    out = KMeansImage(=img=i)
    centersnew_image = out[]out[]
    (new_image.shape)
    plt.figure(=())
    plt.imshow([centers]);
    plt.axis()
    plt.show()
        result = []
    result_width =     result_height_per_center =     center_index (i):
        result.append(np.full((result_width * result_height_per_centercenters.shape[])centers[center_index] * =))
    result = np.array(result)
    result = result.reshape((result_height_per_center * iresult_widthcenters.shape[]))
        imgName = % i
    cv.imwrite(os.path.join(outImgPathimgName)result)
    plt.figure(=())
    plt.imshow(new_image)
    plt.axis()
    plt.show()
    imgName = % i
    cv.imwrite(os.path.join(outImgPathimgName)new_image * )
我们看一下生成的图片合成的gif吧~
 
                                      
当k为2时

 
        
当k为3时

|    | 
当k为4时
|    | 
当k为5时
|    | 
当k为11时
|    | 
当k为21时
|    | 
当k为51时
|    | 
当k为101时
|    | 
当k为200时
|    | 
观察上面的图片,可以看到,当K值增大的时候,图片的色彩会更加丰富,画面变得更加细腻。
这种方法比较简单,但也有弊端,kmeans的运算速度实在是太慢了,在高分辨率图片下,计算时间过长。

本文来自Monk
原文链接:http://www.siyuanblog.com/?p=101593
        【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
            cloudbbs@huaweicloud.com
        
        
        
        
        
        
        - 点赞
- 收藏
- 关注作者
 
             
           
评论(0)