UT-Arlington-Research icon indicating copy to clipboard operation
UT-Arlington-Research copied to clipboard

Updated Code for convolution.py

Open ankit869 opened this issue 1 year ago • 0 comments

import numpy as np
def conv2d(image,kernal,padding=0,strides=1):
      xKernShape=kernal.shape[0]
      yKernShape=kernal.shape[1]
      xImgShape=image.shape[0]
      yImgShape=image.shape[1]
      padding=int(padding)
      strides=int(strides)

      xOutput = int(((xImgShape - xKernShape + 2 * padding) / strides) + 1)
      yOutput = int(((yImgShape - yKernShape + 2 * padding) / strides) + 1)
  
      output = np.zeros((xOutput, yOutput))
      
      ImgPadded=None
      if padding!=0:
          ImgPadded=np.zeros((xImgShape+2*padding,yImgShape+2*padding))
          ImgPadded[padding:-padding,padding:-padding]=image
      else:
          ImgPadded=image
      
      j=0
      for y in range(ImgPadded.shape[1]):
          if y > ImgPadded.shape[1] - yKernShape:
              break
              
          if y%strides==0:
              i=0
              for x in range(ImgPadded.shape[0]):
                  if x > ImgPadded.shape[0] - xKernShape:
                      break
                  
                  if x%strides==0:
                      output[i,j]=np.sum(kernal*(ImgPadded[x:x+xKernShape,y:y+yKernShape]))
                      i+=1
              j+=1
      return output

ankit869 avatar Mar 10 '23 10:03 ankit869