###################################################
### chunk number 1: 
###################################################
library(CRImage)


###################################################
### chunk number 2: 
###################################################
f = system.file("extdata", "exImg2.jpg", package="CRImage")
exImgB=readImage(f)
#find white pixels and exclude them from thresholding(if white is background)
indexWhitePixel=which(exImgB[,,1]>0.85 & exImgB[,,2]>0.85 & exImgB[,,3]>0.85)
#convert to grayscale
exImgB=channel(exImgB,"gray")
#calculate threshold
t=calculateThreshold(as.vector(exImgB[-indexWhitePixel]))
#create binary image
exImgB[which(exImgB>=t)]=1
exImgB[which(exImgB<t)]=0


###################################################
### chunk number 3: 
###################################################
f = system.file("extdata", "exImg2.jpg", package="CRImage")
segmentationValues=segmentImage(f,maxShape=800,minShape=40,failureRegion=2000) 


###################################################
### chunk number 4: 
###################################################
f = system.file("extdata", "trainingData.txt", package="CRImage")
#read training data
trainingData=read.table(f,header=TRUE)
#create classifier
classifierValues=createClassifier(trainingData,topo=FALSE)
classifier=classifierValues[[1]]
#classifiedCells=classifierValues[[2]]
#display(classifiedCells)


###################################################
### chunk number 5: 
###################################################
	#classify cells
	f = system.file("extdata", "exImg2.jpg", package="CRImage")
	classValues=classifyCells(classifier,filename=f,KS=TRUE,maxShape=800,minShape=40,failureRegion=2000)


###################################################
### chunk number 6: 
###################################################
t = system.file("extdata", "trainingData.txt", package="CRImage")
#read training data
trainingData=read.table(t,header=TRUE)
#create classifier
classifier=createClassifier(trainingData,topo=FALSE)[[1]]
#calculation of cellularity
f = system.file("extdata", "exImg2.jpg", package="CRImage")
exImg=readImage(f)
cellularityValues=calculateCellularity(f,classifier=classifier,cancerIdentifier="1")


###################################################
### chunk number 7: 
###################################################
#create the classifier
t = system.file("extdata", "trainingData.txt", package="CRImage")
trainingData=read.table(t,header=TRUE)
classifier=createClassifier(trainingData,topo=FALSE)[[1]]


###################################################
### chunk number 8:  eval=FALSE
###################################################
## dir.create("AperiOutput")
## f = system.file("extdata",  package="CRImage")
## #the image in CWS format
## f=file.path(f,"8905")
## processAperio(classifier=classifier,inputFolder=f,outputFolder="AperiOutput",identifier="Da",numSections=2,cancerIdentifier="c",maxShape=800,minShape=40,failureRegion=2000)