Refrerence

https://blog.saush.com/2011/04/20/edge-detection-with-the-sobel-operator-in-ruby/

#install.packages("BiocManager")
#BiocManager::install("EBImage")
library(EBImage)
IMG<-readImage('E:\\Projects\\Plane.jpg')
display(IMG,method = 'browser')

Understanding the internal strucuture of class Image

str(IMG)
## Formal class 'Image' [package "EBImage"] with 2 slots
##   ..@ .Data    : num [1:630, 1:420, 1:3] 0.651 0.655 0.655 0.659 0.663 ...
##   ..@ colormode: int 2

The .Data slot contains a numeric array of pixel intensities.

dim(IMG)
## [1] 630 420   3

A 630x420 Image of RGB

Using the first frame for the Sobel implementation

IMG_frame1<-IMG@.Data[,,3]

Visualising first frame

display(IMG_frame1)

The sobel kernel x filter

convol_x<-matrix(c(-1,0,1,-2,0,2,-1,0,1),3,3)
convol_x
##      [,1] [,2] [,3]
## [1,]   -1   -2   -1
## [2,]    0    0    0
## [3,]    1    2    1

Resized image to 300x300. Techniques like max-pooling and min-pooling can be used but here we have used a simple resizing filter. This make the application of the 3x3 sobel kernel much simpler

IMG_frame1_resize<-resize(IMG_frame1,300,300)

display(IMG_frame1_resize)

Sobel Filter implementation

sobel<-readImage('sobel.png')
display(sobel)

IMG_conv<-matrix(0,(dim(IMG_frame1_resize)[1]-1),(dim(IMG_frame1_resize)[2]-1))

for (i in seq(2,dim(IMG_frame1_resize)[1]-1)){##row
  for (j in seq(2,dim(IMG_frame1_resize)[2]-1)){##col
 
    ##Please read about the convolution filter from reference page
    IMG_conv[i,j]<-sum(diag(IMG_frame1_resize[(i-1):(i+1),(j-1):(j+1)]%*%t(convol_x)))
    
  }
}

Sobel X kernel Image putput

display(IMG_conv)

sobel y filter, the sobel y filter is nothing but the transpose of the x filter

convol_y<-t(convol_x)

Applying the Y kernel by doing matrix multiplication

IMG_con_y<-matrix(0,(dim(IMG_frame1_resize)[1]-1),(dim(IMG_frame1_resize)[2]-1))
for (i in seq(2,dim(IMG_frame1_resize)[1]-1)){##row
  for (j in seq(2,dim(IMG_frame1_resize)[2]-1)){##col
    ##as the first row cannot be convoluted
    ##as the first col cannot be convoluted
    
    #IMG_conv[i,j]<-sum((IMG_frame1_resize[(i-1):(i+1),(j-1):(j+1)]%*%t(convol_x))[1,1:3])
    IMG_con_y[i,j]<-sum(diag(IMG_frame1_resize[(i-1):(i+1),(j-1):(j+1)]%*%t(convol_y)))
    
  }
}

Sobel Y kernel Image putput

display(IMG_con_y)

Sobel kernel is formed by adding up the squares of x and y convolutions and then taking their square root

IMG_sobel_filter<-sqrt(IMG_conv^2+IMG_con_y^2)

Final output

display(IMG_sobel_filter)