Saturday, June 1, 2013

Convolution of Two Images (matrix form) - OpenCV - Python

To perform convolution of two matrices


import cv2.cv as cv
import sys

if __name__ == '__main__':
  mat1 = cv.CreateMat(3, 3, 8)
  mat2 = cv.CreateMat(3, 3, 8)
  dst = cv.CreateImage(cv.GetSize(mat1), 8, 3)

  kernel = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
  matrix2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  for i in range(3):
    for j in range(3):
      mat1[i][j] = kernel[i][j]
  for i in range(3):
    for j in range(3):
      mat2[i][j] = matrix2[i][j]

  cv.NamedWindow("convolution", 1)
  cv.Filter2D(mat2, dst, mat1)
  cv.ShowImage('convolution', dst)

  print 'Press any key to quit'
  cv.WaitKey(0)
  print 'Exiting...'
  cv.DestroyAllWindows()
  sys.exit(0)


Written by

No comments:

Post a Comment