#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## a. CLEAN WORKSPACE AND LOAD LIBRARIES ----
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
rm(list=ls())

library(imager)
img <- load.image(file='00_data/Santa_Jung_2.jpg')


img.gray <- grayscale(img, method = "Luma", drop = TRUE) 
#Edge filter
filter <- as.cimg(function(x,y) sign(x-10),5,5) 
#Convolution vs. correlation 
img.corr <- correlate(img.gray,filter)
bin_image <- round(img.corr/1*max(img.corr),0)
plot(bin_image)
raster <- as.raster(bin_image)
pxl_grid <- expand.grid(x = 1:nrow(raster), y = 1:ncol(raster)) 
out <- transform(pxl_grid, z = raster[as.matrix(pxl_grid)])
unique(out$z)
out$y <- ncol(raster)-(ncol(raster)-out$y+1)
out$x <- nrow(raster)-out$x+1

out.idx1 <- which(out$z %in% c("#000000","#333333"))
smpl.idx1 <- sample(out.idx1,size=70000,replace=FALSE)
out.idx2 <- which(out$z %in% c("#404040"
                               ,"#808080"))
smpl.idx2 <- sample(out.idx2,size=30000,replace=FALSE)
out.idx3 <- which(out$z %in% c("#BFBFBF"))
smpl.idx3 <- sample(out.idx3,size=5000,replace=FALSE)

plot(out[c(smpl.idx1,
           smpl.idx2,
           smpl.idx3
           ),c("y","x")],pch=16,cex=0.1)


out_matrix <- data.frame(out[c(smpl.idx1,smpl.idx2,smpl.idx3),c("y","x")])
out_matrix <- out_matrix[sample.int(nrow(out_matrix),size=nrow(out_matrix),replace=FALSE),]
out_matrix$ID <- 1:nrow(out_matrix)
out_matrix <- out_matrix[,c("ID","y","x")]
rownames(out_matrix) <- NULL
names(out_matrix) <- c("ID","x","y")

write.csv(out_matrix,file="00_data/point_cloud.csv",row.names = FALSE)


                            