Showing posts with label openCV. Show all posts
Showing posts with label openCV. Show all posts

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

Convolution of Two Images - OpenCV - Python

# To convolute two images img1.bmp and img2.bmp

In mathematics and, in particular, functional analysis, convolution is a m-
athematical operation on two functions f and g, producing a third function
that is typically viewed as a modified version of one of the original func-
tions, giving the area overlap between the two functions as a function of 
the amount that one of the original functions is translated.
-Wikipedia


import cv2.cv as cv
import sys

if __name__ == "__main__":
 # Load two images
 im1 = cv.LoadImageM("img1.bmp")
 im2 = cv.LoadImageM("img2.bmp")
 # Create a destination image of the same size that of the source
 dst = cv.CreateImage(cv.GetSize(im1), 8, 3)

 # Create a window named "convolution(1 for colour)"
 cv.NamedWindow("convolution", 1)
 # Convolute the 2 images
 cv.Filter2D(im1, dst, im2)
 # Show the convoluted result
 cv.ShowImage('convolution', dst)

 # Wait for any key press to close the window
 print 'Press any key to quit'
 cv.WaitKey(0)
 # Destroy all created windows and exit
 print 'Exiting...'
 cv.DestroyAllWindows()
 sys.exit(0)


Written by