Convolution – OpenCV

Convolution probably is the most used method in field of image processing in order to apply a certain mask (kernel) to the image. Here  is a good explanation about convolution. Its simply multiplying mask’s values with image’s pixels intensity and sum them up as show below:

Adapted from

However it should be noticed that because of taking care of impulse response the kernel should be flipped horizontally and vertically.  Here is code for applying convolution on an image:

def convolve(image, kernel):
  '''fliping kernel'''
  '''creating output image based on input image dimention
  notice that I did not take care of the image edges
  so out put will has less pixels than orginal, the number
  of omitted pixels depends on kernel size'''
  output = np.zeros((1+image.shape[0]-kernel.shape[0],1+image.shape[1]-kernel.shape[1]), dtype=image.dtype)
  for i in range(0,output.shape[0]):
   for j in range(0,output.shape[1]):
    signal_patch = image[i:i+kernel.shape[0],j:j+kernel.shape[1]]
    tmp = (rkernel * signal_patch).sum()
	'''not really the best method to normalize the image'''
    if tmp>255:
    if tmp<0:
  return output


One thought on “Convolution – OpenCV

  1. [Tensorflow] Deep Learning for pose estimation – Digital Thinking

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s