# 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 

# 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")

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

library(dplyr)
library(EBImage)
packageVersion("EBImage") # >= 4.12.2

## ============================================================
## Human Skin Colors

colors <-read.table(header=TRUE, sep=",", text="
r,g,b
0.1,0.1,0
0.2,0.2,0.1
0.3,0.3,0.3
0.3,0.3,0.2
0.4,0.4,0.3
0.4,0.4,0.4
0.2,0.1,0.1
0.5,0.5,0.4
0.3,0.2,0.2
0.4,0.5,0.4
0.9,1,0.9
0.6,0.7,0.7
0.5,0.5,0.3
0.4,0.7,0.8
0.6,0.6,0.5
0.4,0.3,0.3
0.5,0.5,0.5
0.7,0.7,0.6
0.5,0.4,0.3
1,1,0.9
0.8,0.8,0.7
0.5,0.4,0.4
0.6,0.6,0.4
0.4,0.3,0.2
0.8,0.9,0.9
0.5,0.6,0.5
0.6,0.6,0.6
0.6,0.7,0.6
0.7,0.7,0.7
0.7,0.8,0.7
0.7,0.7,0.5
0.9,0.9,0.8
0.8,0.9,0.8
0.7,0.6,0.5
0.8,0.7,0.6
0.6,0.5,0.4
0.9,0.9,0.7
0.8,0.8,0.6
0.8,0.8,0.8
0.9,0.8,0.7
0.8,0.7,0.7
0.9,0.9,0.9
0.9,0.8,0.8
0.8,0.7,0.5
1,0.9,0.9
")

filterthiscolors <- function(x, colors){
    ##print("Human Skin Colors")
    dt <- as.data.frame(round(matrix(x,nrow=prod(dim(x)[1:2]),ncol=3),1))
    colnames(dt) <- c("r","g","b")
    colors$yes <- TRUE
    d1 <- left_join(dt,colors,by=c("r","g","b"))
    d1$yes[is.na(d1$yes)] <- FALSE
    c(d1$yes,d1$yes,d1$yes)
}


## ============================================================
## Sample an image

file <- paste0("../input/train/","c0","/", "img_100026.jpg")
x <- readImage(file)
print("Original image")
display(x) ## Original image

filter <- filterthiscolors(x,colors)

print("Get the face and hands")
table(filter)
x1 <- x
x1[!filter] <- 0 
display(x1)


print("Median")
x2 <- medianFilter(x1,4)
display(x2)

print("Clean up noise")
x3 <- x
x3[as.array(x2) < 0.25 | as.array(x2) > 0.8] <- 0
display(x3)