# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library("EBImage")
library(jpeg)
library("grid")
library("gridExtra")
library("rgl")

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

#system("ls ../input/train")


train<- readJPEG("../input/train/dog.5174.jpg")
#if (exists("rasterImage")) { # can plot only in R 2.11.0 and higher
#  plot(1:2, type='n')
#
#  rasterImage(train, 1.2, 1.27, 1.8, 1.73)
#  rasterImage(img.n, 1.5, 1.5, 1.9, 1.8)
#}
dim(train)
grid.raster(train)
train.R<- train
train.G<-train
train.B<-train

train.R[,,2:3]<-0
train.G[,,1]<-0
train.G[,,3]<-0
train.B[,,1:2]<-0

img1 = rasterGrob(train.R)
img2 = rasterGrob(train.G)
img3 = rasterGrob(train.B)
grid.arrange(img1, img2, img3, nrow=1)
#grid.raster(train.R)


df = data.frame(
  red = matrix(train[,,1], ncol=1),
  green = matrix(train[,,2], ncol=1),
  blue = matrix(train[,,3], ncol=1)
)

K<- kmeans(df,4)

str(K)
dim(K$centers)

df$label<- K$cluster



colors = data.frame(
  label = 1:nrow(K$centers), 
  R = K$centers[,"red"],
  G = K$centers[,"green"],
  B = K$centers[,"blue"]
)

df$order = 1:nrow(df)
df = merge(df, colors)
df = df[order(df$order),]
df$order = NULL


R = matrix(df$R, nrow=dim(train)[1])
G = matrix(df$G, nrow=dim(train)[1])
B = matrix(df$B, nrow=dim(train)[1])
  
# reconstitute the segmented image in the same shape as the input image
train.segmented = array(dim=dim(train))
train.segmented[,,1] = R
train.segmented[,,2] = G
train.segmented[,,3] = B

# View the result

real<- rasterGrob(train)

segmented<- rasterGrob(train.segmented)
grid.arrange(real,segmented,ncol=1)
str(df)

PCA = prcomp(df[,c("red","green","blue")], center=TRUE, scale=TRUE)
df$u = PCA$x[,1]
df$v = PCA$x[,2]

summary(PCA)
str(PCA)

ggplot(df, aes(x=u, y=v, col=rgb(red,green,blue))) + 
  geom_point(size=2) + scale_color_identity()

# segmented 
ggplot(df, aes(x=u, y=v, col=rgb(R,G,B))) + 
  geom_point(size=2) + scale_color_identity()



#str(train.segmented)



# Any results you write to the current directory are saved as output.