用kmeans算法压缩图片

kmeans算法应用于图片压缩,思路很简单,把图片转换成像素位置和RGB强度信息,经过kmeans进行聚类,把各像素的RGB值,替换为聚类后的中心值。再把数据转换回图片。

kmeans算法实现于mlass包中,我准备把ml-class(http://www.ml-class.org/)课程所教授的ML算法都实现于mlass包中,目前0.1版本中,只实现了kmeans算法。

在这里,使用mlass包中的kmeans算法压缩我在豆瓣上的头像

?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
x <- rimage::read.jpeg("d:/douban_icon.jpg")
A <- unclass(x)
 
#reshape the image  into an Nx3 matrix
#when N = number of pixels.
# each row will contain the red, green and blue pixel values.
X <- matrix(as.vector(A), ncol=3)
 
# run the k-means algorithm on this data
K <- 8
 
require(mlass)
X.kmeans <- kMeans(X, centers=K)
 
centroids <- X.kmeans["centroids"]
idx <- X.kmeans["clusters"]
X.compressed <- centroids[idx,]
X.compressed <- array(X.compressed, dim=dim(A))
X.compressed <- rimage::imagematrix(X.compressed)
 
par(mfrow=c(1,2))
plot(x, main="Original Image")
plot(X.compressed, main="Compressed Image")


Related Posts

  1. 用kmeans算法压缩图片 | R客 United States Unknow Browser Unknow Os - pingback on February 13, 2012 at 7:38 pm

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackbacks and Pingbacks: