1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| library(png)
nacre <- readPNG("test.png")
nacre
dim(nacre)
# show the full RGB image
grid.raster(nacre)
# show the 3 channels in separate images
nacre.R = nacre
nacre.G = nacre
nacre.B = nacre
# zero out the non-contributing channels for each image copy
nacre.R[,,2:3] = 0
nacre.G[,,1]=0
nacre.G[,,3]=0
nacre.B[,,1:2]=0
# build the image grid
img1 = rasterGrob(nacre.R)
img2 = rasterGrob(nacre.G)
img3 = rasterGrob(nacre.B)
grid.arrange(img1, img2, img3, nrow=1)
# Now lets segment this image. First, we need to reshape the array into a data frame with one row for each pixel and three columns for the RGB channels:
# reshape image into a data frame
df = data.frame(
red = matrix(nacre[,,1], ncol=1),
green = matrix(nacre[,,2], ncol=1),
blue = matrix(nacre[,,3], ncol=1)
)
### compute the k-means clustering
K = kmeans(df,4)
df$label = K$cluster
### Replace the color of each pixel in the image with the mean
### R,G, and B values of the cluster in which the pixel resides:
# get the coloring
colors = data.frame(
label = 1:nrow(K$centers),
R = K$centers[,"red"],
G = K$centers[,"green"],
B = K$centers[,"blue"]
)
# merge color codes on to df
df$order = 1:nrow(df)
df = merge(df, colors)
df = df[order(df$order),]
df$order = NULL
# get mean color channel values for each row of the df.
R = matrix(df$R, nrow=dim(nacre)[1])
G = matrix(df$G, nrow=dim(nacre)[1])
B = matrix(df$B, nrow=dim(nacre)[1])
# reconstitute the segmented image in the same shape as the input image
nacre.segmented = array(dim=dim(nacre))
nacre.segmented[,,1] = R
nacre.segmented[,,2] = G
nacre.segmented[,,3] = B
# View the result
grid.raster(nacre.segmented) |
Partager