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
|
# Provides several methods to binarize a vector consisting of real values.
# The methods are edge-detector-based. With <edge>="firstEdge",
# the first "significant" edge in the sorted data is the threshold for the binarization.
# With the <scaling> factor, the size of the first edge can be adapted.
# The "maxEdge" method searches for the edge with the highest gradient.
edgeDetector <- function(vector,scaling=1,edge=c("firstEdge","maxEdge"))
{
distance<-c()
binarizeddata<-vector
#sort data
sortedvector<-sort(vector)
#distance calculation
for(i in seq_len(length(vector)-1))
{
distance[i]<-sortedvector[i+1]-sortedvector[i]
}
switch(match.arg(edge),
#the index of the first edge with distance[i]>threshold is determined
firstEdge=
{
threshold<-scaling*((sortedvector[length(vector)]-sortedvector[1])/((length(vector)-1)))
index <- 0
for(i in seq_len(length(vector)-1))
{
if(distance[i]>threshold)
{
index<-i
break
}
}
},
#the index of the edge with the maximal gradient is determined
maxEdge=
{
index <- which.max(distance)
},
stop("'method' must be one of \"firstEdge\",\"maxEdge\"")
)
#based on the edge index, the binarization is performed
if(index!=0)
{
for(i in seq_len(length(vector)))
{
if(vector[i]>=sortedvector[index+1])
binarizeddata[i]<-1
else
binarizeddata[i]<-0
}
threshold=(sortedvector[index+1]+sortedvector[index])/2
return(list(bindata=binarizeddata,thresholds=as.numeric(threshold)))
}
else
#if no edge was found, a vector consisting of zeros is returned
{
binarizeddata<-(sapply(vector,function(x) 0))
return(list(bindata=binarizeddata,thresholds=NA))
}
}
|