Image Processing_Boarder Detection (R Studio)

Image Processing_Boarder Detection (R Studio)

An image is essentially a N*M*3 matrix (like 1024*768*3)

By calculating the local variance of a pixel, and by defining thresholds, it's easy to run a simple boarder detection algorithm.

Note: It works perfectly with anything less furry (check the red-panda and desktop example and how cute little fur-balls could mess up my results.)

Output:


Code:

# Load image

matfile <- readMat("/Users/gaochenying1/Desktop/My Projects Demo/linkedin.mat")

testimage = matfile$maskedRGBImage

dim(testimage)

# Let's see how it goes for a single image

nr=dim(testimage)[1]

nc=dim(testimage)[2]

band=5

N=nr*nc

flag.mat=matrix(0,nrow = (nr-(band-1)),ncol = (nc-(band-1)))

var.mat=matrix(0,nrow = (nr-(band-1)),ncol = (nc-(band-1)))

# Calculate Variance of Neighbours

for (i in 3:(nr-(band-1)/2))

{

 for (j in 3:(nc-(band-1)/2))

 {

  tempmat1=testimage[(i-2):(i+2),(j-2):(j+2),1]

  tempvar1=sum((tempmat1-mean(tempmat1))^2)/(band^2)

  # tempflag=ifelse(tempvar>)

  var.mat[i-(band-1)/2,j-(band-1)/2]=tempvar1

 }

}

hist(as.numeric(var.mat), col = "#81D8D0") # Adjust Threshold according to this

# Flag the large variance element and call them borders

thershold=quantile(var.mat,0.92)

for (i in 1:(nr-(band-1)))

{

 for (j in 1:(nc-(band-1)))

 {

  tempflag=ifelse(var.mat[i,j]>thershold,1,0)

  flag.mat[i,j]=tempflag

 }

}

flag.rt = t(apply(flag.mat, 2, rev))

image(flag.rt,col=c("black", "#9de3e1"), main = "LinkedIn Logo")

remove(list=c("testimage", "matfile", "flag.mat", "var.mat"))



要查看或添加评论,请登录

Kathy GAO的更多文章

社区洞察

其他会员也浏览了